diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/CapturedLogEvent.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/CapturedLogEvent.scala index eb1775334e..beaa703364 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/CapturedLogEvent.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/CapturedLogEvent.scala @@ -72,8 +72,8 @@ object CapturedLogEvent { * Helper method to convert [[OptionVal]] to [[Option]] */ private def toOption[A](optionVal: OptionVal[A]): Option[A] = optionVal match { - case OptionVal.Some(x) ⇒ Some(x) - case _ ⇒ None + case OptionVal.Some(x) => Some(x) + case _ => None } def apply( diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/Effect.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/Effect.scala index 9731840a05..b9abde688c 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/Effect.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/Effect.scala @@ -32,11 +32,11 @@ object Effect { extends Effect with Product3[Behavior[T], String, Props] with Serializable { override def equals(other: Any) = other match { - case o: Spawned[_] ⇒ + case o: Spawned[_] => this.behavior == o.behavior && this.childName == o.childName && this.props == o.props - case _ ⇒ false + case _ => false } override def hashCode: Int = (behavior.## * 31 + childName.##) * 31 + props.## override def toString: String = s"Spawned($behavior, $childName, $props)" @@ -60,8 +60,8 @@ object Effect { extends Effect with Product2[Behavior[T], Props] with Serializable { override def equals(other: Any) = other match { - case o: SpawnedAnonymous[_] ⇒ this.behavior == o.behavior && this.props == o.props - case _ ⇒ false + case o: SpawnedAnonymous[_] => this.behavior == o.behavior && this.props == o.props + case _ => false } override def hashCode: Int = behavior.## * 31 + props.## override def toString: String = s"SpawnedAnonymous($behavior, $props)" @@ -86,8 +86,8 @@ object Effect { extends Effect with Product1[String] with Serializable { override def equals(other: Any) = other match { - case o: SpawnedAdapter[_] ⇒ this.name == o.name - case _ ⇒ false + case o: SpawnedAdapter[_] => this.name == o.name + case _ => false } override def hashCode: Int = name.## override def toString: String = s"SpawnedAdapter($name)" @@ -116,8 +116,8 @@ object Effect { extends Effect with Product with Serializable { override def equals(other: Any): Boolean = other match { - case _: SpawnedAnonymousAdapter[_] ⇒ true - case _ ⇒ false + case _: SpawnedAnonymousAdapter[_] => true + case _ => false } override def hashCode: Int = Nil.## override def toString: String = "SpawnedAnonymousAdapter" @@ -141,7 +141,7 @@ object Effect { /** * The behavior create a message adapter for the messages of type clazz */ - final case class MessageAdapter[A, T](messageClass: Class[A], adapt: A ⇒ T) extends Effect { + final case class MessageAdapter[A, T](messageClass: Class[A], adapt: A => T) extends Effect { /** * JAVA API */ diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/TestKitSettings.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/TestKitSettings.scala index 3ba887c0ca..8791648598 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/TestKitSettings.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/TestKitSettings.scala @@ -44,7 +44,7 @@ final class TestKitSettings(val config: Config) { import akka.util.Helpers._ val TestTimeFactor = config.getDouble("timefactor"). - requiring(tf ⇒ !tf.isInfinite && tf > 0, "timefactor must be positive finite double") + requiring(tf => !tf.isInfinite && tf > 0, "timefactor must be positive finite double") /** dilated with `TestTimeFactor` */ val SingleExpectDefaultTimeout: FiniteDuration = dilated(config.getMillisDuration("single-expect-default")) diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/ActorSystemStub.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/ActorSystemStub.scala index 4915c689a3..b87c78d725 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/ActorSystemStub.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/ActorSystemStub.scala @@ -10,7 +10,7 @@ import akka.actor.typed.internal.ActorRefImpl import akka.actor.typed.{ ActorRef, ActorSystem, Behavior, DispatcherSelector, Dispatchers, Extension, ExtensionId, Logger, Props, Settings, Terminated } import akka.annotation.InternalApi import akka.util.Timeout -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } import com.typesafe.config.ConfigFactory import scala.compat.java8.FutureConverters import scala.concurrent._ diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/BehaviorTestKitImpl.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/BehaviorTestKitImpl.scala index 57a29b647d..cbc0fda8aa 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/BehaviorTestKitImpl.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/BehaviorTestKitImpl.scala @@ -39,8 +39,8 @@ private[akka] final class BehaviorTestKitImpl[T](_path: ActorPath, _initialBehav runAllTasks() override def retrieveEffect(): Effect = context.effectQueue.poll() match { - case null ⇒ NoEffects - case x ⇒ x + case null => NoEffects + case x => x } override def childInbox[U](name: String): TestInboxImpl[U] = { @@ -58,8 +58,8 @@ private[akka] final class BehaviorTestKitImpl[T](_path: ActorPath, _initialBehav override def retrieveAllEffects(): immutable.Seq[Effect] = { @tailrec def rec(acc: List[Effect]): List[Effect] = context.effectQueue.poll() match { - case null ⇒ acc.reverse - case x ⇒ rec(x :: acc) + case null => acc.reverse + case x => rec(x :: acc) } rec(Nil) @@ -71,27 +71,27 @@ private[akka] final class BehaviorTestKitImpl[T](_path: ActorPath, _initialBehav override def expectEffect(expectedEffect: Effect): Unit = { context.effectQueue.poll() match { - case null ⇒ assert(expectedEffect == NoEffects, s"expected: $expectedEffect but no effects were recorded") - case effect ⇒ assert(expectedEffect == effect, s"expected: $expectedEffect but found $effect") + case null => assert(expectedEffect == NoEffects, s"expected: $expectedEffect but no effects were recorded") + case effect => assert(expectedEffect == effect, s"expected: $expectedEffect but found $effect") } } def expectEffectClass[E <: Effect](effectClass: Class[E]): E = { context.effectQueue.poll() match { - case null if effectClass.isAssignableFrom(NoEffects.getClass) ⇒ effectClass.cast(NoEffects) - case null ⇒ throw new AssertionError(s"expected: effect type ${effectClass.getName} but no effects were recorded") - case effect if effectClass.isAssignableFrom(effect.getClass) ⇒ effect.asInstanceOf[E] - case other ⇒ throw new AssertionError(s"expected: effect class ${effectClass.getName} but found $other") + case null if effectClass.isAssignableFrom(NoEffects.getClass) => effectClass.cast(NoEffects) + case null => throw new AssertionError(s"expected: effect type ${effectClass.getName} but no effects were recorded") + case effect if effectClass.isAssignableFrom(effect.getClass) => effect.asInstanceOf[E] + case other => throw new AssertionError(s"expected: effect class ${effectClass.getName} but found $other") } } def expectEffectPF[R](f: PartialFunction[Effect, R]): R = { context.effectQueue.poll() match { - case null if f.isDefinedAt(NoEffects) ⇒ + case null if f.isDefinedAt(NoEffects) => f.apply(NoEffects) - case eff if f.isDefinedAt(eff) ⇒ + case eff if f.isDefinedAt(eff) => f.apply(eff) - case other ⇒ + case other => throw new AssertionError(s"expected matching effect but got: $other") } } @@ -104,18 +104,18 @@ private[akka] final class BehaviorTestKitImpl[T](_path: ActorPath, _initialBehav def isAlive: Boolean = Behavior.isAlive(current) private def handleException: Catcher[Unit] = { - case NonFatal(e) ⇒ + case NonFatal(e) => try Behavior.canonicalize(Behavior.interpretSignal(current, context, PostStop), current, context) // TODO why canonicalize here? catch { - case NonFatal(_) ⇒ /* ignore, real is logging */ + case NonFatal(_) => /* ignore, real is logging */ } throw e } private def runAllTasks(): Unit = { context.executionContext match { - case controlled: ControlledExecutor ⇒ controlled.runAll() - case _ ⇒ + case controlled: ControlledExecutor => controlled.runAll() + case _ => } } diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/DebugRef.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/DebugRef.scala index 8210321a3c..6dd84179bd 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/DebugRef.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/DebugRef.scala @@ -9,7 +9,7 @@ import java.util.concurrent.ConcurrentLinkedQueue import akka.actor.typed.ActorRef import akka.actor.typed.internal.{ ActorRefImpl, SystemMessage } import akka.annotation.InternalApi -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } import scala.annotation.tailrec import akka.actor.ActorRefProvider @@ -27,36 +27,36 @@ import akka.actor.typed.internal.InternalRecipientRef override def sendSystem(signal: SystemMessage): Unit = q.add(Left(signal)) def hasMessage: Boolean = q.peek match { - case null ⇒ false - case Left(_) ⇒ false - case Right(_) ⇒ true + case null => false + case Left(_) => false + case Right(_) => true } def hasSignal: Boolean = q.peek match { - case null ⇒ false - case Left(_) ⇒ true - case Right(_) ⇒ false + case null => false + case Left(_) => true + case Right(_) => false } def hasSomething: Boolean = q.peek != null def receiveMessage(): T = q.poll match { - case null ⇒ throw new NoSuchElementException("empty DebugRef") - case Left(signal) ⇒ throw new IllegalStateException(s"expected message but found signal $signal") - case Right(message) ⇒ message + case null => throw new NoSuchElementException("empty DebugRef") + case Left(signal) => throw new IllegalStateException(s"expected message but found signal $signal") + case Right(message) => message } def receiveSignal(): SystemMessage = q.poll match { - case null ⇒ throw new NoSuchElementException("empty DebugRef") - case Left(signal) ⇒ signal - case Right(message) ⇒ throw new IllegalStateException(s"expected signal but found message $message") + case null => throw new NoSuchElementException("empty DebugRef") + case Left(signal) => signal + case Right(message) => throw new IllegalStateException(s"expected signal but found message $message") } def receiveAll(): List[Either[SystemMessage, T]] = { @tailrec def rec(acc: List[Either[SystemMessage, T]]): List[Either[SystemMessage, T]] = q.poll match { - case null ⇒ acc.reverse - case other ⇒ rec(other :: acc) + case null => acc.reverse + case other => rec(other :: acc) } rec(Nil) } diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/EffectfulActorContext.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/EffectfulActorContext.scala index 3d426152c6..5c49571a13 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/EffectfulActorContext.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/EffectfulActorContext.scala @@ -29,17 +29,17 @@ import scala.compat.java8.FunctionConverters._ effectQueue.offer(new SpawnedAnonymous(behavior, props, ref)) ref } - override def spawnMessageAdapter[U](f: U ⇒ T): ActorRef[U] = { + override def spawnMessageAdapter[U](f: U => T): ActorRef[U] = { val ref = super.spawnMessageAdapter(f) effectQueue.offer(new SpawnedAnonymousAdapter(ref)) ref } - override def spawnMessageAdapter[U](f: U ⇒ T, name: String): ActorRef[U] = { + override def spawnMessageAdapter[U](f: U => T, name: String): ActorRef[U] = { val ref = super.spawnMessageAdapter(f, name) effectQueue.offer(new SpawnedAdapter(name, ref)) ref } - override def messageAdapter[U: ClassTag](f: U ⇒ T): ActorRef[U] = { + override def messageAdapter[U: ClassTag](f: U => T): ActorRef[U] = { val ref = super.messageAdapter(f) effectQueue.offer(MessageAdapter(implicitly[ClassTag[U]].runtimeClass.asInstanceOf[Class[U]], f)) ref diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/StubbedActorContext.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/StubbedActorContext.scala index 1b9b7344e2..60ac760a3a 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/StubbedActorContext.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/StubbedActorContext.scala @@ -13,8 +13,8 @@ import akka.actor.{ ActorPath, InvalidMessageException } import akka.annotation.InternalApi import akka.event.Logging import akka.util.{ Helpers, OptionVal } -import akka.{ actor ⇒ untyped } -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ rnd } +import akka.{ actor => untyped } +import java.util.concurrent.ThreadLocalRandom.{ current => rnd } import scala.collection.immutable.TreeMap import scala.concurrent.ExecutionContextExecutor @@ -31,7 +31,7 @@ import akka.actor.ActorRefProvider @InternalApi private[akka] final class FunctionRef[-T]( override val path: ActorPath, - send: (T, FunctionRef[T]) ⇒ Unit) + send: (T, FunctionRef[T]) => Unit) extends ActorRef[T] with ActorRefImpl[T] with InternalRecipientRef[T] { override def tell(message: T): Unit = { @@ -172,15 +172,15 @@ private[akka] final class FunctionRef[-T]( override def spawnAnonymous[U](behavior: Behavior[U], props: Props = Props.empty): ActorRef[U] = { val btk = new BehaviorTestKitImpl[U](path / childName.next() withUid rnd().nextInt(), behavior) - _children += btk.context.self.path.name → btk + _children += btk.context.self.path.name -> btk btk.context.self } override def spawn[U](behavior: Behavior[U], name: String, props: Props = Props.empty): ActorRef[U] = _children get name match { - case Some(_) ⇒ throw untyped.InvalidActorNameException(s"actor name $name is already taken") - case None ⇒ + case Some(_) => throw untyped.InvalidActorNameException(s"actor name $name is already taken") + case None => val btk = new BehaviorTestKitImpl[U](path / name withUid rnd().nextInt(), behavior) - _children += name → btk + _children += name -> btk btk.context.self } @@ -214,16 +214,16 @@ private[akka] final class FunctionRef[-T]( /** * INTERNAL API */ - @InternalApi private[akka] def internalSpawnMessageAdapter[U](f: U ⇒ T, name: String): ActorRef[U] = { + @InternalApi private[akka] def internalSpawnMessageAdapter[U](f: U => T, name: String): ActorRef[U] = { val n = if (name != "") s"${childName.next()}-$name" else childName.next() val p = path / n withUid rnd().nextInt() val i = new BehaviorTestKitImpl[U](p, Behavior.ignore) - _children += p.name → i + _children += p.name -> i new FunctionRef[U]( p, - (message, _) ⇒ { val m = f(message); if (m != null) { selfInbox.ref ! m; i.selfInbox.ref ! message } }) + (message, _) => { val m = f(message); if (m != null) { selfInbox.ref ! m; i.selfInbox.ref ! message } }) } /** diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestInboxImpl.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestInboxImpl.scala index 61ac88affa..ed4791ee0b 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestInboxImpl.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestInboxImpl.scala @@ -23,26 +23,26 @@ private[akka] final class TestInboxImpl[T](path: ActorPath) private val q = new ConcurrentLinkedQueue[T] - override val ref: ActorRef[T] = new FunctionRef[T](path, (message, self) ⇒ q.add(message)) + override val ref: ActorRef[T] = new FunctionRef[T](path, (message, self) => q.add(message)) override def getRef() = ref override def receiveMessage(): T = q.poll() match { - case null ⇒ throw new NoSuchElementException(s"polling on an empty inbox: $path") - case x ⇒ x + case null => throw new NoSuchElementException(s"polling on an empty inbox: $path") + case x => x } override def expectMessage(expectedMessage: T): TestInboxImpl[T] = { q.poll() match { - case null ⇒ assert(assertion = false, s"expected message: $expectedMessage but no messages were received") - case message ⇒ assert(message == expectedMessage, s"expected: $expectedMessage but received $message") + case null => assert(assertion = false, s"expected message: $expectedMessage but no messages were received") + case message => assert(message == expectedMessage, s"expected: $expectedMessage but received $message") } this } override protected def internalReceiveAll(): immutable.Seq[T] = { @tailrec def rec(acc: List[T]): List[T] = q.poll() match { - case null ⇒ acc.reverse - case x ⇒ rec(x :: acc) + case null => acc.reverse + case x => rec(x :: acc) } rec(Nil) diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestKitUtils.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestKitUtils.scala index 6a382c98a9..8f887a3a4d 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestKitUtils.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestKitUtils.scala @@ -26,17 +26,17 @@ private[akka] object ActorTestKitGuardian { final case object Ack val testKitGuardian: Behavior[TestKitCommand] = Behaviors.receive[TestKitCommand] { - case (context, SpawnActor(name, behavior, reply, props)) ⇒ + case (context, SpawnActor(name, behavior, reply, props)) => reply ! context.spawn(behavior, name, props) Behaviors.same - case (context, SpawnActorAnonymous(behavior, reply, props)) ⇒ + case (context, SpawnActorAnonymous(behavior, reply, props)) => reply ! context.spawnAnonymous(behavior, props) Behaviors.same - case (context, StopActor(ref, reply)) ⇒ + case (context, StopActor(ref, reply)) => context.watchWith(ref, ActorStopped(reply)) context.stop(ref) Behaviors.same - case (_, ActorStopped(reply)) ⇒ + case (_, ActorStopped(reply)) => reply ! Ack Behaviors.same } @@ -57,7 +57,7 @@ private[akka] object TestKitUtils { try { Modifier.isAbstract(Class.forName(className).getModifiers) } catch { - case _: Throwable ⇒ false // yes catch everything, best effort check + case _: Throwable => false // yes catch everything, best effort check } } @@ -68,11 +68,11 @@ private[akka] object TestKitUtils { .dropWhile(!_.startsWith(startFrom)) // then continue to the next entry after classToStartFrom that makes sense .dropWhile { - case `startFrom` ⇒ true - case str if str.startsWith(startFrom + "$") ⇒ true // lambdas inside startFrom etc - case TestKitRegex() ⇒ true // testkit internals - case str if isAbstractClass(str) ⇒ true - case _ ⇒ false + case `startFrom` => true + case str if str.startsWith(startFrom + "$") => true // lambdas inside startFrom etc + case TestKitRegex() => true // testkit internals + case str if isAbstractClass(str) => true + case _ => false } if (filteredStack.isEmpty) @@ -100,7 +100,7 @@ private[akka] object TestKitUtils { throwIfShutdownTimesOut: Boolean): Unit = { system.terminate() try Await.ready(system.whenTerminated, timeout) catch { - case _: TimeoutException ⇒ + case _: TimeoutException => val message = "Failed to stop [%s] within [%s] \n%s".format(system.name, timeout, system.printTree) if (throwIfShutdownTimesOut) throw new RuntimeException(message) else println(message) diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestProbeImpl.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestProbeImpl.scala index 3d2bc8edae..76d7c55c46 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestProbeImpl.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/internal/TestProbeImpl.scala @@ -4,12 +4,12 @@ package akka.actor.testkit.typed.internal -import java.time.{ Duration ⇒ JDuration } +import java.time.{ Duration => JDuration } import java.util.concurrent.BlockingDeque import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.atomic.AtomicInteger import java.util.function.Supplier -import java.util.{ List ⇒ JList } +import java.util.{ List => JList } import scala.annotation.tailrec import scala.collection.JavaConverters._ @@ -21,9 +21,9 @@ import scala.util.control.NonFatal import akka.actor.testkit.typed.FishingOutcome import akka.actor.testkit.typed.TestKitSettings -import akka.actor.testkit.typed.javadsl.{ TestProbe ⇒ JavaTestProbe } +import akka.actor.testkit.typed.javadsl.{ TestProbe => JavaTestProbe } import akka.actor.testkit.typed.scaladsl.TestDuration -import akka.actor.testkit.typed.scaladsl.{ TestProbe ⇒ ScalaTestProbe } +import akka.actor.testkit.typed.scaladsl.{ TestProbe => ScalaTestProbe } import akka.actor.typed.ActorRef import akka.actor.typed.ActorSystem import akka.actor.typed.Behavior @@ -43,19 +43,19 @@ private[akka] object TestProbeImpl { private case object Stop private def testActor[M](queue: BlockingDeque[M], terminations: BlockingDeque[Terminated]): Behavior[M] = - Behaviors.receive[M] { (context, msg) ⇒ + Behaviors.receive[M] { (context, msg) => msg match { - case WatchActor(ref) ⇒ + case WatchActor(ref) => context.watch(ref) Behaviors.same - case Stop ⇒ + case Stop => Behaviors.stopped - case other ⇒ + case other => queue.offerLast(other) Behaviors.same } }.receiveSignal { - case (_, t: Terminated) ⇒ + case (_, t: Terminated) => terminations.offerLast(t) Behaviors.same } @@ -91,25 +91,25 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) override def getRemainingOrDefault: JDuration = remainingOrDefault.asJava override def remaining: FiniteDuration = end match { - case f: FiniteDuration ⇒ f - now - case _ ⇒ assertFail("`remaining` may not be called outside of `within`") + case f: FiniteDuration => f - now + case _ => assertFail("`remaining` may not be called outside of `within`") } override def getRemaining: JDuration = remaining.asJava override def remainingOr(duration: FiniteDuration): FiniteDuration = end match { - case x if x eq Duration.Undefined ⇒ duration - case x if !x.isFinite ⇒ throw new IllegalArgumentException("`end` cannot be infinite") - case f: FiniteDuration ⇒ f - now + case x if x eq Duration.Undefined => duration + case x if !x.isFinite => throw new IllegalArgumentException("`end` cannot be infinite") + case f: FiniteDuration => f - now } override def getRemainingOr(duration: JDuration): JDuration = remainingOr(duration.asScala).asJava - override def within[T](min: FiniteDuration, max: FiniteDuration)(f: ⇒ T): T = + override def within[T](min: FiniteDuration, max: FiniteDuration)(f: => T): T = within_internal(min, max.dilated, f) - override def within[T](max: FiniteDuration)(f: ⇒ T): T = + override def within[T](max: FiniteDuration)(f: => T): T = within_internal(Duration.Zero, max.dilated, f) override def within[T](min: JDuration, max: JDuration)(f: Supplier[T]): T = @@ -118,7 +118,7 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) def within[T](max: JDuration)(f: Supplier[T]): T = within_internal(Duration.Zero, max.asScala.dilated, f.get()) - private def within_internal[T](min: FiniteDuration, max: FiniteDuration, f: ⇒ T): T = { + private def within_internal[T](min: FiniteDuration, max: FiniteDuration, f: => T): T = { val start = now val rem = if (end == Duration.Undefined) Duration.Inf else end - start assert(rem >= min, s"required min time $min not possible, only ${rem.pretty} left") @@ -157,9 +157,9 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) val o = receiveOne_internal(max) val hintOrEmptyString = hint.map(": " + _).getOrElse("") o match { - case Some(m) if obj == m ⇒ m.asInstanceOf[T] - case Some(m) ⇒ assertFail(s"expected $obj, found $m$hintOrEmptyString") - case None ⇒ assertFail(s"timeout ($max) during expectMessage while waiting for $obj$hintOrEmptyString") + case Some(m) if obj == m => m.asInstanceOf[T] + case Some(m) => assertFail(s"expected $obj, found $m$hintOrEmptyString") + case None => assertFail(s"timeout ($max) during expectMessage while waiting for $obj$hintOrEmptyString") } } @@ -203,8 +203,8 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) private def expectNoMessage_internal(max: FiniteDuration): Unit = { val o = receiveOne_internal(max) o match { - case None ⇒ lastWasNoMessage = true - case Some(m) ⇒ assertFail(s"Received unexpected message $m") + case None => lastWasNoMessage = true + case Some(m) => assertFail(s"Received unexpected message $m") } } @@ -224,9 +224,9 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) val o = receiveOne_internal(max) val bt = BoxedType(c) o match { - case Some(m) if bt isInstance m ⇒ m.asInstanceOf[C] - case Some(m) ⇒ assertFail(s"Expected $c, found ${m.getClass} ($m)") - case None ⇒ assertFail(s"Timeout ($max) during expectMessageClass waiting for $c") + case Some(m) if bt isInstance m => m.asInstanceOf[C] + case Some(m) => assertFail(s"Expected $c, found ${m.getClass} ($m)") + case None => assertFail(s"Timeout ($max) during expectMessageClass waiting for $c") } } @@ -244,20 +244,20 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) private def receiveMessages_internal(n: Int, max: FiniteDuration): immutable.Seq[M] = { val stop = max + now - for (x ← 1 to n) yield { + for (x <- 1 to n) yield { val timeout = stop - now val o = receiveOne_internal(timeout) o match { - case Some(m) ⇒ m - case None ⇒ assertFail(s"timeout ($max) while expecting $n messages (got ${x - 1})") + case Some(m) => m + case None => assertFail(s"timeout ($max) while expecting $n messages (got ${x - 1})") } } } - override def fishForMessage(max: FiniteDuration, hint: String)(fisher: M ⇒ FishingOutcome): immutable.Seq[M] = + override def fishForMessage(max: FiniteDuration, hint: String)(fisher: M => FishingOutcome): immutable.Seq[M] = fishForMessage_internal(max.dilated, hint, fisher) - override def fishForMessage(max: FiniteDuration)(fisher: M ⇒ FishingOutcome): immutable.Seq[M] = + override def fishForMessage(max: FiniteDuration)(fisher: M => FishingOutcome): immutable.Seq[M] = fishForMessage(max, "")(fisher) override def fishForMessage(max: JDuration, fisher: java.util.function.Function[M, FishingOutcome]): JList[M] = @@ -266,29 +266,29 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) override def fishForMessage(max: JDuration, hint: String, fisher: java.util.function.Function[M, FishingOutcome]): JList[M] = fishForMessage_internal(max.asScala.dilated, hint, fisher.apply).asJava - private def fishForMessage_internal(max: FiniteDuration, hint: String, fisher: M ⇒ FishingOutcome): List[M] = { + private def fishForMessage_internal(max: FiniteDuration, hint: String, fisher: M => FishingOutcome): List[M] = { @tailrec def loop(timeout: FiniteDuration, seen: List[M]): List[M] = { val start = System.nanoTime() val maybeMsg = receiveOne_internal(timeout) maybeMsg match { - case Some(message) ⇒ + case Some(message) => val outcome = try fisher(message) catch { - case ex: MatchError ⇒ throw new AssertionError( + case ex: MatchError => throw new AssertionError( s"Unexpected message $message while fishing for messages, " + s"seen messages ${seen.reverse}, hint: $hint", ex) } outcome match { - case FishingOutcome.Complete ⇒ (message :: seen).reverse - case FishingOutcome.Fail(error) ⇒ assertFail(s"$error, hint: $hint") - case continue: FishingOutcome.ContinueOutcome ⇒ + case FishingOutcome.Complete => (message :: seen).reverse + case FishingOutcome.Fail(error) => assertFail(s"$error, hint: $hint") + case continue: FishingOutcome.ContinueOutcome => val newTimeout = timeout - (System.nanoTime() - start).nanos continue match { - case FishingOutcome.Continue ⇒ loop(newTimeout, message :: seen) - case FishingOutcome.ContinueAndIgnore ⇒ loop(newTimeout, seen) + case FishingOutcome.Continue => loop(newTimeout, message :: seen) + case FishingOutcome.ContinueAndIgnore => loop(newTimeout, seen) } } - case None ⇒ + case None => assertFail(s"timeout ($max) during fishForMessage, seen messages ${seen.reverse}, hint: $hint") } } @@ -319,13 +319,13 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) assert(message.ref == actorRef, s"expected [${actorRef.path}] to stop, but saw [${message.ref.path}] stop") } - override def awaitAssert[A](a: ⇒ A, max: FiniteDuration, interval: FiniteDuration): A = + override def awaitAssert[A](a: => A, max: FiniteDuration, interval: FiniteDuration): A = awaitAssert_internal(a, max.dilated, interval) - override def awaitAssert[A](a: ⇒ A, max: FiniteDuration): A = + override def awaitAssert[A](a: => A, max: FiniteDuration): A = awaitAssert_internal(a, max.dilated, 100.millis) - override def awaitAssert[A](a: ⇒ A): A = + override def awaitAssert[A](a: => A): A = awaitAssert_internal(a, remainingOrDefault, 100.millis) override def awaitAssert[A](max: JDuration, interval: JDuration, supplier: Supplier[A]): A = @@ -337,7 +337,7 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) def awaitAssert[A](supplier: Supplier[A]): A = awaitAssert(getRemainingOrDefault, supplier) - private def awaitAssert_internal[A](a: ⇒ A, max: FiniteDuration, interval: FiniteDuration): A = { + private def awaitAssert_internal[A](a: => A, max: FiniteDuration, interval: FiniteDuration): A = { val stop = now + max @tailrec @@ -351,7 +351,7 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_]) failed = false aRes } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => failed = true if ((now + t) >= stop) throw e else null.asInstanceOf[A] diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/javadsl/ManualTime.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/javadsl/ManualTime.scala index 567d86bd89..bd3aab818e 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/javadsl/ManualTime.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/javadsl/ManualTime.scala @@ -29,8 +29,8 @@ object ManualTime { */ def get[A](system: ActorSystem[A]): ManualTime = system.scheduler match { - case sc: akka.testkit.ExplicitlyTriggeredScheduler ⇒ new ManualTime(sc) - case _ ⇒ throw new IllegalArgumentException("ActorSystem not configured with explicitly triggered scheduler, " + + case sc: akka.testkit.ExplicitlyTriggeredScheduler => new ManualTime(sc) + case _ => throw new IllegalArgumentException("ActorSystem not configured with explicitly triggered scheduler, " + "make sure to include akka.actor.testkit.typed.javadsl.ManualTime.config() when setting up the test") } diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/javadsl/TestProbe.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/javadsl/TestProbe.scala index 0415c8356c..a2377cd682 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/javadsl/TestProbe.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/javadsl/TestProbe.scala @@ -6,7 +6,7 @@ package akka.actor.testkit.typed.javadsl import java.time.Duration import java.util.function.Supplier -import java.util.{ List ⇒ JList } +import java.util.{ List => JList } import akka.actor.testkit.typed.FishingOutcome import akka.actor.testkit.typed.TestKitSettings diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/ActorTestKit.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/ActorTestKit.scala index 4adf44f623..c1b96cc9d1 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/ActorTestKit.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/ActorTestKit.scala @@ -181,9 +181,9 @@ final class ActorTestKit private[akka] (val name: String, val config: Config, se * Other actors will not be stopped by this method. */ def stop[T](ref: ActorRef[T], max: FiniteDuration = timeout.duration): Unit = try { - Await.result(internalSystem.ask { x: ActorRef[ActorTestKitGuardian.Ack.type] ⇒ ActorTestKitGuardian.StopActor(ref, x) }, max) + Await.result(internalSystem.ask { x: ActorRef[ActorTestKitGuardian.Ack.type] => ActorTestKitGuardian.StopActor(ref, x) }, max) } catch { - case _: TimeoutException ⇒ + case _: TimeoutException => assert(false, s"timeout ($max) during stop() waiting for actor [${ref.path}] to stop") } diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/ManualTime.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/ManualTime.scala index 5faaeb08d0..893ed2c6b2 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/ManualTime.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/ManualTime.scala @@ -28,8 +28,8 @@ object ManualTime { */ def apply()(implicit system: ActorSystem[_]): ManualTime = system.scheduler match { - case sc: akka.testkit.ExplicitlyTriggeredScheduler ⇒ new ManualTime(sc) - case _ ⇒ throw new IllegalArgumentException("ActorSystem not configured with explicitly triggered scheduler, " + + case sc: akka.testkit.ExplicitlyTriggeredScheduler => new ManualTime(sc) + case _ => throw new IllegalArgumentException("ActorSystem not configured with explicitly triggered scheduler, " + "make sure to include akka.actor.testkit.typed.scaladsl.ManualTime.config() when setting up the test") } diff --git a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/TestProbe.scala b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/TestProbe.scala index 904f8c5b14..7f73733db5 100644 --- a/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/TestProbe.scala +++ b/akka-actor-testkit-typed/src/main/scala/akka/actor/testkit/typed/scaladsl/TestProbe.scala @@ -96,12 +96,12 @@ object TestProbe { * } * }}} */ - def within[T](min: FiniteDuration, max: FiniteDuration)(f: ⇒ T): T + def within[T](min: FiniteDuration, max: FiniteDuration)(f: => T): T /** * Same as calling `within(0 seconds, max)(f)`. */ - def within[T](max: FiniteDuration)(f: ⇒ T): T + def within[T](max: FiniteDuration)(f: => T): T /** * Same as `expectMessage(remainingOrDefault, obj)`, but using the default timeout as deadline. @@ -189,12 +189,12 @@ object TestProbe { * The timeout is scaled using the configuration entry "akka.actor.testkit.typed.timefactor". * @return The messages accepted in the order they arrived */ - def fishForMessage(max: FiniteDuration, hint: String)(fisher: M ⇒ FishingOutcome): immutable.Seq[M] + def fishForMessage(max: FiniteDuration, hint: String)(fisher: M => FishingOutcome): immutable.Seq[M] /** * Same as the other `fishForMessage` but with no hint */ - def fishForMessage(max: FiniteDuration)(fisher: M ⇒ FishingOutcome): immutable.Seq[M] + def fishForMessage(max: FiniteDuration)(fisher: M => FishingOutcome): immutable.Seq[M] /** * Expect the given actor to be stopped or stop within the given timeout or @@ -215,7 +215,7 @@ object TestProbe { * * Note that the timeout is scaled using the configuration entry "akka.actor.testkit.typed.timefactor". */ - def awaitAssert[A](a: ⇒ A, max: FiniteDuration, interval: FiniteDuration): A + def awaitAssert[A](a: => A, max: FiniteDuration, interval: FiniteDuration): A /** * Evaluate the given assert every 100 ms until it does not throw an exception and return the @@ -223,7 +223,7 @@ object TestProbe { * * If the `max` timeout expires the last exception is thrown. */ - def awaitAssert[A](a: ⇒ A, max: FiniteDuration): A + def awaitAssert[A](a: => A, max: FiniteDuration): A /** * Evaluate the given assert every 100 ms until it does not throw an exception and return the @@ -231,7 +231,7 @@ object TestProbe { * * If the default timeout expires the last exception is thrown. */ - def awaitAssert[A](a: ⇒ A): A + def awaitAssert[A](a: => A): A /** * Stops the [[TestProbe.ref]], which is useful when testing watch and termination. diff --git a/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/ActorTestKitSpec.scala b/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/ActorTestKitSpec.scala index 443bbd084f..8c677a5659 100644 --- a/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/ActorTestKitSpec.scala +++ b/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/ActorTestKitSpec.scala @@ -40,7 +40,7 @@ class ActorTestKitSpec extends ScalaTestWithActorTestKit with WordSpecLike { "spawn an actor" in { val sawMessage = Promise[Boolean]() - val ref = spawn(Behaviors.setup[AnyRef] { context ⇒ + val ref = spawn(Behaviors.setup[AnyRef] { context => sawMessage.trySuccess(true) Behaviors.empty }) @@ -50,7 +50,7 @@ class ActorTestKitSpec extends ScalaTestWithActorTestKit with WordSpecLike { "spawn a named actor" in { val spawnedWithName = Promise[String]() - val ref = spawn(Behaviors.setup[AnyRef] { context ⇒ + val ref = spawn(Behaviors.setup[AnyRef] { context => spawnedWithName.trySuccess(context.self.path.name) Behaviors.empty }, "name") diff --git a/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala b/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala index ce34ea058f..8895bbd396 100644 --- a/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala +++ b/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala @@ -31,75 +31,75 @@ object BehaviorTestKitSpec { case class StopChild(child: ActorRef[String]) extends Command case object SpawnAdapter extends Command case class SpawnAdapterWithName(name: String) extends Command - case class CreateMessageAdapter[U](messageClass: Class[U], f: U ⇒ Command) extends Command + case class CreateMessageAdapter[U](messageClass: Class[U], f: U => Command) extends Command case class SpawnAndWatchUnwatch(name: String) extends Command case class SpawnAndWatchWith(name: String) extends Command case class SpawnSession(replyTo: ActorRef[ActorRef[String]], sessionHandler: ActorRef[String]) extends Command case class KillSession(session: ActorRef[String], replyTo: ActorRef[Done]) extends Command case class Log(what: String) extends Command - val init: Behavior[Command] = Behaviors.receive[Command] { (context, message) ⇒ + val init: Behavior[Command] = Behaviors.receive[Command] { (context, message) => message match { - case SpawnChild ⇒ + case SpawnChild => context.spawn(Child.initial, "child") Behaviors.same - case SpawnChildren(numberOfChildren) if numberOfChildren > 0 ⇒ - 0.until(numberOfChildren).foreach { i ⇒ + case SpawnChildren(numberOfChildren) if numberOfChildren > 0 => + 0.until(numberOfChildren).foreach { i => context.spawn(Child.initial, s"child$i") } Behaviors.same - case SpawnChildrenWithProps(numberOfChildren, props) if numberOfChildren > 0 ⇒ - 0.until(numberOfChildren).foreach { i ⇒ + case SpawnChildrenWithProps(numberOfChildren, props) if numberOfChildren > 0 => + 0.until(numberOfChildren).foreach { i => context.spawn(Child.initial, s"child$i", props) } Behaviors.same - case SpawnAnonymous(numberOfChildren) if numberOfChildren > 0 ⇒ - 0.until(numberOfChildren).foreach { _ ⇒ + case SpawnAnonymous(numberOfChildren) if numberOfChildren > 0 => + 0.until(numberOfChildren).foreach { _ => context.spawnAnonymous(Child.initial) } Behaviors.same - case SpawnAnonymousWithProps(numberOfChildren, props) if numberOfChildren > 0 ⇒ - 0.until(numberOfChildren).foreach { _ ⇒ + case SpawnAnonymousWithProps(numberOfChildren, props) if numberOfChildren > 0 => + 0.until(numberOfChildren).foreach { _ => context.spawnAnonymous(Child.initial, props) } Behaviors.same - case StopChild(child) ⇒ + case StopChild(child) => context.stop(child) Behaviors.same - case SpawnAdapter ⇒ + case SpawnAdapter => context.spawnMessageAdapter { - r: Reproduce ⇒ SpawnAnonymous(r.times) + r: Reproduce => SpawnAnonymous(r.times) } Behaviors.same - case SpawnAdapterWithName(name) ⇒ + case SpawnAdapterWithName(name) => context.spawnMessageAdapter({ - r: Reproduce ⇒ SpawnAnonymous(r.times) + r: Reproduce => SpawnAnonymous(r.times) }, name) Behaviors.same - case SpawnAndWatchUnwatch(name) ⇒ + case SpawnAndWatchUnwatch(name) => val c = context.spawn(Child.initial, name) context.watch(c) context.unwatch(c) Behaviors.same - case m @ SpawnAndWatchWith(name) ⇒ + case m @ SpawnAndWatchWith(name) => val c = context.spawn(Child.initial, name) context.watchWith(c, m) Behaviors.same - case SpawnSession(replyTo, sessionHandler) ⇒ - val session = context.spawnAnonymous[String](Behaviors.receiveMessage { message ⇒ + case SpawnSession(replyTo, sessionHandler) => + val session = context.spawnAnonymous[String](Behaviors.receiveMessage { message => sessionHandler ! message Behavior.same }) replyTo ! session Behaviors.same - case KillSession(session, replyTo) ⇒ + case KillSession(session, replyTo) => context.stop(session) replyTo ! Done Behaviors.same - case CreateMessageAdapter(messageClass, f) ⇒ + case CreateMessageAdapter(messageClass, f) => context.messageAdapter(f)(ClassTag(messageClass)) Behaviors.same - case Log(what) ⇒ + case Log(what) => context.log.info(what) Behaviors.same } @@ -110,9 +110,9 @@ object BehaviorTestKitSpec { sealed trait Action - val initial: Behavior[Action] = Behaviors.receive[Action] { (_, message) ⇒ + val initial: Behavior[Action] = Behaviors.receive[Action] { (_, message) => message match { - case _ ⇒ + case _ => Behaviors.empty } } @@ -156,7 +156,7 @@ class BehaviorTestKitSpec extends WordSpec with Matchers { testkit.run(SpawnChildren(1)) val ae = intercept[AssertionError] { testkit.expectEffectPF { - case SpawnedAnonymous(_, _) ⇒ + case SpawnedAnonymous(_, _) => } } ae.getMessage should startWith("expected matching effect but got: ") @@ -166,7 +166,7 @@ class BehaviorTestKitSpec extends WordSpec with Matchers { val testkit = BehaviorTestKit[Father.Command](Father.init) testkit.run(SpawnChildren(1)) val childName = testkit.expectEffectPF { - case Spawned(_, name, _) ⇒ name + case Spawned(_, name, _) => name } childName should ===("child0") } @@ -174,7 +174,7 @@ class BehaviorTestKitSpec extends WordSpec with Matchers { "allow assertions using partial functions - match on NoEffect" in { val testkit = BehaviorTestKit[Father.Command](Father.init) val hasEffects = testkit.expectEffectPF { - case NoEffects ⇒ false + case NoEffects => false } hasEffects should ===(false) } @@ -248,7 +248,7 @@ class BehaviorTestKitSpec extends WordSpec with Matchers { "BehaviorTestkit's messageAdapter" must { "create message adapters and record effects" in { val testkit = BehaviorTestKit[Father.Command](Father.init) - testkit.run(CreateMessageAdapter(classOf[String], (_: String) ⇒ SpawnChildren(1))) + testkit.run(CreateMessageAdapter(classOf[String], (_: String) => SpawnChildren(1))) testkit.expectEffectType[MessageAdapter[String, Command]] } } diff --git a/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/TestProbeSpec.scala b/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/TestProbeSpec.scala index 600cbaeaf8..7416bd338e 100644 --- a/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/TestProbeSpec.scala +++ b/akka-actor-testkit-typed/src/test/scala/akka/actor/testkit/typed/scaladsl/TestProbeSpec.scala @@ -17,7 +17,7 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with WordSpecLike { def compileOnlyApiTest(): Unit = { val probe = TestProbe[AnyRef]() probe.fishForMessage(100.millis) { - case _ ⇒ FishingOutcomes.complete + case _ => FishingOutcomes.complete } probe.awaitAssert({ "result" @@ -43,11 +43,11 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with WordSpecLike { "allow probing for actor stop when actor has not stopped yet" in { case object Stop val probe = TestProbe() - val ref = spawn(Behaviors.receive[Stop.type]((context, message) ⇒ - Behaviors.withTimers { (timer) ⇒ + val ref = spawn(Behaviors.receive[Stop.type]((context, message) => + Behaviors.withTimers { (timer) => timer.startSingleTimer("key", Stop, 300.millis) - Behaviors.receive((context, stop) ⇒ + Behaviors.receive((context, stop) => Behaviors.stopped ) } @@ -65,8 +65,8 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with WordSpecLike { probe.ref ! "two" val result = probe.fishForMessage(300.millis) { - case "one" ⇒ FishingOutcomes.continue - case "two" ⇒ FishingOutcomes.complete + case "one" => FishingOutcomes.continue + case "two" => FishingOutcomes.complete } result should ===(List("one", "two")) @@ -81,8 +81,8 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with WordSpecLike { intercept[AssertionError] { probe.fishForMessage(300.millis) { - case "one" ⇒ FishingOutcomes.continue - case "two" ⇒ FishingOutcomes.fail("not the fish I'm looking for") + case "one" => FishingOutcomes.continue + case "two" => FishingOutcomes.fail("not the fish I'm looking for") } } } @@ -91,7 +91,7 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with WordSpecLike { val probe = TestProbe[AnyRef]() assertThrows[AssertionError] { - probe.fishForMessage(100.millis) { _ ⇒ + probe.fishForMessage(100.millis) { _ => Thread.sleep(150) FishingOutcomes.complete } @@ -106,7 +106,7 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with WordSpecLike { intercept[AssertionError] { probe.fishForMessage(300.millis) { - case "one" ⇒ FishingOutcomes.continue + case "one" => FishingOutcomes.continue } } } @@ -118,7 +118,7 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with WordSpecLike { intercept[AssertionError] { probe.fishForMessage(300.millis) { - case "one" ⇒ FishingOutcomes.continue + case "one" => FishingOutcomes.continue } } } @@ -147,7 +147,7 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with WordSpecLike { "allow receiving one message of type TestProbe[M]" in { val probe = createTestProbe[EventT]() - eventsT(10).forall { e ⇒ + eventsT(10).forall { e => probe.ref ! e probe.receiveMessage == e } should ===(true) @@ -179,7 +179,7 @@ object TestProbeSpec { /** Creates the `expected` number of events to test. */ def eventsT(expected: Int): Seq[EventT] = - for (n ← 1 to expected) yield EventT(n) + for (n <- 1 to expected) yield EventT(n) } class TestProbeTimeoutSpec extends ScalaTestWithActorTestKit(TestProbeSpec.timeoutConfig) with WordSpecLike { diff --git a/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/AsyncTestingExampleSpec.scala b/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/AsyncTestingExampleSpec.scala index 8665eba79e..a780c7daa4 100644 --- a/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/AsyncTestingExampleSpec.scala +++ b/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/AsyncTestingExampleSpec.scala @@ -24,9 +24,9 @@ object AsyncTestingExampleSpec { case class Ping(message: String, response: ActorRef[Pong]) case class Pong(message: String) - val echoActor: Behavior[Ping] = Behaviors.receive { (_, message) ⇒ + val echoActor: Behavior[Ping] = Behaviors.receive { (_, message) => message match { - case Ping(m, replyTo) ⇒ + case Ping(m, replyTo) => replyTo ! Pong(m) Behaviors.same } @@ -43,7 +43,7 @@ object AsyncTestingExampleSpec { } private def publish(i: Int)(implicit timeout: Timeout): Future[Try[Int]] = { - publisher.ask(ref ⇒ Message(i, ref)) + publisher.ask(ref => Message(i, ref)) } } @@ -100,7 +100,7 @@ class AsyncTestingExampleSpec extends WordSpec with BeforeAndAfterAll with Match import testKit._ // simulate the happy path - val mockedBehavior = Behaviors.receiveMessage[Message] { msg ⇒ + val mockedBehavior = Behaviors.receiveMessage[Message] { msg => msg.replyTo ! Success(msg.i) Behaviors.same } @@ -113,7 +113,7 @@ class AsyncTestingExampleSpec extends WordSpec with BeforeAndAfterAll with Match producer.produce(messages) // verify expected behavior - for (i ← 0 until messages) { + for (i <- 0 until messages) { val msg = probe.expectMessageType[Message] msg.i shouldBe i } diff --git a/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/ManualTimerExampleSpec.scala b/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/ManualTimerExampleSpec.scala index 5f1291f21c..4e2e1d9fb0 100644 --- a/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/ManualTimerExampleSpec.scala +++ b/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/ManualTimerExampleSpec.scala @@ -22,9 +22,9 @@ class ManualTimerExampleSpec extends ScalaTestWithActorTestKit(ManualTime.config case object Tock val probe = TestProbe[Tock.type]() - val behavior = Behaviors.withTimers[Tick.type] { timer ⇒ + val behavior = Behaviors.withTimers[Tick.type] { timer => timer.startSingleTimer("T", Tick, 10.millis) - Behaviors.receiveMessage { _ ⇒ + Behaviors.receiveMessage { _ => probe.ref ! Tock Behaviors.same } @@ -46,9 +46,9 @@ class ManualTimerExampleSpec extends ScalaTestWithActorTestKit(ManualTime.config case object Tock val probe = TestProbe[Tock.type]() - val behavior = Behaviors.withTimers[Tick.type] { timer ⇒ + val behavior = Behaviors.withTimers[Tick.type] { timer => timer.startPeriodicTimer("T", Tick, 10.millis) - Behaviors.receive { (context, Tick) ⇒ + Behaviors.receive { (context, Tick) => probe.ref ! Tock Behaviors.same } @@ -56,7 +56,7 @@ class ManualTimerExampleSpec extends ScalaTestWithActorTestKit(ManualTime.config spawn(behavior) - for (_ ← Range(0, 5)) { + for (_ <- Range(0, 5)) { manualTime.expectNoMessageFor(9.millis, probe) manualTime.timePasses(1.milli) @@ -75,14 +75,14 @@ class ManualTimerExampleSpec extends ScalaTestWithActorTestKit(ManualTime.config val probe = TestProbe[Event]("evt") val interval = 10.millis - val behavior = Behaviors.withTimers[Command] { timer ⇒ + val behavior = Behaviors.withTimers[Command] { timer => timer.startPeriodicTimer("T", Tick(1), interval) - Behaviors.receive { (context, cmd) ⇒ + Behaviors.receive { (context, cmd) => cmd match { - case Tick(n) ⇒ + case Tick(n) => probe.ref ! Tock(n) Behaviors.same - case SlowThenBump(nextCount) ⇒ + case SlowThenBump(nextCount) => manualTime.timePasses(interval) timer.startPeriodicTimer("T", Tick(nextCount), interval) probe.ref ! SlowThenBumpAck diff --git a/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/SyncTestingExampleSpec.scala b/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/SyncTestingExampleSpec.scala index 412a398863..0aff7f0bb3 100644 --- a/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/SyncTestingExampleSpec.scala +++ b/akka-actor-testkit-typed/src/test/scala/docs/akka/actor/testkit/typed/scaladsl/SyncTestingExampleSpec.scala @@ -18,7 +18,7 @@ import org.scalatest.WordSpec object SyncTestingExampleSpec { //#child - val childActor = Behaviors.receiveMessage[String] { _ ⇒ + val childActor = Behaviors.receiveMessage[String] { _ => Behaviors.same[String] } //#child @@ -33,24 +33,24 @@ object SyncTestingExampleSpec { case class LogAndSayHello(who: ActorRef[String]) extends Cmd val myBehavior = Behaviors.receivePartial[Cmd] { - case (context, CreateChild(name)) ⇒ + case (context, CreateChild(name)) => context.spawn(childActor, name) Behaviors.same - case (context, CreateAnonymousChild) ⇒ + case (context, CreateAnonymousChild) => context.spawnAnonymous(childActor) Behaviors.same - case (context, SayHelloToChild(childName)) ⇒ + case (context, SayHelloToChild(childName)) => val child: ActorRef[String] = context.spawn(childActor, childName) child ! "hello" Behaviors.same - case (context, SayHelloToAnonymousChild) ⇒ + case (context, SayHelloToAnonymousChild) => val child: ActorRef[String] = context.spawnAnonymous(childActor) child ! "hello stranger" Behaviors.same - case (_, SayHello(who)) ⇒ + case (_, SayHello(who)) => who ! "hello" Behaviors.same - case (context, LogAndSayHello(who)) ⇒ + case (context, LogAndSayHello(who)) => context.log.info("Saying hello to {}", who.path.name) who ! "hello" Behaviors.same diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorConfigurationVerificationSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorConfigurationVerificationSpec.scala index e2c00621ff..54c66e2537 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorConfigurationVerificationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorConfigurationVerificationSpec.scala @@ -18,7 +18,7 @@ object ActorConfigurationVerificationSpec { class TestActor extends Actor { def receive: Receive = { - case _ ⇒ + case _ => } } diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorCreationPerfSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorCreationPerfSpec.scala index 4f8f409481..0391a44a10 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorCreationPerfSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorCreationPerfSpec.scala @@ -33,7 +33,7 @@ object ActorCreationPerfSpec { akka.actor.serialize-messages = off """) - final case class Create(number: Int, props: () ⇒ Props) + final case class Create(number: Int, props: () => Props) case object Created case object IsAlive case object Alive @@ -42,24 +42,24 @@ object ActorCreationPerfSpec { class EmptyActor extends Actor { def receive = { - case IsAlive ⇒ sender() ! Alive + case IsAlive => sender() ! Alive } } class EmptyArgsActor(val foo: Int, val bar: Int) extends Actor { def receive = { - case IsAlive ⇒ sender() ! Alive + case IsAlive => sender() ! Alive } } class TimingDriver(hist: Histogram) extends Actor { def receive = { - case IsAlive ⇒ + case IsAlive => sender() ! Alive - case Create(number, propsCreator) ⇒ + case Create(number, propsCreator) => - for (i ← 1 to number) { + for (i <- 1 to number) { val start = System.nanoTime() context.actorOf(propsCreator.apply()) // yes, we are aware of this being skewed @@ -68,7 +68,7 @@ object ActorCreationPerfSpec { } sender() ! Created - case WaitForChildren ⇒ + case WaitForChildren => context.children.foreach(_ ! IsAlive) context.become(waiting(context.children.size, sender()), discardOld = false) } @@ -77,7 +77,7 @@ object ActorCreationPerfSpec { var current = number { - case Alive ⇒ + case Alive => current -= 1 if (current == 0) { replyTo ! Waited @@ -90,14 +90,14 @@ object ActorCreationPerfSpec { class Driver extends Actor { def receive = { - case IsAlive ⇒ + case IsAlive => sender() ! Alive - case Create(number, propsCreator) ⇒ - for (i ← 1 to number) { + case Create(number, propsCreator) => + for (i <- 1 to number) { context.actorOf(propsCreator.apply()) } sender() ! Created - case WaitForChildren ⇒ + case WaitForChildren => context.children.foreach(_ ! IsAlive) context.become(waiting(context.children.size, sender()), discardOld = false) } @@ -106,7 +106,7 @@ object ActorCreationPerfSpec { var current = number { - case Alive ⇒ + case Alive => current -= 1 if (current == 0) { replyTo ! Waited @@ -133,7 +133,7 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with override val reportMetricsEnabled = metricsConfig.getBoolean("akka.test.actor.ActorPerfSpec.report-metrics") override val forceGcEnabled = metricsConfig.getBoolean("akka.test.actor.ActorPerfSpec.force-gc") - def runWithCounterInside(metricName: String, scenarioName: String, number: Int, propsCreator: () ⇒ Props): Unit = { + def runWithCounterInside(metricName: String, scenarioName: String, number: Int, propsCreator: () => Props): Unit = { val hist = histogram(BlockingTimeKey / metricName) val driver = system.actorOf(Props(classOf[TimingDriver], hist), scenarioName) @@ -141,10 +141,10 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with expectMsg(Alive) driver ! Create(number, propsCreator) - expectMsgPF(15 seconds, s"$scenarioName waiting for Created") { case Created ⇒ } + expectMsgPF(15 seconds, s"$scenarioName waiting for Created") { case Created => } driver ! WaitForChildren - expectMsgPF(15 seconds, s"$scenarioName waiting for Waited") { case Waited ⇒ } + expectMsgPF(15 seconds, s"$scenarioName waiting for Waited") { case Waited => } driver ! PoisonPill watch(driver) @@ -152,7 +152,7 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with gc() } - def runWithoutCounter(scenarioName: String, number: Int, propsCreator: () ⇒ Props): HeapMemoryUsage = { + def runWithoutCounter(scenarioName: String, number: Int, propsCreator: () => Props): HeapMemoryUsage = { val mem = measureMemory(TotalTimeKey / scenarioName) val driver = system.actorOf(Props(classOf[Driver]), scenarioName) @@ -163,10 +163,10 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with val before = mem.getHeapSnapshot driver ! Create(number, propsCreator) - expectMsgPF(15 seconds, s"$scenarioName waiting for Created") { case Created ⇒ } + expectMsgPF(15 seconds, s"$scenarioName waiting for Created") { case Created => } driver ! WaitForChildren - expectMsgPF(15 seconds, s"$scenarioName waiting for Waited") { case Waited ⇒ } + expectMsgPF(15 seconds, s"$scenarioName waiting for Waited") { case Waited => } gc() val after = mem.getHeapSnapshot @@ -178,7 +178,7 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with after diff before } - def registerTests(name: String, propsCreator: () ⇒ Props): Unit = { + def registerTests(name: String, propsCreator: () => Props): Unit = { val scenarioName = name.replaceAll("""[^\w]""", "") s"warm-up before: $name" taggedAs PerformanceTest in { @@ -192,7 +192,7 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with s"measure synchronous blocked time for $name" taggedAs PerformanceTest in { // note: measuring per-actor-memory-use in this scenario is skewed as the Actor contains references to counters etc! // for measuring actor size use refer to the `runWithoutCounter` method - for (i ← 1 to nrOfRepeats) { + for (i <- 1 to nrOfRepeats) { runWithCounterInside(name, s"${scenarioName}_driver_inside_$i", nrOfActors, propsCreator) } @@ -202,7 +202,7 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with s"measure total creation time for $name" taggedAs PerformanceTest in { val avgMem = averageGauge(ActorCreationKey / name / "avg-mem-per-actor") - for (i ← 1 to nrOfRepeats) { + for (i <- 1 to nrOfRepeats) { val heapUsed = timedWithKnownOps(TotalTimeKey / s"creating-$nrOfActors-actors" / name, ops = nrOfActors) { runWithoutCounter(s"${scenarioName}_driver_outside_$i", nrOfActors, propsCreator) } @@ -217,25 +217,25 @@ class ActorCreationPerfSpec extends AkkaSpec(ActorCreationPerfSpec.config) with "Actor creation with actorOf" must { - registerTests("Props[EmptyActor] with new Props", () ⇒ Props[EmptyActor]) + registerTests("Props[EmptyActor] with new Props", () => Props[EmptyActor]) val props1 = Props[EmptyActor] - registerTests("Props[EmptyActor] with same Props", () ⇒ props1) + registerTests("Props[EmptyActor] with same Props", () => props1) - registerTests("Props(new EmptyActor) new", () ⇒ { Props(new EmptyActor) }) + registerTests("Props(new EmptyActor) new", () => { Props(new EmptyActor) }) val props2 = Props(new EmptyActor) - registerTests("Props(new EmptyActor) same", () ⇒ { props2 }) + registerTests("Props(new EmptyActor) same", () => { props2 }) - registerTests("Props(classOf[EmptyArgsActor], ...) new", () ⇒ { Props(classOf[EmptyArgsActor], 4711, 1729) }) + registerTests("Props(classOf[EmptyArgsActor], ...) new", () => { Props(classOf[EmptyArgsActor], 4711, 1729) }) val props3 = Props(classOf[EmptyArgsActor], 4711, 1729) - registerTests("Props(classOf[EmptyArgsActor], ...) same", () ⇒ { props3 }) + registerTests("Props(classOf[EmptyArgsActor], ...) same", () => { props3 }) - registerTests("Props(new EmptyArgsActor(...)) new", () ⇒ { Props(new EmptyArgsActor(4711, 1729)) }) + registerTests("Props(new EmptyArgsActor(...)) new", () => { Props(new EmptyArgsActor(4711, 1729)) }) val props4 = Props(new EmptyArgsActor(4711, 1729)) - registerTests("Props(new EmptyArgsActor(...)) same", () ⇒ { props4 }) + registerTests("Props(new EmptyArgsActor(...)) same", () => { props4 }) } override def afterTermination() = shutdownMetrics() diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorDSLSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorDSLSpec.scala index 8658a5e165..703b718c0b 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorDSLSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorDSLSpec.scala @@ -26,7 +26,7 @@ class ActorDSLSpec extends AkkaSpec { val echo = system.actorOf(Props(new Actor { def receive = { - case x ⇒ sender() ! x + case x => sender() ! x } })) @@ -59,9 +59,9 @@ class ActorDSLSpec extends AkkaSpec { val i = inbox() import system.dispatcher val res = Future.sequence(Seq( - Future { i.receive() } recover { case x ⇒ x }, - Future { Thread.sleep(100); i.select() { case "world" ⇒ 1 } } recover { case x ⇒ x }, - Future { Thread.sleep(200); i.select() { case "hello" ⇒ 2 } } recover { case x ⇒ x })) + Future { i.receive() } recover { case x => x }, + Future { Thread.sleep(100); i.select() { case "world" => 1 } } recover { case x => x }, + Future { Thread.sleep(200); i.select() { case "hello" => 2 } } recover { case x => x })) Thread.sleep(1000) res.isCompleted should ===(false) i.receiver ! 42 @@ -75,7 +75,7 @@ class ActorDSLSpec extends AkkaSpec { i.receiver ! "hello" i.receiver ! "world" val result = i.select() { - case "world" ⇒ true + case "world" => true } result should ===(true) i.receive() should ===("hello") @@ -85,7 +85,7 @@ class ActorDSLSpec extends AkkaSpec { val i = inbox() system.eventStream.subscribe(testActor, classOf[Warning]) try { - for (_ ← 1 to 1000) i.receiver ! 0 + for (_ <- 1 to 1000) i.receiver ! 0 expectNoMsg(1 second) EventFilter.warning(start = "dropping message", occurrences = 1) intercept { i.receiver ! 42 @@ -93,8 +93,8 @@ class ActorDSLSpec extends AkkaSpec { expectMsgType[Warning] i.receiver ! 42 expectNoMsg(1 second) - val gotit = for (_ ← 1 to 1000) yield i.receive() - gotit should ===((1 to 1000) map (_ ⇒ 0)) + val gotit = for (_ <- 1 to 1000) yield i.receive() + gotit should ===((1 to 1000) map (_ => 0)) intercept[TimeoutException] { i.receive(1 second) } @@ -121,7 +121,7 @@ class ActorDSLSpec extends AkkaSpec { //#simple-actor val a = actor(new Act { become { - case "hello" ⇒ sender() ! "hi" + case "hello" => sender() ! "hi" } }) //#simple-actor @@ -135,13 +135,13 @@ class ActorDSLSpec extends AkkaSpec { //#becomeStacked val a = actor(new Act { become { // this will replace the initial (empty) behavior - case "info" ⇒ sender() ! "A" - case "switch" ⇒ + case "info" => sender() ! "A" + case "switch" => becomeStacked { // this will stack upon the "A" behavior - case "info" ⇒ sender() ! "B" - case "switch" ⇒ unbecome() // return to the "A" behavior + case "info" => sender() ! "B" + case "switch" => unbecome() // return to the "A" behavior } - case "lobotomize" ⇒ unbecome() // OH NOES: Actor.emptyBehavior + case "lobotomize" => unbecome() // OH NOES: Actor.emptyBehavior } }) //#becomeStacked @@ -174,18 +174,18 @@ class ActorDSLSpec extends AkkaSpec { //#failing-actor val a = actor(new Act { become { - case "die" ⇒ throw new Exception + case "die" => throw new Exception } - whenFailing { case m @ (cause, msg) ⇒ testActor ! m } - whenRestarted { cause ⇒ testActor ! cause } + whenFailing { case m @ (cause, msg) => testActor ! m } + whenRestarted { cause => testActor ! cause } }) //#failing-actor EventFilter[Exception](occurrences = 1) intercept { a ! "die" } - expectMsgPF() { case (x: Exception, Some("die")) ⇒ } - expectMsgPF() { case _: Exception ⇒ } + expectMsgPF() { case (x: Exception, Some("die")) => } + expectMsgPF() { case _: Exception => } } "support superviseWith" in { @@ -193,19 +193,19 @@ class ActorDSLSpec extends AkkaSpec { val system = null // shadow the implicit system //#supervise-with superviseWith(OneForOneStrategy() { - case e: Exception if e.getMessage == "hello" ⇒ Stop - case _: Exception ⇒ Resume + case e: Exception if e.getMessage == "hello" => Stop + case _: Exception => Resume }) //#supervise-with val child = actor("child")(new Act { - whenFailing { (_, _) ⇒ } + whenFailing { (_, _) => } become { - case ref: ActorRef ⇒ whenStopping(ref ! "stopped") - case ex: Exception ⇒ throw ex + case ref: ActorRef => whenStopping(ref ! "stopped") + case ex: Exception => throw ex } }) become { - case x ⇒ child ! x + case x => child ! x } }) a ! testActor @@ -228,7 +228,7 @@ class ActorDSLSpec extends AkkaSpec { whenStarting { context.parent ! ("hello from " + self.path) } }) become { - case x ⇒ testActor ! x + case x => testActor ! x } }) //#nested-actor @@ -240,10 +240,10 @@ class ActorDSLSpec extends AkkaSpec { //#act-with-stash val a = actor(new ActWithStash { become { - case 1 ⇒ stash() - case 2 ⇒ + case 1 => stash() + case 2 => testActor ! 2; unstashAll(); becomeStacked { - case 1 ⇒ testActor ! 1; unbecome() + case 1 => testActor ! 1; unbecome() } } }) diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorLifeCycleSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorLifeCycleSpec.scala index 1a380f8c56..e97cb5da3d 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorLifeCycleSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorLifeCycleSpec.scala @@ -14,7 +14,7 @@ import scala.concurrent.duration._ import java.util.concurrent.atomic._ import scala.concurrent.Await import akka.pattern.ask -import java.util.UUID.{ randomUUID ⇒ newUuid } +import java.util.UUID.{ randomUUID => newUuid } object ActorLifeCycleSpec { @@ -24,7 +24,7 @@ object ActorLifeCycleSpec { val currentGen = generationProvider.getAndIncrement() override def preStart(): Unit = { report("preStart") } override def postStop(): Unit = { report("postStop") } - def receive = { case "status" ⇒ sender() ! message("OK") } + def receive = { case "status" => sender() ! message("OK") } } } @@ -127,18 +127,18 @@ class ActorLifeCycleSpec extends AkkaSpec("akka.actor.serialize-messages=off") w } "clear the behavior stack upon restart" in { - final case class Become(recv: ActorContext ⇒ Receive) + final case class Become(recv: ActorContext => Receive) val a = system.actorOf(Props(new Actor { def receive = { - case Become(beh) ⇒ { context.become(beh(context), discardOld = false); sender() ! "ok" } - case x ⇒ sender() ! 42 + case Become(beh) => { context.become(beh(context), discardOld = false); sender() ! "ok" } + case x => sender() ! 42 } })) a ! "hello" expectMsg(42) - a ! Become(ctx ⇒ { - case "fail" ⇒ throw new RuntimeException("buh") - case x ⇒ ctx.sender() ! 43 + a ! Become(ctx => { + case "fail" => throw new RuntimeException("buh") + case x => ctx.sender() ! 43 }) expectMsg("ok") a ! "hello" diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorLookupSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorLookupSpec.scala index 7cac9eea20..a10edce5c8 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorLookupSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorLookupSpec.scala @@ -25,11 +25,11 @@ object ActorLookupSpec { class Node extends Actor { def receive = { - case Create(name) ⇒ sender() ! context.actorOf(p, name) - case LookupElems(path) ⇒ sender() ! context.actorFor(path) - case LookupString(path) ⇒ sender() ! context.actorFor(path) - case LookupPath(path) ⇒ sender() ! context.actorFor(path) - case GetSender(ref) ⇒ ref ! sender() + case Create(name) => sender() ! context.actorOf(p, name) + case LookupElems(path) => sender() ! context.actorFor(path) + case LookupString(path) => sender() ! context.actorFor(path) + case LookupPath(path) => sender() ! context.actorFor(path) + case GetSender(ref) => ref ! sender() } } @@ -50,7 +50,7 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout { def empty(path: String) = new EmptyLocalActorRef(sysImpl.provider, path match { - case RelativeActorPath(elems) ⇒ system.actorFor("/").path / elems + case RelativeActorPath(elems) => system.actorFor("/").path / elems }, system.eventStream) "An ActorSystem" must { @@ -179,8 +179,8 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout { Await.result(looker ? LookupPath(pathOf.path), timeout.duration) should ===(result) } for { - looker ← all - target ← all + looker <- all + target <- all } check(looker, target, target) } @@ -193,8 +193,8 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout { Await.result(looker ? LookupString(pathOf.path.toString + "/"), timeout.duration) should ===(result) } for { - looker ← all - target ← all + looker <- all + target <- all } check(looker, target, target) } @@ -204,8 +204,8 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout { Await.result(looker ? LookupString(pathOf.path.elements.mkString("/", "/", "/")), timeout.duration) should ===(result) } for { - looker ← all - target ← all + looker <- all + target <- all } check(looker, target, target) } @@ -217,8 +217,8 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout { } check(c1, user, "..") for { - looker ← Seq(c1, c2) - target ← all + looker <- Seq(c1, c2) + target <- all } check(looker, target, Seq("..") ++ target.path.elements.drop(1): _*) check(c21, user, "..", "..") check(c21, root, "..", "..", "..") @@ -227,7 +227,7 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout { "find system-generated actors" in { def check(target: ActorRef): Unit = { - for (looker ← all) { + for (looker <- all) { Await.result(looker ? LookupPath(target.path), timeout.duration) should ===(target) Await.result(looker ? LookupString(target.path.toString), timeout.duration) should ===(target) Await.result(looker ? LookupString(target.path.toString + "/"), timeout.duration) should ===(target) @@ -235,7 +235,7 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout { if (target != root) Await.result(looker ? LookupString(target.path.elements.mkString("/", "/", "/")), timeout.duration) should ===(target) } } - for (target ← Seq(root, syst, user, system.deadLetters)) check(target) + for (target <- Seq(root, syst, user, system.deadLetters)) check(target) } "return deadLetters or EmptyLocalActorRef, respectively, for non-existing paths" in { @@ -249,18 +249,18 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout { def check(looker: ActorRef): Unit = { val lookname = looker.path.elements.mkString("", "/", "/") for ( - (l, r) ← Seq( - LookupString("a/b/c") → empty(lookname + "a/b/c"), - LookupString("") → system.deadLetters, - LookupString("akka://all-systems/Nobody") → system.deadLetters, - LookupPath(system / "hallo") → empty("user/hallo"), - LookupPath(looker.path child "hallo") → empty(lookname + "hallo"), // test Java API - LookupPath(looker.path descendant Seq("a", "b").asJava) → empty(lookname + "a/b"), // test Java API - LookupElems(Seq()) → system.deadLetters, - LookupElems(Seq("a")) → empty(lookname + "a")) + (l, r) <- Seq( + LookupString("a/b/c") -> empty(lookname + "a/b/c"), + LookupString("") -> system.deadLetters, + LookupString("akka://all-systems/Nobody") -> system.deadLetters, + LookupPath(system / "hallo") -> empty("user/hallo"), + LookupPath(looker.path child "hallo") -> empty(lookname + "hallo"), // test Java API + LookupPath(looker.path descendant Seq("a", "b").asJava) -> empty(lookname + "a/b"), // test Java API + LookupElems(Seq()) -> system.deadLetters, + LookupElems(Seq("a")) -> empty(lookname + "a")) ) checkOne(looker, l, r) } - for (looker ← all) check(looker) + for (looker <- all) check(looker) } "find temporary actors" in { diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorMailboxSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorMailboxSpec.scala index d0a3f92fd3..c350599262 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorMailboxSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorMailboxSpec.scala @@ -168,7 +168,7 @@ object ActorMailboxSpec { class QueueReportingActor extends Actor { def receive = { - case _ ⇒ sender() ! context.asInstanceOf[ActorCell].mailbox.messageQueue + case _ => sender() ! context.asInstanceOf[ActorCell].mailbox.messageQueue } } @@ -231,7 +231,7 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout actor ! "ping" val q = expectMsgType[MessageQueue] - types foreach (t ⇒ assert(t isInstance q, s"Type [${q.getClass.getName}] is not assignable to [${t.getName}]")) + types foreach (t => assert(t isInstance q, s"Type [${q.getClass.getName}] is not assignable to [${t.getName}]")) q } diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorRefSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorRefSpec.scala index f08faeaa1d..8eb2d7e9f1 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorRefSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorRefSpec.scala @@ -23,28 +23,28 @@ object ActorRefSpec { var replyTo: ActorRef = null def receive = { - case "complexRequest" ⇒ { + case "complexRequest" => { replyTo = sender() val worker = context.actorOf(Props[WorkerActor]) worker ! "work" } - case "complexRequest2" ⇒ + case "complexRequest2" => val worker = context.actorOf(Props[WorkerActor]) worker ! ReplyTo(sender()) - case "workDone" ⇒ replyTo ! "complexReply" - case "simpleRequest" ⇒ sender() ! "simpleReply" + case "workDone" => replyTo ! "complexReply" + case "simpleRequest" => sender() ! "simpleReply" } } class WorkerActor() extends Actor { import context.system def receive = { - case "work" ⇒ { + case "work" => { work() sender() ! "workDone" context.stop(self) } - case ReplyTo(replyTo) ⇒ { + case ReplyTo(replyTo) => { work() replyTo ! "complexReply" } @@ -56,13 +56,13 @@ object ActorRefSpec { class SenderActor(replyActor: ActorRef, latch: TestLatch) extends Actor { def receive = { - case "complex" ⇒ replyActor ! "complexRequest" - case "complex2" ⇒ replyActor ! "complexRequest2" - case "simple" ⇒ replyActor ! "simpleRequest" - case "complexReply" ⇒ { + case "complex" => replyActor ! "complexRequest" + case "complex2" => replyActor ! "complexRequest2" + case "simple" => replyActor ! "simpleRequest" + case "complexReply" => { latch.countDown() } - case "simpleReply" ⇒ { + case "simpleReply" => { latch.countDown() } } @@ -70,8 +70,8 @@ object ActorRefSpec { class OuterActor(val inner: ActorRef) extends Actor { def receive = { - case "self" ⇒ sender() ! self - case x ⇒ inner forward x + case "self" => sender() ! self + case x => inner forward x } } @@ -79,8 +79,8 @@ object ActorRefSpec { val fail = new InnerActor def receive = { - case "self" ⇒ sender() ! self - case x ⇒ inner forward x + case "self" => sender() ! self + case x => inner forward x } } @@ -90,8 +90,8 @@ object ActorRefSpec { class InnerActor extends Actor { def receive = { - case "innerself" ⇒ sender() ! self - case other ⇒ sender() ! other + case "innerself" => sender() ! self + case other => sender() ! other } } @@ -99,8 +99,8 @@ object ActorRefSpec { val fail = new InnerActor def receive = { - case "innerself" ⇒ sender() ! self - case other ⇒ sender() ! other + case "innerself" => sender() ! self + case other => sender() ! other } } @@ -112,17 +112,17 @@ object ActorRefSpec { class ActorRefSpec extends AkkaSpec with DefaultTimeout { import akka.actor.ActorRefSpec._ - def promiseIntercept(f: ⇒ Actor)(to: Promise[Actor]): Actor = try { + def promiseIntercept(f: => Actor)(to: Promise[Actor]): Actor = try { val r = f to.success(r) r } catch { - case e: Throwable ⇒ + case e: Throwable => to.failure(e) throw e } - def wrap[T](f: Promise[Actor] ⇒ T): T = { + def wrap[T](f: Promise[Actor] => T): T = { val result = Promise[Actor]() val r = f(result) Await.result(result.future, 1 minute) @@ -134,17 +134,17 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { "not allow Actors to be created outside of an actorOf" in { import system.actorOf intercept[akka.actor.ActorInitializationException] { - new Actor { def receive = { case _ ⇒ } } + new Actor { def receive = { case _ => } } } def contextStackMustBeEmpty(): Unit = ActorCell.contextStack.get.headOption should ===(None) EventFilter[ActorInitializationException](occurrences = 1) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new Actor { - val nested = promiseIntercept(new Actor { def receive = { case _ ⇒ } })(result) - def receive = { case _ ⇒ } + val nested = promiseIntercept(new Actor { def receive = { case _ => } })(result) + def receive = { case _ => } }))) } @@ -153,7 +153,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 1) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(promiseIntercept(new FailingOuterActor(actorOf(Props(new InnerActor))))(result)))) } @@ -162,7 +162,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 1) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result))))))) } @@ -171,7 +171,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 1) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(promiseIntercept(new FailingInheritingOuterActor(actorOf(Props(new InnerActor))))(result)))) } @@ -180,7 +180,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 2) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new FailingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result))))))) } @@ -189,7 +189,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 2) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new FailingInheritingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result))))))) } @@ -198,7 +198,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 2) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new FailingInheritingOuterActor(actorOf(Props(promiseIntercept(new FailingInnerActor)(result))))))) } @@ -207,7 +207,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 1) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new OuterActor(actorOf(Props(new InnerActor { val a = promiseIntercept(new InnerActor)(result) })))))) @@ -218,7 +218,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 2) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new FailingOuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result))))))) } @@ -227,7 +227,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 1) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept(new FailingInheritingInnerActor)(result))))))) } @@ -236,7 +236,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 1) intercept { intercept[akka.actor.ActorInitializationException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept({ new InnerActor; new InnerActor })(result))))))) } @@ -245,7 +245,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { EventFilter[ActorInitializationException](occurrences = 1) intercept { (intercept[java.lang.IllegalStateException] { - wrap(result ⇒ + wrap(result => actorOf(Props(new OuterActor(actorOf(Props(promiseIntercept({ throw new IllegalStateException("Ur state be b0rked"); new InnerActor })(result))))))) }).getMessage should ===("Ur state be b0rked") @@ -256,7 +256,7 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { "insert its path in a ActorInitializationException" in { EventFilter[ActorInitializationException](occurrences = 1, pattern = "/user/failingActor:") intercept { intercept[java.lang.IllegalStateException] { - wrap(result ⇒ + wrap(result => system.actorOf(Props(promiseIntercept({ throw new IllegalStateException })(result)), "failingActor")) @@ -344,8 +344,8 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { "support nested actorOfs" in { val a = system.actorOf(Props(new Actor { - val nested = system.actorOf(Props(new Actor { def receive = { case _ ⇒ } })) - def receive = { case _ ⇒ sender() ! nested } + val nested = system.actorOf(Props(new Actor { def receive = { case _ => } })) + def receive = { case _ => sender() ! nested } })) val nested = Await.result((a ? "any").mapTo[ActorRef], timeout.duration) @@ -401,8 +401,8 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { val timeout = Timeout(20.seconds) val ref = system.actorOf(Props(new Actor { def receive = { - case 5 ⇒ sender() ! "five" - case 0 ⇒ sender() ! "null" + case 5 => sender() ! "five" + case 0 => sender() ! "null" } })) @@ -428,12 +428,12 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { val ref = context.actorOf( Props(new Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } override def preRestart(reason: Throwable, msg: Option[Any]) = latch.countDown() override def postRestart(reason: Throwable) = latch.countDown() })) - def receive = { case "sendKill" ⇒ ref ! Kill } + def receive = { case "sendKill" => ref ! Kill } })) boss ! "sendKill" @@ -446,10 +446,10 @@ class ActorRefSpec extends AkkaSpec with DefaultTimeout { val child = context.actorOf( Props(new Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } }), "child") - def receive = { case name: String ⇒ sender() ! context.child(name).isDefined } + def receive = { case name: String => sender() ! context.child(name).isDefined } }), "parent") assert(Await.result((parent ? "child"), timeout.duration) === true) diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorSelectionSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorSelectionSpec.scala index 052e086808..708401def1 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorSelectionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorSelectionSpec.scala @@ -25,12 +25,12 @@ object ActorSelectionSpec { class Node extends Actor { def receive = { - case Create(name) ⇒ sender() ! context.actorOf(p, name) - case SelectString(path) ⇒ sender() ! context.actorSelection(path) - case SelectPath(path) ⇒ sender() ! context.actorSelection(path) - case GetSender(ref) ⇒ ref ! sender() - case Forward(path, msg) ⇒ context.actorSelection(path).forward(msg) - case msg ⇒ sender() ! msg + case Create(name) => sender() ! context.actorOf(p, name) + case SelectString(path) => sender() ! context.actorSelection(path) + case SelectPath(path) => sender() ! context.actorSelection(path) + case GetSender(ref) => ref ! sender() + case Forward(path, msg) => context.actorSelection(path).forward(msg) + case msg => sender() ! msg } } @@ -51,7 +51,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { def empty(path: String) = new EmptyLocalActorRef(sysImpl.provider, path match { - case RelativeActorPath(elems) ⇒ sysImpl.lookupRoot.path / elems + case RelativeActorPath(elems) => sysImpl.lookupRoot.path / elems }, system.eventStream) val idProbe = TestProbe() @@ -59,7 +59,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { def identify(selection: ActorSelection): Option[ActorRef] = { selection.tell(Identify(selection), idProbe.ref) val result = idProbe.expectMsgPF() { - case ActorIdentity(`selection`, ref) ⇒ ref + case ActorIdentity(`selection`, ref) => ref } val asked = Await.result((selection ? Identify(selection)).mapTo[ActorIdentity], timeout.duration) asked.ref should ===(result) @@ -67,7 +67,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { implicit val ec = system.dispatcher val resolved = Await.result( - selection.resolveOne(timeout.duration).mapTo[ActorRef] recover { case _ ⇒ null }, + selection.resolveOne(timeout.duration).mapTo[ActorRef] recover { case _ => null }, timeout.duration) Option(resolved) should ===(result) @@ -79,8 +79,8 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { def askNode(node: ActorRef, query: Query): Option[ActorRef] = { Await.result(node ? query, timeout.duration) match { - case ref: ActorRef ⇒ Some(ref) - case selection: ActorSelection ⇒ identify(selection) + case ref: ActorRef => Some(ref) + case selection: ActorSelection => identify(selection) } } @@ -188,8 +188,8 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { askNode(looker, SelectPath(pathOf.path)) should ===(Some(result)) } for { - looker ← all - target ← all + looker <- all + target <- all } check(looker, target, target) } @@ -200,8 +200,8 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { askNode(looker, SelectString(pathOf.path.toStringWithoutAddress + "/")) should ===(Some(result)) } for { - looker ← all - target ← all + looker <- all + target <- all } check(looker, target, target) } @@ -211,8 +211,8 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { askNode(looker, SelectString(pathOf.path.elements.mkString("/", "/", "/"))) should ===(Some(result)) } for { - looker ← all - target ← all + looker <- all + target <- all } check(looker, target, target) } @@ -223,8 +223,8 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { } check(c1, user, "..") for { - looker ← Seq(c1, c2) - target ← all + looker <- Seq(c1, c2) + target <- all } check(looker, target, Seq("..") ++ target.path.elements.drop(1): _*) check(c21, user, "..", "..") check(c21, root, "..", "..", "..") @@ -233,7 +233,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { "find system-generated actors" in { def check(target: ActorRef): Unit = { - for (looker ← all) { + for (looker <- all) { askNode(looker, SelectPath(target.path)) should ===(Some(target)) askNode(looker, SelectString(target.path.toString)) should ===(Some(target)) askNode(looker, SelectString(target.path.toString + "/")) should ===(Some(target)) @@ -241,7 +241,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { if (target != root) askNode(c1, SelectString("../.." + target.path.elements.mkString("/", "/", "/"))) should ===(Some(target)) } - for (target ← Seq(root, syst, user)) check(target) + for (target <- Seq(root, syst, user)) check(target) } "return deadLetters or ActorIdentity(None), respectively, for non-existing paths" in { @@ -254,15 +254,15 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { def check(looker: ActorRef): Unit = { val lookname = looker.path.elements.mkString("", "/", "/") for ( - (l, r) ← Seq( - SelectString("a/b/c") → None, - SelectString("akka://all-systems/Nobody") → None, - SelectPath(system / "hallo") → None, - SelectPath(looker.path child "hallo") → None, // test Java API - SelectPath(looker.path descendant Seq("a", "b").asJava) → None) // test Java API + (l, r) <- Seq( + SelectString("a/b/c") -> None, + SelectString("akka://all-systems/Nobody") -> None, + SelectPath(system / "hallo") -> None, + SelectPath(looker.path child "hallo") -> None, // test Java API + SelectPath(looker.path descendant Seq("a", "b").asJava) -> None) // test Java API ) checkOne(looker, l, r) } - for (looker ← all) check(looker) + for (looker <- all) check(looker) } } @@ -291,7 +291,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { implicit val sender = c1 ActorSelection(c21, "../../*") ! GetSender(testActor) val actors = Set() ++ receiveWhile(messages = 2) { - case `c1` ⇒ lastSender + case `c1` => lastSender } actors should ===(Set(c1, c2)) expectNoMsg(1 second) @@ -301,7 +301,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { implicit val sender = c2 ActorSelection(c21, "../../*/c21") ! GetSender(testActor) val actors = receiveWhile(messages = 2) { - case `c2` ⇒ lastSender + case `c2` => lastSender } actors should ===(Seq(c21)) expectNoMsg(200.millis) @@ -368,7 +368,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout { val probe = TestProbe() system.actorSelection("/user/a/*").tell(Identify(1), probe.ref) - probe.receiveN(2).map { case ActorIdentity(1, r) ⇒ r }.toSet should ===(Set[Option[ActorRef]](Some(b1), Some(b2))) + probe.receiveN(2).map { case ActorIdentity(1, r) => r }.toSet should ===(Set[Option[ActorRef]](Some(b1), Some(b2))) probe.expectNoMsg(200.millis) system.actorSelection("/user/a/b1/*").tell(Identify(2), probe.ref) diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala index cd9559c72b..99e4022f45 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala @@ -27,14 +27,14 @@ object ActorSystemSpec { var terminaters = Set[ActorRef]() def receive = { - case n: Int ⇒ + case n: Int => master = sender() - terminaters = Set() ++ (for (i ← 1 to n) yield { + terminaters = Set() ++ (for (i <- 1 to n) yield { val man = context.watch(context.system.actorOf(Props[Terminater])) man ! "run" man }) - case Terminated(child) if terminaters contains child ⇒ + case Terminated(child) if terminaters contains child => terminaters -= child if (terminaters.isEmpty) { master ! "done" @@ -52,13 +52,13 @@ object ActorSystemSpec { class Terminater extends Actor { def receive = { - case "run" ⇒ context.stop(self) + case "run" => context.stop(self) } } class Strategy extends SupervisorStrategyConfigurator { def create() = OneForOneStrategy() { - case _ ⇒ SupervisorStrategy.Escalate + case _ => SupervisorStrategy.Escalate } } @@ -69,7 +69,7 @@ object ActorSystemSpec { latch.countDown() def receive = { - case _ ⇒ + case _ => } } @@ -87,7 +87,7 @@ object ActorSystemSpec { doneIt.switchOn { TestKit.awaitCond(mbox.actor.actor != null, 1.second) mbox.actor.actor match { - case FastActor(latch, _) ⇒ Await.ready(latch, 1.second) + case FastActor(latch, _) => Await.ready(latch, 1.second) } } ret @@ -132,7 +132,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend "reject invalid names" in { for ( - n ← Seq( + n <- Seq( "-hallowelt", "_hallowelt", "hallo*welt", @@ -190,7 +190,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend val count = 10 val latch = TestLatch(count) - for (i ← 1 to count) { + for (i <- 1 to count) { system2.registerOnTermination { Thread.sleep((i % 3).millis.dilated.toMillis) result add i @@ -201,7 +201,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend system2.terminate() Await.ready(latch, 5 seconds) - val expected = (for (i ← 1 to count) yield i).reverse + val expected = (for (i <- 1 to count) yield i).reverse immutableSeq(result) should ===(expected) } @@ -253,7 +253,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend system2.terminate() system2.registerOnTermination { count.incrementAndGet() } } catch { - case _: RejectedExecutionException ⇒ count.incrementAndGet() + case _: RejectedExecutionException => count.incrementAndGet() } Await.ready(system2.whenTerminated, 10.seconds) @@ -263,7 +263,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend "reliably create waves of actors" in { import system.dispatcher implicit val timeout = Timeout((20 seconds).dilated) - val waves = for (i ← 1 to 3) yield system.actorOf(Props[ActorSystemSpec.Waves]) ? 50000 + val waves = for (i <- 1 to 3) yield system.actorOf(Props[ActorSystemSpec.Waves]) ? 50000 Await.result(Future.sequence(waves), timeout.duration + 5.seconds) should ===(Vector("done", "done", "done")) } @@ -285,7 +285,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend created :+= t if (created.size % 1000 == 0) Thread.sleep(50) // in case of unfair thread scheduling } catch { - case _: IllegalStateException ⇒ failing = true + case _: IllegalStateException => failing = true } if (!failing && system.uptime >= 10) { @@ -295,7 +295,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend } } - created filter (ref ⇒ !ref.isTerminated && !ref.asInstanceOf[ActorRefWithCell].underlying.isInstanceOf[UnstartedCell]) should ===(Seq.empty[ActorRef]) + created filter (ref => !ref.isTerminated && !ref.asInstanceOf[ActorRefWithCell].underlying.isInstanceOf[UnstartedCell]) should ===(Seq.empty[ActorRef]) } "shut down when /user fails" in { @@ -313,7 +313,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend .withFallback(AkkaSpec.testConf)) val a = system.actorOf(Props(new Actor { def receive = { - case "die" ⇒ throw new Exception("hello") + case "die" => throw new Exception("hello") } })) val probe = TestProbe() @@ -334,7 +334,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend .withFallback(AkkaSpec.testConf)) val a = system.actorOf(Props(new Actor { def receive = { - case "die" ⇒ throw new Exception("hello") + case "die" => throw new Exception("hello") } })) EventFilter[Exception]("hello") intercept { @@ -352,7 +352,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend try { val ref = system2.actorOf(Props(new Actor { def receive = { - case "ping" ⇒ sender() ! "pong" + case "ping" => sender() ! "pong" } })) diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorWithBoundedStashSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorWithBoundedStashSpec.scala index 59ce87c0d7..35cedcc140 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorWithBoundedStashSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorWithBoundedStashSpec.scala @@ -19,18 +19,18 @@ object ActorWithBoundedStashSpec { class StashingActor extends Actor with Stash { def receive = { - case msg: String if msg.startsWith("hello") ⇒ + case msg: String if msg.startsWith("hello") => stash() sender() ! "ok" - case "world" ⇒ + case "world" => context.become(afterWorldBehavior) unstashAll() } def afterWorldBehavior: Receive = { - case _ ⇒ stash() + case _ => stash() } } @@ -38,10 +38,10 @@ object ActorWithBoundedStashSpec { var numStashed = 0 def receive = { - case msg: String if msg.startsWith("hello") ⇒ + case msg: String if msg.startsWith("hello") => numStashed += 1 try { stash(); sender() ! "ok" } catch { - case _: StashOverflowException ⇒ + case _: StashOverflowException => if (numStashed == 21) { sender() ! "STASHOVERFLOW" context stop self @@ -97,7 +97,7 @@ class ActorWithBoundedStashSpec extends AkkaSpec(ActorWithBoundedStashSpec.testC def testDeadLetters(stasher: ActorRef): Unit = { // fill up stash - for (n ← 1 to 11) { + for (n <- 1 to 11) { stasher ! "hello" + n expectMsg("ok") } @@ -108,12 +108,12 @@ class ActorWithBoundedStashSpec extends AkkaSpec(ActorWithBoundedStashSpec.testC stasher ! PoisonPill // stashed messages are sent to deadletters when stasher is stopped - for (n ← 2 to 11) expectMsg(DeadLetter("hello" + n, testActor, stasher)) + for (n <- 2 to 11) expectMsg(DeadLetter("hello" + n, testActor, stasher)) } def testStashOverflowException(stasher: ActorRef): Unit = { // fill up stash - for (n ← 1 to 20) { + for (n <- 1 to 20) { stasher ! "hello" + n expectMsg("ok") } @@ -122,7 +122,7 @@ class ActorWithBoundedStashSpec extends AkkaSpec(ActorWithBoundedStashSpec.testC expectMsg("STASHOVERFLOW") // stashed messages are sent to deadletters when stasher is stopped, - for (n ← 1 to 20) expectMsg(DeadLetter("hello" + n, testActor, stasher)) + for (n <- 1 to 20) expectMsg(DeadLetter("hello" + n, testActor, stasher)) } "An Actor with Stash" must { diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorWithStashSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorWithStashSpec.scala index 751658d861..b0c54c1917 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorWithStashSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorWithStashSpec.scala @@ -20,49 +20,49 @@ object ActorWithStashSpec { class StashingActor extends Actor with Stash { import context.system def greeted: Receive = { - case "bye" ⇒ + case "bye" => state.s = "bye" state.finished.await - case _ ⇒ // do nothing + case _ => // do nothing } def receive = { - case "hello" ⇒ + case "hello" => state.s = "hello" unstashAll() context.become(greeted) - case msg ⇒ stash() + case msg => stash() } } class StashingTwiceActor extends Actor with Stash { def receive = { - case "hello" ⇒ + case "hello" => try { stash() stash() } catch { - case e: IllegalStateException ⇒ + case e: IllegalStateException => state.expectedException.open() } - case msg ⇒ // do nothing + case msg => // do nothing } } class ActorWithProtocol extends Actor with Stash { import context.system def receive = { - case "open" ⇒ + case "open" => unstashAll() context.become { - case "write" ⇒ // do writing... - case "close" ⇒ + case "write" => // do writing... + case "close" => unstashAll() context.unbecome() - case msg ⇒ stash() + case msg => stash() } - case "done" ⇒ state.finished.await - case msg ⇒ stash() + case "done" => state.finished.await + case msg => stash() } } @@ -77,7 +77,7 @@ object ActorWithStashSpec { context.stop(watched) def receive = { - case Terminated(`watched`) ⇒ + case Terminated(`watched`) => if (!stashed) { stash() stashed = true @@ -150,15 +150,15 @@ class ActorWithStashSpec extends AkkaSpec(ActorWithStashSpec.testConf) with Defa val slaveProps = Props(new Actor with Stash { def receive = { - case "crash" ⇒ + case "crash" => throw new Exception("Crashing...") // when restartLatch is not yet open, stash all messages != "crash" - case msg if !restartLatch.isOpen ⇒ + case msg if !restartLatch.isOpen => stash() // when restartLatch is open, must receive "hello" - case "hello" ⇒ + case "hello" => hasMsgLatch.open() } @@ -190,9 +190,9 @@ class ActorWithStashSpec extends AkkaSpec(ActorWithStashSpec.testConf) with Defa import ActorDSL._ val a = actor(new ActWithStash { become { - case "die" ⇒ throw new RuntimeException("dying") + case "die" => throw new RuntimeException("dying") } - whenRestarted { thr ⇒ + whenRestarted { thr => testActor ! "restarted" } }) diff --git a/akka-actor-tests/src/test/scala/akka/actor/Bench.scala b/akka-actor-tests/src/test/scala/akka/actor/Bench.scala index 3d070a037d..60498b52af 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/Bench.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/Bench.scala @@ -30,42 +30,42 @@ object Chameneos { mall ! Meet(self, colour) def receive = { - case Meet(from, otherColour) ⇒ + case Meet(from, otherColour) => colour = complement(otherColour) meetings = meetings + 1 from ! Change(colour) mall ! Meet(self, colour) - case Change(newColour) ⇒ + case Change(newColour) => colour = newColour meetings = meetings + 1 mall ! Meet(self, colour) - case Exit ⇒ + case Exit => colour = FADED sender() ! MeetingCount(meetings) } def complement(otherColour: Colour): Colour = colour match { - case RED ⇒ otherColour match { - case RED ⇒ RED - case YELLOW ⇒ BLUE - case BLUE ⇒ YELLOW - case FADED ⇒ FADED + case RED => otherColour match { + case RED => RED + case YELLOW => BLUE + case BLUE => YELLOW + case FADED => FADED } - case YELLOW ⇒ otherColour match { - case RED ⇒ BLUE - case YELLOW ⇒ YELLOW - case BLUE ⇒ RED - case FADED ⇒ FADED + case YELLOW => otherColour match { + case RED => BLUE + case YELLOW => YELLOW + case BLUE => RED + case FADED => FADED } - case BLUE ⇒ otherColour match { - case RED ⇒ YELLOW - case YELLOW ⇒ RED - case BLUE ⇒ BLUE - case FADED ⇒ FADED + case BLUE => otherColour match { + case RED => YELLOW + case YELLOW => RED + case BLUE => BLUE + case FADED => FADED } - case FADED ⇒ FADED + case FADED => FADED } override def toString = cid + "(" + colour + ")" @@ -77,11 +77,11 @@ object Chameneos { var numFaded = 0 override def preStart() = { - for (i ← 0 until numChameneos) context.actorOf(Props(new Chameneo(self, colours(i % 3), i))) + for (i <- 0 until numChameneos) context.actorOf(Props(new Chameneo(self, colours(i % 3), i))) } def receive = { - case MeetingCount(i) ⇒ + case MeetingCount(i) => numFaded += 1 sumMeetings += i if (numFaded == numChameneos) { @@ -89,14 +89,14 @@ object Chameneos { context.stop(self) } - case msg @ Meet(a, c) ⇒ + case msg @ Meet(a, c) => if (n > 0) { waitingChameneo match { - case Some(chameneo) ⇒ + case Some(chameneo) => n -= 1 chameneo ! msg waitingChameneo = None - case None ⇒ waitingChameneo = Some(sender()) + case None => waitingChameneo = Some(sender()) } } else { waitingChameneo.foreach(_ ! Exit) diff --git a/akka-actor-tests/src/test/scala/akka/actor/ConsistencySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ConsistencySpec.scala index 99f4d8021f..8d1ab0f05d 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ConsistencySpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ConsistencySpec.scala @@ -34,7 +34,7 @@ object ConsistencySpec { var right = new CacheMisaligned(0, 0, 0, 0) //var var lastStep = -1L def receive = { - case step: Long ⇒ + case step: Long => if (lastStep != (step - 1)) sender() ! "Test failed: Last step %s, this step %s".format(lastStep, step) @@ -48,7 +48,7 @@ object ConsistencySpec { } lastStep = step - case "done" ⇒ sender() ! "done"; context.stop(self) + case "done" => sender() ! "done"; context.stop(self) } } } @@ -64,13 +64,13 @@ class ConsistencySpec extends AkkaSpec(ConsistencySpec.config) { val props = Props[ConsistencyCheckingActor].withDispatcher("consistency-dispatcher") val actors = Vector.fill(noOfActors)(system.actorOf(props)) - for (i ← 0L until 10000L) { + for (i <- 0L until 10000L) { actors.foreach(_.tell(i, testActor)) } - for (a ← actors) { a.tell("done", testActor) } + for (a <- actors) { a.tell("done", testActor) } - for (a ← actors) expectMsg(5 minutes, "done") + for (a <- actors) expectMsg(5 minutes, "done") } } } diff --git a/akka-actor-tests/src/test/scala/akka/actor/CoordinatedShutdownSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/CoordinatedShutdownSpec.scala index 9126aee680..347927ea10 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/CoordinatedShutdownSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/CoordinatedShutdownSpec.scala @@ -34,15 +34,15 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( private def checkTopologicalSort(phases: Map[String, Phase]): List[String] = { val result = CoordinatedShutdown.topologicalSort(phases) result.zipWithIndex.foreach { - case (phase, i) ⇒ + case (phase, i) => phases.get(phase) match { - case Some(Phase(dependsOn, _, _, _)) ⇒ - dependsOn.foreach { depPhase ⇒ + case Some(Phase(dependsOn, _, _, _)) => + dependsOn.foreach { depPhase => withClue(s"phase [$phase] depends on [$depPhase] but was ordered before it in topological sort result $result") { i should be > result.indexOf(depPhase) } } - case None ⇒ // ok + case None => // ok } } result @@ -56,37 +56,37 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( checkTopologicalSort(Map.empty) should ===(Nil) checkTopologicalSort(Map( - "a" → emptyPhase)) should ===(List("a")) + "a" -> emptyPhase)) should ===(List("a")) checkTopologicalSort(Map( - "b" → phase("a"))) should ===(List("a", "b")) + "b" -> phase("a"))) should ===(List("a", "b")) val result1 = checkTopologicalSort(Map( - "c" → phase("a"), "b" → phase("a"))) + "c" -> phase("a"), "b" -> phase("a"))) result1.head should ===("a") // b, c can be in any order result1.toSet should ===(Set("a", "b", "c")) checkTopologicalSort(Map( - "b" → phase("a"), "c" → phase("b"))) should ===(List("a", "b", "c")) + "b" -> phase("a"), "c" -> phase("b"))) should ===(List("a", "b", "c")) checkTopologicalSort(Map( - "b" → phase("a"), "c" → phase("a", "b"))) should ===(List("a", "b", "c")) + "b" -> phase("a"), "c" -> phase("a", "b"))) should ===(List("a", "b", "c")) val result2 = checkTopologicalSort(Map( - "c" → phase("a", "b"))) + "c" -> phase("a", "b"))) result2.last should ===("c") // a, b can be in any order result2.toSet should ===(Set("a", "b", "c")) checkTopologicalSort(Map( - "b" → phase("a"), "c" → phase("b"), "d" → phase("b", "c"), - "e" → phase("d"))) should ===( + "b" -> phase("a"), "c" -> phase("b"), "d" -> phase("b", "c"), + "e" -> phase("d"))) should ===( List("a", "b", "c", "d", "e")) val result3 = checkTopologicalSort(Map( - "a2" → phase("a1"), "a3" → phase("a2"), - "b2" → phase("b1"), "b3" → phase("b2"))) + "a2" -> phase("a1"), "a3" -> phase("a2"), + "b2" -> phase("b1"), "b3" -> phase("b2"))) val (a, b) = result3.partition(_.charAt(0) == 'a') a should ===(List("a1", "a2", "a3")) b should ===(List("b1", "b2", "b3")) @@ -95,22 +95,22 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( "detect cycles in phases (non-DAG)" in { intercept[IllegalArgumentException] { CoordinatedShutdown.topologicalSort(Map( - "a" → phase("a"))) + "a" -> phase("a"))) } intercept[IllegalArgumentException] { CoordinatedShutdown.topologicalSort(Map( - "b" → phase("a"), "a" → phase("b"))) + "b" -> phase("a"), "a" -> phase("b"))) } intercept[IllegalArgumentException] { CoordinatedShutdown.topologicalSort(Map( - "c" → phase("a"), "c" → phase("b"), "b" → phase("c"))) + "c" -> phase("a"), "c" -> phase("b"), "b" -> phase("c"))) } intercept[IllegalArgumentException] { CoordinatedShutdown.topologicalSort(Map( - "d" → phase("a"), "d" → phase("c"), "c" → phase("b"), "b" → phase("d"))) + "d" -> phase("a"), "d" -> phase("c"), "c" -> phase("b"), "b" -> phase("d"))) } } @@ -135,19 +135,19 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( "run ordered phases" in { import system.dispatcher val phases = Map( - "a" → emptyPhase, - "b" → phase("a"), - "c" → phase("b", "a")) + "a" -> emptyPhase, + "b" -> phase("a"), + "c" -> phase("b", "a")) val co = new CoordinatedShutdown(extSys, phases) - co.addTask("a", "a1") { () ⇒ + co.addTask("a", "a1") { () => testActor ! "A" Future.successful(Done) } - co.addTask("b", "b1") { () ⇒ + co.addTask("b", "b1") { () => testActor ! "B" Future.successful(Done) } - co.addTask("b", "b2") { () ⇒ + co.addTask("b", "b2") { () => Future { // to verify that c is not performed before b Thread.sleep(100) @@ -155,7 +155,7 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( Done } } - co.addTask("c", "c1") { () ⇒ + co.addTask("c", "c1") { () => testActor ! "C" Future.successful(Done) } @@ -165,19 +165,19 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( "run from a given phase" in { val phases = Map( - "a" → emptyPhase, - "b" → phase("a"), - "c" → phase("b", "a")) + "a" -> emptyPhase, + "b" -> phase("a"), + "c" -> phase("b", "a")) val co = new CoordinatedShutdown(extSys, phases) - co.addTask("a", "a1") { () ⇒ + co.addTask("a", "a1") { () => testActor ! "A" Future.successful(Done) } - co.addTask("b", "b1") { () ⇒ + co.addTask("b", "b1") { () => testActor ! "B" Future.successful(Done) } - co.addTask("c", "c1") { () ⇒ + co.addTask("c", "c1") { () => testActor ! "C" Future.successful(Done) } @@ -187,9 +187,9 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( } "only run once" in { - val phases = Map("a" → emptyPhase) + val phases = Map("a" -> emptyPhase) val co = new CoordinatedShutdown(extSys, phases) - co.addTask("a", "a1") { () ⇒ + co.addTask("a", "a1") { () => testActor ! "A" Future.successful(Done) } @@ -206,15 +206,15 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( "continue after timeout or failure" in { import system.dispatcher val phases = Map( - "a" → emptyPhase, - "b" → Phase(dependsOn = Set("a"), timeout = 100.millis, recover = true, enabled = true), - "c" → phase("b", "a")) + "a" -> emptyPhase, + "b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = true, enabled = true), + "c" -> phase("b", "a")) val co = new CoordinatedShutdown(extSys, phases) - co.addTask("a", "a1") { () ⇒ + co.addTask("a", "a1") { () => testActor ! "A" Future.failed(new RuntimeException("boom")) } - co.addTask("a", "a2") { () ⇒ + co.addTask("a", "a2") { () => Future { // to verify that b is not performed before a also in case of failure Thread.sleep(100) @@ -222,11 +222,11 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( Done } } - co.addTask("b", "b1") { () ⇒ + co.addTask("b", "b1") { () => testActor ! "B" Promise[Done]().future // never completed } - co.addTask("c", "c1") { () ⇒ + co.addTask("c", "c1") { () => testActor ! "C" Future.successful(Done) } @@ -243,15 +243,15 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( "abort if recover=off" in { val phases = Map( - "a" → emptyPhase, - "b" → Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false, enabled = true), - "c" → phase("b", "a")) + "a" -> emptyPhase, + "b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false, enabled = true), + "c" -> phase("b", "a")) val co = new CoordinatedShutdown(extSys, phases) - co.addTask("b", "b1") { () ⇒ + co.addTask("b", "b1") { () => testActor ! "B" Promise[Done]().future // never completed } - co.addTask("c", "c1") { () ⇒ + co.addTask("c", "c1") { () => testActor ! "C" Future.successful(Done) } @@ -265,15 +265,15 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( "skip tasks in disabled phase" in { val phases = Map( - "a" → emptyPhase, - "b" → Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false, enabled = false), - "c" → phase("b", "a")) + "a" -> emptyPhase, + "b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false, enabled = false), + "c" -> phase("b", "a")) val co = new CoordinatedShutdown(extSys, phases) - co.addTask("b", "b1") { () ⇒ + co.addTask("b", "b1") { () => testActor ! "B" Future.failed(new RuntimeException("Was expected to not be executed")) } - co.addTask("c", "c1") { () ⇒ + co.addTask("c", "c1") { () => testActor ! "C" Future.successful(Done) } @@ -286,12 +286,12 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( "be possible to add tasks in later phase from task in earlier phase" in { val phases = Map( - "a" → emptyPhase, - "b" → phase("a")) + "a" -> emptyPhase, + "b" -> phase("a")) val co = new CoordinatedShutdown(extSys, phases) - co.addTask("a", "a1") { () ⇒ + co.addTask("a", "a1") { () => testActor ! "A" - co.addTask("b", "b1") { () ⇒ + co.addTask("b", "b1") { () => testActor ! "B" Future.successful(Done) } @@ -318,9 +318,9 @@ class CoordinatedShutdownSpec extends AkkaSpec(ConfigFactory.parseString( } } """)) should ===(Map( - "a" → Phase(dependsOn = Set.empty, timeout = 10.seconds, recover = true, enabled = true), - "b" → Phase(dependsOn = Set("a"), timeout = 15.seconds, recover = true, enabled = true), - "c" → Phase(dependsOn = Set("a", "b"), timeout = 10.seconds, recover = false, enabled = true))) + "a" -> Phase(dependsOn = Set.empty, timeout = 10.seconds, recover = true, enabled = true), + "b" -> Phase(dependsOn = Set("a"), timeout = 15.seconds, recover = true, enabled = true), + "c" -> Phase(dependsOn = Set("a", "b"), timeout = 10.seconds, recover = false, enabled = true))) } "default exit code to 0" in { diff --git a/akka-actor-tests/src/test/scala/akka/actor/DeathWatchSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/DeathWatchSpec.scala index 9833cc8181..bbb688c844 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/DeathWatchSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/DeathWatchSpec.scala @@ -20,8 +20,8 @@ object DeathWatchSpec { class Watcher(target: ActorRef, testActor: ActorRef) extends Actor { context.watch(target) def receive = { - case t: Terminated ⇒ testActor forward WrappedTerminated(t) - case x ⇒ testActor forward x + case t: Terminated => testActor forward WrappedTerminated(t) + case x => testActor forward x } } @@ -35,11 +35,11 @@ object DeathWatchSpec { class NKOTBWatcher(testActor: ActorRef) extends Actor { def receive = { - case "NKOTB" ⇒ - val currentKid = context.watch(context.actorOf(Props(new Actor { def receive = { case "NKOTB" ⇒ context stop self } }), "kid")) + case "NKOTB" => + val currentKid = context.watch(context.actorOf(Props(new Actor { def receive = { case "NKOTB" => context stop self } }), "kid")) currentKid forward "NKOTB" context become { - case Terminated(`currentKid`) ⇒ + case Terminated(`currentKid`) => testActor ! "GREEN" context unbecome } @@ -48,9 +48,9 @@ object DeathWatchSpec { class WUWatcher extends Actor { def receive = { - case W(ref) ⇒ context watch ref - case U(ref) ⇒ context unwatch ref - case Latches(t1: TestLatch, t2: TestLatch) ⇒ + case W(ref) => context watch ref + case U(ref) => context unwatch ref + case Latches(t1: TestLatch, t2: TestLatch) => t1.countDown() Await.ready(t2, 3.seconds) } @@ -69,7 +69,7 @@ object DeathWatchSpec { final case class Latches(t1: TestLatch, t2: TestLatch) extends NoSerializationVerificationNeeded } -trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout ⇒ +trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout => import DeathWatchSpec._ @@ -79,7 +79,7 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout "The Death Watch" must { def expectTerminationOf(actorRef: ActorRef) = expectMsgPF(5 seconds, actorRef + ": Stopped or Already terminated when linking") { - case WrappedTerminated(Terminated(`actorRef`)) ⇒ true + case WrappedTerminated(Terminated(`actorRef`)) => true } "notify with one Terminated message when an Actor is stopped" in { @@ -123,8 +123,8 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout context.watch(terminal) context.unwatch(terminal) def receive = { - case "ping" ⇒ sender() ! "pong" - case t: Terminated ⇒ testActor ! WrappedTerminated(t) + case "ping" => sender() ! "pong" + case t: Terminated => testActor ! WrappedTerminated(t) } }).withDeploy(Deploy.local)) @@ -180,9 +180,9 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout failed ! Kill val result = receiveWhile(3 seconds, messages = 3) { - case FF(Failed(_, _: ActorKilledException, _)) if lastSender eq failed ⇒ 1 - case FF(Failed(_, DeathPactException(`failed`), _)) if lastSender eq brother ⇒ 2 - case WrappedTerminated(Terminated(`brother`)) ⇒ 3 + case FF(Failed(_, _: ActorKilledException, _)) if lastSender eq failed => 1 + case FF(Failed(_, DeathPactException(`failed`), _)) if lastSender eq brother => 2 + case WrappedTerminated(Terminated(`brother`)) => 3 } testActor.isTerminated should not be true result should ===(Seq(1, 2, 3)) diff --git a/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala index 2a4fee3cb5..4d853b89e2 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala @@ -70,7 +70,7 @@ object DeployerSpec { """, ConfigParseOptions.defaults) class RecipeActor extends Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } } } @@ -227,8 +227,8 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) { deployment.get.routerConfig.getClass should ===(expected.getClass) deployment.get.scope should ===(NoScopeGiven) expected match { - case pool: Pool ⇒ deployment.get.routerConfig.asInstanceOf[Pool].resizer should ===(pool.resizer) - case _ ⇒ + case pool: Pool => deployment.get.routerConfig.asInstanceOf[Pool].resizer should ===(pool.resizer) + case _ => } } } diff --git a/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala index a191fb5f81..1a04d81a99 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala @@ -34,37 +34,37 @@ object FSMActorSpec { class Lock(code: String, timeout: FiniteDuration, latches: Latches) extends Actor with FSM[LockState, CodeState] { import latches._ - import FSM.`→` + import FSM.`->` startWith(Locked, CodeState("", code)) when(Locked) { - case Event(digit: Char, CodeState(soFar, code)) ⇒ { + case Event(digit: Char, CodeState(soFar, code)) => { soFar + digit match { - case incomplete if incomplete.length < code.length ⇒ + case incomplete if incomplete.length < code.length => stay using CodeState(incomplete, code) - case codeTry if (codeTry == code) ⇒ { + case codeTry if (codeTry == code) => { doUnlock() goto(Open) using CodeState("", code) forMax timeout } - case wrong ⇒ { + case wrong => { stay using CodeState("", code) } } } - case Event("hello", _) ⇒ stay replying "world" - case Event("bye", _) ⇒ stop(FSM.Shutdown) + case Event("hello", _) => stay replying "world" + case Event("bye", _) => stop(FSM.Shutdown) } when(Open) { - case Event(StateTimeout, _) ⇒ { + case Event(StateTimeout, _) => { doLock() goto(Locked) } } whenUnhandled { - case Event(msg, _) ⇒ { + case Event(msg, _) => { log.warning("unhandled event " + msg + " in state " + stateName + " with data " + stateData) unhandledLatch.open stay @@ -72,7 +72,7 @@ object FSMActorSpec { } onTransition { - case Locked → Open ⇒ transitionLatch.open + case Locked -> Open => transitionLatch.open } // verify that old-style does still compile @@ -83,7 +83,7 @@ object FSMActorSpec { } onTermination { - case StopEvent(FSM.Shutdown, Locked, _) ⇒ + case StopEvent(FSM.Shutdown, Locked, _) => // stop is called from lockstate with shutdown as reason... terminatedLatch.open() } @@ -99,9 +99,9 @@ object FSMActorSpec { final case class CodeState(soFar: String, code: String) } -class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with ImplicitSender { +class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" -> true)) with ImplicitSender { import FSMActorSpec._ - import FSM.`→` + import FSM.`->` val timeout = Timeout(2 seconds) @@ -119,8 +119,8 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I val transitionTester = system.actorOf(Props(new Actor { def receive = { - case Transition(_, _, _) ⇒ transitionCallBackLatch.open - case CurrentState(_, s: LockState) if s eq Locked ⇒ initialStateLatch.open // SI-5900 workaround + case Transition(_, _, _) => transitionCallBackLatch.open + case CurrentState(_, s: LockState) if s eq Locked => initialStateLatch.open // SI-5900 workaround } })) @@ -146,9 +146,9 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I val answerLatch = TestLatch() val tester = system.actorOf(Props(new Actor { def receive = { - case Hello ⇒ lock ! "hello" - case "world" ⇒ answerLatch.open - case Bye ⇒ lock ! "bye" + case Hello => lock ! "hello" + case "world" => answerLatch.open + case Bye => lock ! "bye" } })) tester ! Hello @@ -162,7 +162,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I val fsm = TestActorRef(new Actor with FSM[Int, Null] { startWith(1, null) when(1) { - case Event("go", _) ⇒ goto(2) + case Event("go", _) => goto(2) } }) val name = fsm.path.toString @@ -170,7 +170,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I system.eventStream.subscribe(testActor, classOf[Logging.Error]) fsm ! "go" expectMsgPF(1 second, hint = "Next state 2 does not exist") { - case Logging.Error(_, `name`, _, "Next state 2 does not exist") ⇒ true + case Logging.Error(_, `name`, _, "Next state 2 does not exist") => true } system.eventStream.unsubscribe(testActor) } @@ -187,7 +187,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I startWith(1, null) when(1) { FSM.NullFunction } onTermination { - case x ⇒ testActor ! x + case x => testActor ! x } } val ref = system.actorOf(Props(fsm)) @@ -201,10 +201,10 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I val actor = system.actorOf(Props(new Actor with FSM[Int, String] { startWith(1, null) when(1) { - case Event(2, null) ⇒ stop(FSM.Normal, expected) + case Event(2, null) => stop(FSM.Normal, expected) } onTermination { - case StopEvent(FSM.Normal, 1, `expected`) ⇒ testActor ! "green" + case StopEvent(FSM.Normal, 1, `expected`) => testActor ! "green" } })) actor ! 2 @@ -218,17 +218,17 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I lazy val fsmref = TestFSMRef(new Actor with FSM[String, Null] { startWith("not-started", null) when("not-started") { - case Event("start", _) ⇒ goto("started") replying "starting" + case Event("start", _) => goto("started") replying "starting" } when("started", stateTimeout = 10 seconds) { - case Event("stop", _) ⇒ stop() + case Event("stop", _) => stop() } onTransition { - case "not-started" → "started" ⇒ - for (timerName ← timerNames) setTimer(timerName, (), 10 seconds, false) + case "not-started" -> "started" => + for (timerName <- timerNames) setTimer(timerName, (), 10 seconds, false) } onTermination { - case _ ⇒ { + case _ => { checkTimersActive(false) testActor ! "stopped" } @@ -236,7 +236,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I }) def checkTimersActive(active: Boolean): Unit = { - for (timer ← timerNames) fsmref.isTimerActive(timer) should ===(active) + for (timer <- timerNames) fsmref.isTimerActive(timer) should ===(active) fsmref.isStateTimerActive should ===(active) } @@ -252,8 +252,8 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I "log events and transitions if asked to do so" in { import scala.collection.JavaConverters._ - val config = ConfigFactory.parseMap(Map("akka.loglevel" → "DEBUG", "akka.actor.serialize-messages" → "off", - "akka.actor.debug.fsm" → true).asJava).withFallback(system.settings.config) + val config = ConfigFactory.parseMap(Map("akka.loglevel" -> "DEBUG", "akka.actor.serialize-messages" -> "off", + "akka.actor.debug.fsm" -> true).asJava).withFallback(system.settings.config) val fsmEventSystem = ActorSystem("fsmEvent", config) try { new TestKit(fsmEventSystem) { @@ -261,17 +261,17 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I val fsm = TestActorRef(new Actor with LoggingFSM[Int, Null] { startWith(1, null) when(1) { - case Event("go", _) ⇒ + case Event("go", _) => setTimer("t", FSM.Shutdown, 1.5 seconds, false) goto(2) } when(2) { - case Event("stop", _) ⇒ + case Event("stop", _) => cancelTimer("t") stop } onTermination { - case StopEvent(r, _, _) ⇒ testActor ! r + case StopEvent(r, _, _) => testActor ! r } }) val name = fsm.path.toString @@ -279,13 +279,13 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I system.eventStream.subscribe(testActor, classOf[Logging.Debug]) fsm ! "go" expectMsgPF(1 second, hint = "processing Event(go,null)") { - case Logging.Debug(`name`, `fsmClass`, s: String) if s.startsWith("processing Event(go,null) from Actor[") ⇒ true + case Logging.Debug(`name`, `fsmClass`, s: String) if s.startsWith("processing Event(go,null) from Actor[") => true } expectMsg(1 second, Logging.Debug(name, fsmClass, "setting timer 't'/1500 milliseconds: Shutdown")) expectMsg(1 second, Logging.Debug(name, fsmClass, "transition 1 -> 2")) fsm ! "stop" expectMsgPF(1 second, hint = "processing Event(stop,null)") { - case Logging.Debug(`name`, `fsmClass`, s: String) if s.startsWith("processing Event(stop,null) from Actor[") ⇒ true + case Logging.Debug(`name`, `fsmClass`, s: String) if s.startsWith("processing Event(stop,null) from Actor[") => true } expectMsgAllOf(1 second, Logging.Debug(name, fsmClass, "canceling timer 't'"), FSM.Normal) expectNoMsg(1 second) @@ -302,8 +302,8 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I override def logDepth = 3 startWith(1, 0) when(1) { - case Event("count", c) ⇒ stay using (c + 1) - case Event("log", _) ⇒ stay replying getLog + case Event("count", c) => stay using (c + 1) + case Event("log", _) => stay replying getLog } }) fsmref ! "log" @@ -323,12 +323,12 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I val fsmref = system.actorOf(Props(new Actor with FSM[Int, Int] { startWith(0, 0) when(0)(transform { - case Event("go", _) ⇒ stay + case Event("go", _) => stay } using { - case x ⇒ goto(1) + case x => goto(1) }) when(1) { - case _ ⇒ stay + case _ => stay } })) fsmref ! SubscribeTransitionCallBack(testActor) @@ -348,11 +348,11 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" → true)) with I startWith("init", "") when("init", stateTimeout = 300.millis) { - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => p.ref ! StateTimeout stay() - case Event(OverrideTimeoutToInf, _) ⇒ + case Event(OverrideTimeoutToInf, _) => p.ref ! OverrideTimeoutToInf stay() forMax Duration.Inf } diff --git a/akka-actor-tests/src/test/scala/akka/actor/FSMTimingSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FSMTimingSpec.scala index cee6268afb..551eefb494 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/FSMTimingSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/FSMTimingSpec.scala @@ -18,7 +18,7 @@ class FSMTimingSpec extends AkkaSpec with ImplicitSender { expectMsg(1 second, CurrentState(fsm, Initial)) ignoreMsg { - case Transition(_, bs: FSMTimingSpec.State, _) if bs eq Initial ⇒ true // SI-5900 workaround + case Transition(_, bs: FSMTimingSpec.State, _) if bs eq Initial => true // SI-5900 workaround } "A Finite State Machine" must { @@ -120,7 +120,7 @@ class FSMTimingSpec extends AkkaSpec with ImplicitSender { "receive and cancel a repeated timer" taggedAs TimingTest in { fsm ! TestRepeatedTimer val seq = receiveWhile(2 seconds) { - case Tick ⇒ Tick + case Tick => Tick } seq should have length 5 within(500 millis) { @@ -152,13 +152,13 @@ class FSMTimingSpec extends AkkaSpec with ImplicitSender { object FSMTimingSpec { def suspend(actorRef: ActorRef): Unit = actorRef match { - case l: ActorRefWithCell ⇒ l.suspend() - case _ ⇒ + case l: ActorRefWithCell => l.suspend() + case _ => } def resume(actorRef: ActorRef): Unit = actorRef match { - case l: ActorRefWithCell ⇒ l.resume(causedByFailure = null) - case _ ⇒ + case l: ActorRefWithCell => l.resume(causedByFailure = null) + case _ => } trait State @@ -189,54 +189,54 @@ object FSMTimingSpec { startWith(Initial, 0) when(Initial) { - case Event(TestSingleTimer, _) ⇒ + case Event(TestSingleTimer, _) => setTimer("tester", Tick, 500.millis.dilated, false) goto(TestSingleTimer) - case Event(TestRepeatedTimer, _) ⇒ + case Event(TestRepeatedTimer, _) => setTimer("tester", Tick, 100.millis.dilated, true) goto(TestRepeatedTimer) using 4 - case Event(TestStateTimeoutOverride, _) ⇒ + case Event(TestStateTimeoutOverride, _) => goto(TestStateTimeout) forMax (Duration.Inf) - case Event(x: FSMTimingSpec.State, _) ⇒ goto(x) + case Event(x: FSMTimingSpec.State, _) => goto(x) } when(TestStateTimeout, stateTimeout = 800.millis.dilated) { - case Event(StateTimeout, _) ⇒ goto(Initial) - case Event(Cancel, _) ⇒ goto(Initial) replying (Cancel) + case Event(StateTimeout, _) => goto(Initial) + case Event(Cancel, _) => goto(Initial) replying (Cancel) } when(TestSingleTimer) { - case Event(Tick, _) ⇒ + case Event(Tick, _) => tester ! Tick goto(Initial) } onTransition { - case Initial → TestSingleTimerResubmit ⇒ setTimer("blah", Tick, 500.millis.dilated) + case Initial -> TestSingleTimerResubmit => setTimer("blah", Tick, 500.millis.dilated) } when(TestSingleTimerResubmit) { - case Event(Tick, _) ⇒ + case Event(Tick, _) => tester ! Tick setTimer("blah", Tock, 500.millis.dilated) stay() - case Event(Tock, _) ⇒ + case Event(Tock, _) => tester ! Tock goto(Initial) } when(TestCancelTimer) { - case Event(Tick, _) ⇒ + case Event(Tick, _) => setTimer("hallo", Tock, 1.milli.dilated) TestKit.awaitCond(context.asInstanceOf[ActorCell].mailbox.hasMessages, 1.second.dilated) cancelTimer("hallo") sender() ! Tick setTimer("hallo", Tock, 500.millis.dilated) stay - case Event(Tock, _) ⇒ + case Event(Tock, _) => tester ! Tock stay - case Event(Cancel, _) ⇒ + case Event(Cancel, _) => cancelTimer("hallo") goto(Initial) } when(TestRepeatedTimer) { - case Event(Tick, remaining) ⇒ + case Event(Tick, remaining) => tester ! Tick if (remaining == 0) { cancelTimer("tester") @@ -247,29 +247,29 @@ object FSMTimingSpec { } when(TestCancelStateTimerInNamedTimerMessage) { // FSM is suspended after processing this message and resumed 500ms later - case Event(Tick, _) ⇒ + case Event(Tick, _) => suspend(self) setTimer("named", Tock, 1.millis.dilated) TestKit.awaitCond(context.asInstanceOf[ActorCell].mailbox.hasMessages, 1.second.dilated) stay forMax (1.millis.dilated) replying Tick - case Event(Tock, _) ⇒ + case Event(Tock, _) => goto(TestCancelStateTimerInNamedTimerMessage2) } when(TestCancelStateTimerInNamedTimerMessage2) { - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => goto(Initial) - case Event(Cancel, _) ⇒ + case Event(Cancel, _) => goto(Initial) replying Cancel } when(TestUnhandled) { - case Event(SetHandler, _) ⇒ + case Event(SetHandler, _) => whenUnhandled { - case Event(Tick, _) ⇒ + case Event(Tick, _) => tester ! Unhandled(Tick) stay } stay - case Event(Cancel, _) ⇒ + case Event(Cancel, _) => whenUnhandled(NullFunction) goto(Initial) } @@ -279,7 +279,7 @@ object FSMTimingSpec { startWith(Initial, 0) when(Initial, 200 millis) { - case Event(TestStoppingActorStateTimeout, _) ⇒ + case Event(TestStoppingActorStateTimeout, _) => context.stop(self) stay } diff --git a/akka-actor-tests/src/test/scala/akka/actor/FSMTransitionSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FSMTransitionSpec.scala index 7f79c41467..fc951aa4f7 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/FSMTransitionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/FSMTransitionSpec.scala @@ -10,19 +10,19 @@ import scala.concurrent.duration._ import scala.language.postfixOps object FSMTransitionSpec { - import FSM.`→` + import FSM.`->` class Supervisor extends Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } } class SendAnyTransitionFSM(target: ActorRef) extends Actor with FSM[Int, Int] { startWith(0, 0) when(0) { - case Event("stay", _) ⇒ stay() - case Event(_, _) ⇒ goto(0) + case Event("stay", _) => stay() + case Event(_, _) => goto(0) } - onTransition { case from → to ⇒ target ! (from → to) } + onTransition { case from -> to => target ! (from -> to) } initialize() } @@ -30,13 +30,13 @@ object FSMTransitionSpec { class MyFSM(target: ActorRef) extends Actor with FSM[Int, Unit] { startWith(0, Unit) when(0) { - case Event("tick", _) ⇒ goto(1) + case Event("tick", _) => goto(1) } when(1) { - case Event("tick", _) ⇒ goto(0) + case Event("tick", _) => goto(0) } whenUnhandled { - case Event("reply", _) ⇒ stay replying "reply" + case Event("reply", _) => stay replying "reply" } initialize() override def preRestart(reason: Throwable, msg: Option[Any]): Unit = { target ! "restarted" } @@ -45,20 +45,20 @@ object FSMTransitionSpec { class OtherFSM(target: ActorRef) extends Actor with FSM[Int, Int] { startWith(0, 0) when(0) { - case Event("tick", _) ⇒ goto(1) using 1 - case Event("stay", _) ⇒ stay() + case Event("tick", _) => goto(1) using 1 + case Event("stay", _) => stay() } when(1) { - case _ ⇒ goto(1) + case _ => goto(1) } onTransition { - case 0 → 1 ⇒ target ! ((stateData, nextStateData)) - case 1 → 1 ⇒ target ! ((stateData, nextStateData)) + case 0 -> 1 => target ! ((stateData, nextStateData)) + case 1 -> 1 => target ! ((stateData, nextStateData)) } } class Forwarder(target: ActorRef) extends Actor { - def receive = { case x ⇒ target ! x } + def receive = { case x => target ! x } } } @@ -66,17 +66,17 @@ object FSMTransitionSpec { class FSMTransitionSpec extends AkkaSpec with ImplicitSender { import FSMTransitionSpec._ - import FSM.`→` + import FSM.`->` "A FSM transition notifier" must { "not trigger onTransition for stay" in { val fsm = system.actorOf(Props(new SendAnyTransitionFSM(testActor))) - expectMsg(0 → 0) // caused by initialize(), OK. + expectMsg(0 -> 0) // caused by initialize(), OK. fsm ! "stay" // no transition event expectNoMsg(500.millis) fsm ! "goto" // goto(current state) - expectMsg(0 → 0) + expectMsg(0 -> 0) } "notify listeners" in { @@ -150,17 +150,17 @@ class FSMTransitionSpec extends AkkaSpec with ImplicitSender { val fsmref = system.actorOf(Props(new Actor with FSM[Int, ActorRef] { startWith(0, null) when(0) { - case Event("switch", _) ⇒ goto(1) using sender() + case Event("switch", _) => goto(1) using sender() } onTransition { - case x → y ⇒ nextStateData ! (x → y) + case x -> y => nextStateData ! (x -> y) } when(1) { - case Event("test", _) ⇒ + case Event("test", _) => try { sender() ! s"failed: $nextStateData" } catch { - case _: IllegalStateException ⇒ sender() ! "ok" + case _: IllegalStateException => sender() ! "ok" } stay() } diff --git a/akka-actor-tests/src/test/scala/akka/actor/ForwardActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ForwardActorSpec.scala index 59bdb6e146..71a64b4a1b 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ForwardActorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ForwardActorSpec.scala @@ -15,12 +15,12 @@ object ForwardActorSpec { def createForwardingChain(system: ActorSystem): ActorRef = { val replier = system.actorOf(Props(new Actor { - def receive = { case x ⇒ sender() ! x } + def receive = { case x => sender() ! x } })) def mkforwarder(forwardTo: ActorRef) = system.actorOf(Props( new Actor { - def receive = { case x ⇒ forwardTo forward x } + def receive = { case x => forwardTo forward x } })) mkforwarder(mkforwarder(mkforwarder(replier))) @@ -33,7 +33,7 @@ class ForwardActorSpec extends AkkaSpec { "A Forward Actor" must { "forward actor reference when invoking forward on tell" in { - val replyTo = system.actorOf(Props(new Actor { def receive = { case ExpectedMessage ⇒ testActor ! ExpectedMessage } })) + val replyTo = system.actorOf(Props(new Actor { def receive = { case ExpectedMessage => testActor ! ExpectedMessage } })) val chain = createForwardingChain(system) diff --git a/akka-actor-tests/src/test/scala/akka/actor/FunctionRefSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FunctionRefSpec.scala index 6334c7e26f..f40c0f2f48 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/FunctionRefSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/FunctionRefSpec.scala @@ -18,11 +18,11 @@ object FunctionRefSpec { class Super extends Actor { def receive = { - case GetForwarder(replyTo) ⇒ + case GetForwarder(replyTo) => val cell = context.asInstanceOf[ActorCell] - val ref = cell.addFunctionRef((sender, msg) ⇒ replyTo ! Forwarded(msg, sender)) + val ref = cell.addFunctionRef((sender, msg) => replyTo ! Forwarded(msg, sender)) replyTo ! ref - case DropForwarder(ref) ⇒ + case DropForwarder(ref) => val cell = context.asInstanceOf[ActorCell] cell.removeFunctionRef(ref) } @@ -31,7 +31,7 @@ object FunctionRefSpec { class SupSuper extends Actor { val s = context.actorOf(Props[Super], "super") def receive = { - case msg ⇒ s ! msg + case msg => s ! msg } } @@ -93,7 +93,7 @@ class FunctionRefSpec extends AkkaSpec with ImplicitSender { "not registered" must { "not be found" in { val provider = system.asInstanceOf[ExtendedActorSystem].provider - val ref = new FunctionRef(testActor.path / "blabla", provider, system, (_, _) ⇒ ()) + val ref = new FunctionRef(testActor.path / "blabla", provider, system, (_, _) => ()) EventFilter[SerializationCheckFailedException](start = "Failed to serialize and deserialize message of type akka.actor.FunctionRefSpec", occurrences = 1) intercept { // needs to be something that fails when the deserialized form is not a FunctionRef // this relies upon serialize-messages during tests diff --git a/akka-actor-tests/src/test/scala/akka/actor/HotSwapSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/HotSwapSpec.scala index 539e7822c9..9450985103 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/HotSwapSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/HotSwapSpec.scala @@ -18,8 +18,8 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender { "An Actor" must { "be able to become in its constructor" in { val a = system.actorOf(Props(new Becomer { - context.become { case always ⇒ sender() ! always } - def receive = { case _ ⇒ sender() ! "FAILURE" } + context.become { case always => sender() ! always } + def receive = { case _ => sender() ! "FAILURE" } })) a ! "pigdog" expectMsg("pigdog") @@ -27,8 +27,8 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender { "be able to become multiple times in its constructor" in { val a = system.actorOf(Props(new Becomer { - for (i ← 1 to 4) context.become({ case always ⇒ sender() ! i + ":" + always }) - def receive = { case _ ⇒ sender() ! "FAILURE" } + for (i <- 1 to 4) context.become({ case always => sender() ! i + ":" + always }) + def receive = { case _ => sender() ! "FAILURE" } })) a ! "pigdog" expectMsg("4:pigdog") @@ -36,8 +36,8 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender { "be able to become with stacking in its constructor" in { val a = system.actorOf(Props(new Becomer { - context.become({ case always ⇒ sender() ! "pigdog:" + always; context.unbecome() }, false) - def receive = { case always ⇒ sender() ! "badass:" + always } + context.become({ case always => sender() ! "pigdog:" + always; context.unbecome() }, false) + def receive = { case always => sender() ! "badass:" + always } })) a ! "pigdog" expectMsg("pigdog:pigdog") @@ -47,8 +47,8 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender { "be able to become, with stacking, multiple times in its constructor" in { val a = system.actorOf(Props(new Becomer { - for (i ← 1 to 4) context.become({ case always ⇒ sender() ! i + ":" + always; context.unbecome() }, false) - def receive = { case _ ⇒ sender() ! "FAILURE" } + for (i <- 1 to 4) context.become({ case always => sender() ! i + ":" + always; context.unbecome() }, false) + def receive = { case _ => sender() ! "FAILURE" } })) a ! "pigdog" a ! "pigdog" @@ -63,8 +63,8 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender { "be able to hotswap its behavior with become(..)" in { val a = system.actorOf(Props(new Actor { def receive = { - case "init" ⇒ sender() ! "init" - case "swap" ⇒ context.become({ case x: String ⇒ context.sender() ! x }) + case "init" => sender() ! "init" + case "swap" => context.become({ case x: String => context.sender() ! x }) } })) @@ -78,10 +78,10 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender { "be able to revert hotswap its behavior with unbecome" in { val a = system.actorOf(Props(new Actor { def receive = { - case "init" ⇒ sender() ! "init" - case "swap" ⇒ context.become({ - case "swapped" ⇒ sender() ! "swapped" - case "revert" ⇒ context.unbecome() + case "init" => sender() ! "init" + case "swap" => context.become({ + case "swapped" => sender() ! "swapped" + case "revert" => context.unbecome() }) } })) @@ -102,12 +102,12 @@ class HotSwapSpec extends AkkaSpec with ImplicitSender { val a = system.actorOf(Props(new Actor { def receive = { - case "state" ⇒ sender() ! "0" - case "swap" ⇒ + case "state" => sender() ! "0" + case "swap" => context.become({ - case "state" ⇒ sender() ! "1" - case "swapped" ⇒ sender() ! "swapped" - case "crash" ⇒ throw new Exception("Crash (expected)!") + case "state" => sender() ! "1" + case "swapped" => sender() ! "swapped" + case "crash" => throw new Exception("Crash (expected)!") }) sender() ! "swapped" } diff --git a/akka-actor-tests/src/test/scala/akka/actor/LocalActorRefProviderSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/LocalActorRefProviderSpec.scala index 2891c633dc..82bf819cc7 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/LocalActorRefProviderSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/LocalActorRefProviderSpec.scala @@ -34,7 +34,7 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi "An LocalActorRefProvider" must { "find actor refs using actorFor" in { - val a = system.actorOf(Props(new Actor { def receive = { case _ ⇒ } })) + val a = system.actorOf(Props(new Actor { def receive = { case _ => } })) val b = system.actorFor(a.path) a should ===(b) } @@ -44,7 +44,7 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi val a = system.actorOf(Props(new Actor { val child = context.actorOf(Props.empty, name = childName) def receive = { - case "lookup" ⇒ + case "lookup" => if (childName == child.path.name) sender() ! context.actorFor(childName) else sender() ! s"$childName is not ${child.path.name}!" } @@ -102,7 +102,7 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi val GetChild = "GetChild" val a = watch(system.actorOf(Props(new Actor { val child = context.actorOf(Props.empty) - def receive = { case `GetChild` ⇒ sender() ! child } + def receive = { case `GetChild` => sender() ! child } }))) a.tell(GetChild, testActor) val child = expectMsgType[ActorRef] @@ -128,14 +128,14 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi provider.isInstanceOf[LocalActorRefProvider] should ===(true) - for (i ← 0 until 100) { + for (i <- 0 until 100) { val address = "new-actor" + i implicit val timeout = Timeout(5 seconds) - val actors = for (j ← 1 to 4) yield Future(system.actorOf(Props(new Actor { def receive = { case _ ⇒ } }), address)) - val set = Set() ++ actors.map(a ⇒ Await.ready(a, timeout.duration).value match { - case Some(Success(a: ActorRef)) ⇒ 1 - case Some(Failure(ex: InvalidActorNameException)) ⇒ 2 - case x ⇒ x + val actors = for (j <- 1 to 4) yield Future(system.actorOf(Props(new Actor { def receive = { case _ => } }), address)) + val set = Set() ++ actors.map(a => Await.ready(a, timeout.duration).value match { + case Some(Success(a: ActorRef)) => 1 + case Some(Failure(ex: InvalidActorNameException)) => 2 + case x => x }) set should ===(Set[Any](1, 2)) } @@ -144,7 +144,7 @@ class LocalActorRefProviderSpec extends AkkaSpec(LocalActorRefProviderSpec.confi "only create one instance of an actor from within the same message invocation" in { val supervisor = system.actorOf(Props(new Actor { def receive = { - case "" ⇒ + case "" => val a, b = context.actorOf(Props.empty, "duplicate") } })) diff --git a/akka-actor-tests/src/test/scala/akka/actor/ReceiveTimeoutSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ReceiveTimeoutSpec.scala index 3ef2460238..1cc11c4b4c 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ReceiveTimeoutSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ReceiveTimeoutSpec.scala @@ -28,7 +28,7 @@ class ReceiveTimeoutSpec extends AkkaSpec { context.setReceiveTimeout(500 milliseconds) def receive = { - case ReceiveTimeout ⇒ timeoutLatch.open + case ReceiveTimeout => timeoutLatch.open } })) @@ -43,8 +43,8 @@ class ReceiveTimeoutSpec extends AkkaSpec { context.setReceiveTimeout(500 milliseconds) def receive = { - case Tick ⇒ () - case ReceiveTimeout ⇒ timeoutLatch.open + case Tick => () + case ReceiveTimeout => timeoutLatch.open } })) @@ -62,8 +62,8 @@ class ReceiveTimeoutSpec extends AkkaSpec { context.setReceiveTimeout(500 milliseconds) def receive = { - case Tick ⇒ () - case ReceiveTimeout ⇒ + case Tick => () + case ReceiveTimeout => count.incrementAndGet timeoutLatch.open context.setReceiveTimeout(Duration.Undefined) @@ -82,7 +82,7 @@ class ReceiveTimeoutSpec extends AkkaSpec { val timeoutActor = system.actorOf(Props(new Actor { def receive = { - case ReceiveTimeout ⇒ timeoutLatch.open + case ReceiveTimeout => timeoutLatch.open } })) @@ -97,8 +97,8 @@ class ReceiveTimeoutSpec extends AkkaSpec { context.setReceiveTimeout(1 second) def receive = { - case ReceiveTimeout ⇒ timeoutLatch.open - case TransperentTick ⇒ + case ReceiveTimeout => timeoutLatch.open + case TransperentTick => } })) @@ -121,10 +121,10 @@ class ReceiveTimeoutSpec extends AkkaSpec { context.setReceiveTimeout(1 second) def receive = { - case ReceiveTimeout ⇒ + case ReceiveTimeout => self ! TransperentTick timeoutLatch.countDown() - case TransperentTick ⇒ + case TransperentTick => } })) @@ -142,9 +142,9 @@ class ReceiveTimeoutSpec extends AkkaSpec { context.setReceiveTimeout(1 second) def receive: Receive = { - case ReceiveTimeout ⇒ + case ReceiveTimeout => timeoutLatch.open - case TransperentTick ⇒ + case TransperentTick => count.incrementAndGet() } } @@ -161,8 +161,8 @@ class ReceiveTimeoutSpec extends AkkaSpec { val timeoutActor = system.actorOf(Props(new Actor { def receive = { - case TransperentTick ⇒ context.setReceiveTimeout(500 milliseconds) - case ReceiveTimeout ⇒ timeoutLatch.open + case TransperentTick => context.setReceiveTimeout(500 milliseconds) + case ReceiveTimeout => timeoutLatch.open } })) @@ -179,8 +179,8 @@ class ReceiveTimeoutSpec extends AkkaSpec { context.setReceiveTimeout(500 milliseconds) def receive = { - case TransperentTick ⇒ context.setReceiveTimeout(Duration.Inf) - case ReceiveTimeout ⇒ timeoutLatch.open + case TransperentTick => context.setReceiveTimeout(Duration.Inf) + case ReceiveTimeout => timeoutLatch.open } })) diff --git a/akka-actor-tests/src/test/scala/akka/actor/RestartStrategySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/RestartStrategySpec.scala index 3a706ee96e..dc3ee3c228 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/RestartStrategySpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/RestartStrategySpec.scala @@ -39,8 +39,8 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off" val slaveProps = Props(new Actor { def receive = { - case Ping ⇒ countDownLatch.countDown() - case Crash ⇒ throw new Exception("Crashing...") + case Ping => countDownLatch.countDown() + case Crash => throw new Exception("Crashing...") } override def postRestart(reason: Throwable) = { @@ -82,7 +82,7 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off" val slaveProps = Props(new Actor { def receive = { - case Crash ⇒ throw new Exception("Crashing...") + case Crash => throw new Exception("Crashing...") } override def postRestart(reason: Throwable) = { @@ -91,7 +91,7 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off" }) val slave = Await.result((boss ? slaveProps).mapTo[ActorRef], timeout.duration) - (1 to 100) foreach { _ ⇒ slave ! Crash } + (1 to 100) foreach { _ => slave ! Crash } Await.ready(countDownLatch, 2 minutes) assert(!slave.isTerminated) } @@ -109,9 +109,9 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off" val slaveProps = Props(new Actor { def receive = { - case Ping ⇒ + case Ping => if (!pingLatch.isOpen) pingLatch.open else secondPingLatch.open - case Crash ⇒ throw new Exception("Crashing...") + case Crash => throw new Exception("Crashing...") } override def postRestart(reason: Throwable) = { if (!restartLatch.isOpen) @@ -165,8 +165,8 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off" val slaveProps = Props(new Actor { def receive = { - case Ping ⇒ countDownLatch.countDown() - case Crash ⇒ throw new Exception("Crashing...") + case Ping => countDownLatch.countDown() + case Crash => throw new Exception("Crashing...") } override def postRestart(reason: Throwable) = { if (!restartLatch.isOpen) @@ -212,16 +212,16 @@ class RestartStrategySpec extends AkkaSpec("akka.actor.serialize-messages = off" val boss = system.actorOf(Props(new Actor { override val supervisorStrategy = OneForOneStrategy(withinTimeRange = 1 second)(List(classOf[Throwable])) def receive = { - case p: Props ⇒ sender() ! context.watch(context.actorOf(p)) - case t: Terminated ⇒ maxNoOfRestartsLatch.open() + case p: Props => sender() ! context.watch(context.actorOf(p)) + case t: Terminated => maxNoOfRestartsLatch.open() } })) val slaveProps = Props(new Actor { def receive = { - case Ping ⇒ countDownLatch.countDown() - case Crash ⇒ throw new Exception("Crashing...") + case Ping => countDownLatch.countDown() + case Crash => throw new Exception("Crashing...") } override def postRestart(reason: Throwable) = { diff --git a/akka-actor-tests/src/test/scala/akka/actor/SchedulerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SchedulerSpec.scala index f7b661f46e..16e96e8464 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/SchedulerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/SchedulerSpec.scala @@ -27,7 +27,7 @@ object SchedulerSpec { """).withFallback(AkkaSpec.testConf) } -trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with ImplicitSender { this: AkkaSpec ⇒ +trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with ImplicitSender { this: AkkaSpec => import system.dispatcher def collectCancellable(c: Cancellable): Cancellable @@ -41,7 +41,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit val tickActor, tickActor2 = system.actorOf(Props(new Actor { var ticks = 0 def receive = { - case Tick ⇒ + case Tick => if (ticks < 3) { sender() ! Tock ticks += 1 @@ -67,7 +67,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit } "stop continuous scheduling if the receiving actor has been terminated" taggedAs TimingTest in { - val actor = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } })) + val actor = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } })) // run immediately and then every 100 milliseconds collectCancellable(system.scheduler.schedule(0 milliseconds, 100 milliseconds, actor, "msg")) @@ -96,7 +96,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit case object Tick val countDownLatch = new CountDownLatch(3) val tickActor = system.actorOf(Props(new Actor { - def receive = { case Tick ⇒ countDownLatch.countDown() } + def receive = { case Tick => countDownLatch.countDown() } })) // run after 300 millisec @@ -117,7 +117,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit * ticket #372 */ "be cancellable" taggedAs TimingTest in { - for (_ ← 1 to 10) system.scheduler.scheduleOnce(1 second, testActor, "fail").cancel() + for (_ <- 1 to 10) system.scheduler.scheduleOnce(1 second, testActor, "fail").cancel() expectNoMsg(2 seconds) } @@ -184,8 +184,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit val supervisor = system.actorOf(Props(new Supervisor(AllForOneStrategy(3, 1 second)(List(classOf[Exception]))))) val props = Props(new Actor { def receive = { - case Ping ⇒ pingLatch.countDown() - case Crash ⇒ throw new Exception("CRASH") + case Ping => pingLatch.countDown() + case Crash => throw new Exception("CRASH") } override def postRestart(reason: Throwable) = restartLatch.open @@ -210,7 +210,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit val actor = system.actorOf(Props(new Actor { def receive = { - case Msg(ts) ⇒ + case Msg(ts) => val now = System.nanoTime // Make sure that no message has been dispatched before the scheduled time (10ms) has occurred if (now < ts) throw new RuntimeException("Interval is too small: " + (now - ts)) @@ -218,7 +218,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit } })) - (1 to 300).foreach { i ⇒ + (1 to 300).foreach { i => collectCancellable(system.scheduler.scheduleOnce(20 milliseconds, actor, Msg(System.nanoTime))) Thread.sleep(5) } @@ -232,7 +232,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit case object Msg val actor = system.actorOf(Props(new Actor { - def receive = { case Msg ⇒ ticks.countDown() } + def receive = { case Msg => ticks.countDown() } })) val startTime = System.nanoTime() @@ -283,7 +283,7 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit "survive being stressed without cancellation" taggedAs TimingTest in { val r = ThreadLocalRandom.current() val N = 100000 - for (_ ← 1 to N) { + for (_ <- 1 to N) { val next = r.nextInt(3000) val now = System.nanoTime system.scheduler.scheduleOnce(next.millis) { @@ -292,12 +292,12 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit } } val latencies = within(10.seconds) { - for (i ← 1 to N) yield try expectMsgType[Long] catch { - case NonFatal(e) ⇒ throw new Exception(s"failed expecting the $i-th latency", e) + for (i <- 1 to N) yield try expectMsgType[Long] catch { + case NonFatal(e) => throw new Exception(s"failed expecting the $i-th latency", e) } } val histogram = latencies groupBy (_ / 100000000L) - for (k ← histogram.keys.toSeq.sorted) { + for (k <- histogram.keys.toSeq.sorted) { system.log.info(f"${k * 100}%3d: ${histogram(k).size}") } } @@ -345,7 +345,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev import system.dispatcher val r = ThreadLocalRandom.current val N = 1000000 - val tasks = for (_ ← 1 to N) yield { + val tasks = for (_ <- 1 to N) yield { val next = r.nextInt(3000) val now = System.nanoTime system.scheduler.scheduleOnce(next.millis) { @@ -355,26 +355,26 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev } // get somewhat into the middle of things Thread.sleep(500) - val cancellations = for (t ← tasks) yield { + val cancellations = for (t <- tasks) yield { t.cancel() if (t.isCancelled) 1 else 0 } val cancelled = cancellations.sum println(cancelled) val latencies = within(10.seconds) { - for (i ← 1 to (N - cancelled)) yield try expectMsgType[Long] catch { - case NonFatal(e) ⇒ throw new Exception(s"failed expecting the $i-th latency", e) + for (i <- 1 to (N - cancelled)) yield try expectMsgType[Long] catch { + case NonFatal(e) => throw new Exception(s"failed expecting the $i-th latency", e) } } val histogram = latencies groupBy (_ / 100000000L) - for (k ← histogram.keys.toSeq.sorted) { + for (k <- histogram.keys.toSeq.sorted) { system.log.info(f"${k * 100}%3d: ${histogram(k).size}") } expectNoMsg(1.second) } "survive vicious enqueueing" taggedAs TimingTest in { - withScheduler(config = ConfigFactory.parseString("akka.scheduler.ticks-per-wheel=2")) { (sched, driver) ⇒ + withScheduler(config = ConfigFactory.parseString("akka.scheduler.ticks-per-wheel=2")) { (sched, driver) => import driver._ import system.dispatcher val counter = new AtomicInteger @@ -389,7 +389,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev } def delay = if (ThreadLocalRandom.current.nextBoolean) step * 2 else step val N = 1000000 - (1 to N) foreach (_ ⇒ sched.scheduleOnce(delay)(counter.incrementAndGet())) + (1 to N) foreach (_ => sched.scheduleOnce(delay)(counter.incrementAndGet())) sched.close() Await.result(terminated, 3.seconds.dilated) should be > 10 awaitCond(counter.get == N) @@ -397,22 +397,22 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev } "execute multiple jobs at once when expiring multiple buckets" taggedAs TimingTest in { - withScheduler() { (sched, driver) ⇒ + withScheduler() { (sched, driver) => implicit def ec = localEC import driver._ val start = step / 2 - (0 to 3) foreach (i ⇒ sched.scheduleOnce(start + step * i, testActor, "hello")) + (0 to 3) foreach (i => sched.scheduleOnce(start + step * i, testActor, "hello")) expectNoMsg(step) wakeUp(step) expectWait(step) wakeUp(step * 4 + step / 2) expectWait(step / 2) - (0 to 3) foreach (_ ⇒ expectMsg(Duration.Zero, "hello")) + (0 to 3) foreach (_ => expectMsg(Duration.Zero, "hello")) } } "properly defer jobs even when the timer thread oversleeps" taggedAs TimingTest in { - withScheduler() { (sched, driver) ⇒ + withScheduler() { (sched, driver) => implicit def ec = localEC import driver._ sched.scheduleOnce(step * 3, probe.ref, "hello") @@ -427,11 +427,11 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev } "correctly wrap around wheel rounds" taggedAs TimingTest in { - withScheduler(config = ConfigFactory.parseString("akka.scheduler.ticks-per-wheel=2")) { (sched, driver) ⇒ + withScheduler(config = ConfigFactory.parseString("akka.scheduler.ticks-per-wheel=2")) { (sched, driver) => implicit def ec = localEC import driver._ val start = step / 2 - (0 to 3) foreach (i ⇒ sched.scheduleOnce(start + step * i, probe.ref, "hello")) + (0 to 3) foreach (i => sched.scheduleOnce(start + step * i, probe.ref, "hello")) probe.expectNoMsg(step) wakeUp(step) expectWait(step) @@ -454,11 +454,11 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev } "correctly execute jobs when clock wraps around" taggedAs TimingTest in { - withScheduler(Long.MaxValue - 200000000L) { (sched, driver) ⇒ + withScheduler(Long.MaxValue - 200000000L) { (sched, driver) => implicit def ec = localEC import driver._ val start = step / 2 - (0 to 3) foreach (i ⇒ sched.scheduleOnce(start + step * i, testActor, "hello")) + (0 to 3) foreach (i => sched.scheduleOnce(start + step * i, testActor, "hello")) expectNoMsg(step) wakeUp(step) expectWait(step) @@ -484,7 +484,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev val numEvents = 40 val targetTicks = Int.MaxValue - numEvents + 20 - withScheduler(_startTick = Int.MaxValue - 100) { (sched, driver) ⇒ + withScheduler(_startTick = Int.MaxValue - 100) { (sched, driver) => implicit def ec = localEC import driver._ @@ -494,12 +494,12 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev probe.expectMsgType[Long] val nums = 0 until numEvents - nums foreach (i ⇒ sched.scheduleOnce(start + step * i, testActor, "hello-" + i)) + nums foreach (i => sched.scheduleOnce(start + step * i, testActor, "hello-" + i)) expectNoMsg(step) wakeUp(step) expectWait(step) - nums foreach { i ⇒ + nums foreach { i => wakeUp(step) expectMsg("hello-" + i) expectWait(step) @@ -508,7 +508,7 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev } "reliably reject jobs when shutting down" taggedAs TimingTest in { - withScheduler() { (sched, driver) ⇒ + withScheduler() { (sched, driver) => import system.dispatcher val counter = new AtomicInteger Future { Thread.sleep(5); driver.close(); sched.close() } @@ -542,8 +542,8 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev def reportFailure(t: Throwable): Unit = { t.printStackTrace() } } - def withScheduler(start: Long = 0L, _startTick: Int = 0, config: Config = ConfigFactory.empty)(thunk: (Scheduler with Closeable, Driver) ⇒ Unit): Unit = { - import akka.actor.{ LightArrayRevolverScheduler ⇒ LARS } + def withScheduler(start: Long = 0L, _startTick: Int = 0, config: Config = ConfigFactory.empty)(thunk: (Scheduler with Closeable, Driver) => Unit): Unit = { + import akka.actor.{ LightArrayRevolverScheduler => LARS } val lbq = new AtomicReference[LinkedBlockingQueue[Long]](new LinkedBlockingQueue[Long]) val prb = TestProbe() val tf = system.asInstanceOf[ActorSystemImpl].threadFactory @@ -560,11 +560,11 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev // println(s"waiting $ns") prb.ref ! ns try time += (lbq.get match { - case q: LinkedBlockingQueue[Long] ⇒ q.take() - case _ ⇒ 0L + case q: LinkedBlockingQueue[Long] => q.take() + case _ => 0L }) catch { - case _: InterruptedException ⇒ Thread.currentThread.interrupt() + case _: InterruptedException => Thread.currentThread.interrupt() } } @@ -572,25 +572,25 @@ class LightArrayRevolverSchedulerSpec extends AkkaSpec(SchedulerSpec.testConfRev } val driver = new Driver { def wakeUp(d: FiniteDuration) = lbq.get match { - case q: LinkedBlockingQueue[Long] ⇒ q.offer(d.toNanos) - case _ ⇒ + case q: LinkedBlockingQueue[Long] => q.offer(d.toNanos) + case _ => } def expectWait(): FiniteDuration = probe.expectMsgType[Long].nanos def probe = prb def step = sched.TickDuration def close() = lbq.getAndSet(null) match { - case q: LinkedBlockingQueue[Long] ⇒ q.offer(0L) - case _ ⇒ + case q: LinkedBlockingQueue[Long] => q.offer(0L) + case _ => } } driver.expectWait() try thunk(sched, driver) catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => try { driver.close() sched.close() - } catch { case _: Exception ⇒ } + } catch { case _: Exception => } throw ex } driver.close() diff --git a/akka-actor-tests/src/test/scala/akka/actor/Supervisor.scala b/akka-actor-tests/src/test/scala/akka/actor/Supervisor.scala index f47176021a..1c02b68885 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/Supervisor.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/Supervisor.scala @@ -11,7 +11,7 @@ package akka.actor class Supervisor(override val supervisorStrategy: SupervisorStrategy) extends Actor { def receive = { - case x: Props ⇒ sender() ! context.actorOf(x) + case x: Props => sender() ! context.actorOf(x) } // need to override the default of stopping all children upon restart, tests rely on keeping them around override def preRestart(cause: Throwable, msg: Option[Any]): Unit = {} diff --git a/akka-actor-tests/src/test/scala/akka/actor/SupervisorHierarchySpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SupervisorHierarchySpec.scala index d68a21556f..e1234c8522 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/SupervisorHierarchySpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/SupervisorHierarchySpec.scala @@ -27,7 +27,7 @@ import akka.util.Helpers.ConfigOps import akka.testkit.LongRunningTest object SupervisorHierarchySpec { - import FSM.`→` + import FSM.`->` class FireWorkerException(msg: String) extends Exception(msg) @@ -38,7 +38,7 @@ object SupervisorHierarchySpec { class CountDownActor(countDown: CountDownLatch, override val supervisorStrategy: SupervisorStrategy) extends Actor { def receive = { - case p: Props ⇒ sender() ! context.actorOf(p) + case p: Props => sender() ! context.actorOf(p) } // test relies on keeping children around during restart override def preRestart(cause: Throwable, msg: Option[Any]): Unit = {} @@ -48,11 +48,11 @@ object SupervisorHierarchySpec { } class Resumer extends Actor { - override def supervisorStrategy = OneForOneStrategy() { case _ ⇒ SupervisorStrategy.Resume } + override def supervisorStrategy = OneForOneStrategy() { case _ => SupervisorStrategy.Resume } def receive = { - case "spawn" ⇒ sender() ! context.actorOf(Props[Resumer]) - case "fail" ⇒ throw new Exception("expected") - case "ping" ⇒ sender() ! "pong" + case "spawn" => sender() ! context.actorOf(Props[Resumer]) + case "fail" => throw new Exception("expected") + case "ping" => sender() ! "pong" } } @@ -92,8 +92,8 @@ object SupervisorHierarchySpec { override def suspend(cell: ActorCell): Unit = { cell.actor match { - case h: Hierarchy ⇒ h.log :+= Event("suspended " + cell.mailbox.suspendCount, identityHashCode(cell.actor)) - case _ ⇒ + case h: Hierarchy => h.log :+= Event("suspended " + cell.mailbox.suspendCount, identityHashCode(cell.actor)) + case _ => } super.suspend(cell) } @@ -101,8 +101,8 @@ object SupervisorHierarchySpec { override def resume(cell: ActorCell): Unit = { super.resume(cell) cell.actor match { - case h: Hierarchy ⇒ h.log :+= Event("resumed " + cell.mailbox.suspendCount, identityHashCode(cell.actor)) - case _ ⇒ + case h: Hierarchy => h.log :+= Event("resumed " + cell.mailbox.suspendCount, identityHashCode(cell.actor)) + case _ => } } @@ -125,11 +125,11 @@ object SupervisorHierarchySpec { var log = Vector.empty[Event] stateCache.get(self.path) match { - case hs @ HierarchyState(l: Vector[Event], _, f: Failure) if f.failConstr > 0 && !ignoreFailConstr ⇒ + case hs @ HierarchyState(l: Vector[Event], _, f: Failure) if f.failConstr > 0 && !ignoreFailConstr => val log = l :+ Event("Failed in constructor", identityHashCode(this)) stateCache.put(self.path, hs.copy(log = log, failConstr = f.copy(failConstr = f.failConstr - 1))) throw f - case _ ⇒ + case _ => } var failed = false @@ -143,9 +143,9 @@ object SupervisorHierarchySpec { } def setFlags(directive: Directive): Unit = directive match { - case Restart ⇒ failed = true - case Resume ⇒ suspended = true - case _ ⇒ + case Restart => failed = true + case Resume => suspended = true + case _ => } def suspendCount = context.asInstanceOf[ActorCell].mailbox.suspendCount @@ -160,7 +160,7 @@ object SupervisorHierarchySpec { val sizes = s / kids var rest = s % kids val propsTemplate = Props.empty.withDispatcher("hierarchy") - (1 to kids).iterator.map { (id) ⇒ + (1 to kids).iterator.map { (id) => val kidSize = if (rest > 0) { rest -= 1; sizes + 1 } else sizes val props = Props(new Hierarchy(kidSize, breadth, listener, myLevel + 1, random)).withDeploy(propsTemplate.deploy) (context.watch(context.actorOf(props, id.toString)).path, kidSize) @@ -177,8 +177,8 @@ object SupervisorHierarchySpec { log :+= Event("preRestart " + cause, identityHashCode(this)) preRestartCalled = true cause match { - case f: Failure ⇒ - context.children.take(f.stopKids) foreach { child ⇒ + case f: Failure => + context.children.take(f.stopKids) foreach { child => log :+= Event("killing " + child, identityHashCode(this)) context.unwatch(child) context.stop(child) @@ -188,33 +188,33 @@ object SupervisorHierarchySpec { f.failPre -= 1 throw f } - case _ ⇒ stateCache.put(self.path, stateCache.get(self.path).copy(log = log)) + case _ => stateCache.put(self.path, stateCache.get(self.path).copy(log = log)) } } } val unwrap: PartialFunction[Throwable, (Throwable, Throwable)] = { - case x @ PostRestartException(_, f: Failure, _) ⇒ (f, x) - case x @ ActorInitializationException(_, _, f: Failure) ⇒ (f, x) - case x ⇒ (x, x) + case x @ PostRestartException(_, f: Failure, _) => (f, x) + case x @ ActorInitializationException(_, _, f: Failure) => (f, x) + case x => (x, x) } override val supervisorStrategy = OneForOneStrategy()(unwrap andThen { - case (_: Failure, _) if pongsToGo > 0 ⇒ + case (_: Failure, _) if pongsToGo > 0 => log :+= Event("pongOfDeath resuming " + sender(), identityHashCode(this)) Resume - case (f: Failure, orig) ⇒ + case (f: Failure, orig) => if (f.depth > 0) { setFlags(f.directive) log :+= Event("escalating " + f + " from " + sender(), identityHashCode(this)) throw f.copy(depth = f.depth - 1) } val prefix = orig match { - case f: Failure ⇒ "applying " - case _ ⇒ "re-applying " + case f: Failure => "applying " + case _ => "re-applying " } log :+= Event(prefix + f + " to " + sender(), identityHashCode(this)) if (myLevel > 3 && f.failPost == 0 && f.stop) Stop else f.directive - case (_, x) ⇒ + case (_, x) => log :+= Event("unhandled exception from " + sender() + Logging.stackTraceFor(x), identityHashCode(this)) sender() ! Dump(0) context.system.scheduler.scheduleOnce(1 second, self, Dump(0))(context.dispatcher) @@ -226,7 +226,7 @@ object SupervisorHierarchySpec { log = state.log log :+= Event("restarted " + suspendCount + " " + cause, identityHashCode(this)) state.kids foreach { - case (childPath, kidSize) ⇒ + case (childPath, kidSize) => val name = childPath.name if (context.child(name).isEmpty) { listener ! Died(childPath) @@ -238,9 +238,9 @@ object SupervisorHierarchySpec { abort("invariant violated: " + state.kids.size + " != " + context.children.size) } cause match { - case f: Failure if f.failPost > 0 ⇒ { f.failPost -= 1; throw f } - case PostRestartException(`self`, f: Failure, _) if f.failPost > 0 ⇒ { f.failPost -= 1; throw f } - case _ ⇒ + case f: Failure if f.failPost > 0 => { f.failPost -= 1; throw f } + case PostRestartException(`self`, f: Failure, _) if f.failPost > 0 => { f.failPost -= 1; throw f } + case _ => } } @@ -275,14 +275,14 @@ object SupervisorHierarchySpec { def receive = new Receive { val handler: Receive = { - case f: Failure ⇒ + case f: Failure => setFlags(f.directive) stateCache.put(self.path, stateCache.get(self.path).copy(failConstr = f.copy())) throw f - case "ping" ⇒ { Thread.sleep((random.nextFloat * 1.03).toLong); sender() ! "pong" } - case Dump(0) ⇒ abort("dump") - case Dump(level) ⇒ context.children foreach (_ ! Dump(level - 1)) - case Terminated(ref) ⇒ + case "ping" => { Thread.sleep((random.nextFloat * 1.03).toLong); sender() ! "pong" } + case Dump(0) => abort("dump") + case Dump(level) => context.children foreach (_ ! Dump(level - 1)) + case Terminated(ref) => /* * It might be that we acted upon this death already in postRestart * (if the unwatch() came too late), so just ignore in this case. @@ -301,8 +301,8 @@ object SupervisorHierarchySpec { // an indication of duplicate Terminate messages log :+= Event(sender() + " terminated while pongOfDeath", identityHashCode(Hierarchy.this)) } - case Abort ⇒ abort("terminating") - case PingOfDeath ⇒ + case Abort => abort("terminating") + case PingOfDeath => if (size > 1) { pongsToGo = context.children.size log :+= Event("sending " + pongsToGo + " pingOfDeath", identityHashCode(Hierarchy.this)) @@ -311,7 +311,7 @@ object SupervisorHierarchySpec { context stop self context.parent ! PongOfDeath } - case PongOfDeath ⇒ + case PongOfDeath => pongsToGo -= 1 if (pongsToGo == 0) { context stop self @@ -406,10 +406,10 @@ object SupervisorHierarchySpec { // don’t escalate from this one! override val supervisorStrategy = OneForOneStrategy() { - case f: Failure ⇒ f.directive - case OriginalRestartException(f: Failure) ⇒ f.directive - case ActorInitializationException(_, _, f: Failure) ⇒ f.directive - case _ ⇒ Stop + case f: Failure => f.directive + case OriginalRestartException(f: Failure) => f.directive + case ActorInitializationException(_, _, f: Failure) => f.directive + case _ => Stop } var children = Vector.empty[ActorRef] @@ -418,14 +418,14 @@ object SupervisorHierarchySpec { var pingChildren = Set.empty[ActorRef] val nextJob = Iterator.continually(random.nextFloat match { - case x if x >= 0.5 ⇒ + case x if x >= 0.5 => // ping one child val pick = ((x - 0.5) * 2 * idleChildren.size).toInt val ref = idleChildren(pick) idleChildren = idleChildren.take(pick) ++ idleChildren.drop(pick + 1) pingChildren += ref Ping(ref) - case x ⇒ + case x => // fail one child val pick = ((if (x >= 0.25) x - 0.25 else x) * 4 * activeChildren.size).toInt Fail(activeChildren(pick), if (x > 0.25) Restart else Resume) @@ -449,14 +449,14 @@ object SupervisorHierarchySpec { startWith(Idle, size * 1000) when(Idle) { - case Event(Init, _) ⇒ + case Event(Init, _) => hierarchy = context.watch(context.actorOf(Props(new Hierarchy(size, breadth, self, 0, random)).withDispatcher("hierarchy"), "head")) setTimer("phase", StateTimeout, 5 seconds, false) goto(Init) } when(Init) { - case Event(Ready(ref), _) ⇒ + case Event(Ready(ref), _) => if (children contains ref) { testActor ! "children not unique" stop() @@ -465,13 +465,13 @@ object SupervisorHierarchySpec { if (children.size == size) goto(Stress) else stay } - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => testActor ! "did not get children list" stop() } onTransition { - case Init → Stress ⇒ + case Init -> Stress => self ! Work idleChildren = children activeChildren = children @@ -482,14 +482,14 @@ object SupervisorHierarchySpec { val workSchedule = 50.millis private def random012: Int = random.nextFloat match { - case x if x > 0.1 ⇒ 0 - case x if x > 0.03 ⇒ 1 - case _ ⇒ 2 + case x if x > 0.1 => 0 + case x if x > 0.03 => 1 + case _ => 2 } private def bury(path: ActorPath): Unit = { val deadGuy = path.elements val deadGuySize = deadGuy.size - val isChild = (other: ActorRef) ⇒ other.path.elements.take(deadGuySize) == deadGuy + val isChild = (other: ActorRef) => other.path.elements.take(deadGuySize) == deadGuy activeChildren = activeChildren filterNot isChild idleChildren = idleChildren filterNot isChild pingChildren = pingChildren filterNot isChild @@ -498,33 +498,33 @@ object SupervisorHierarchySpec { var ignoreNotResumedLogs = true when(Stress) { - case Event(Work, _) if idleChildren.isEmpty ⇒ + case Event(Work, _) if idleChildren.isEmpty => context.system.scheduler.scheduleOnce(workSchedule, self, Work)(context.dispatcher) stay - case Event(Work, x) if x > 0 ⇒ + case Event(Work, x) if x > 0 => nextJob.next match { - case Ping(ref) ⇒ ref ! "ping" - case Fail(ref, dir) ⇒ + case Ping(ref) => ref ! "ping" + case Fail(ref, dir) => val f = Failure(dir, stop = random012 > 0, depth = random012, failPre = random012, failPost = random012, failConstr = random012, stopKids = random012 match { - case 0 ⇒ 0 - case 1 ⇒ random.nextInt(breadth / 2) - case 2 ⇒ 1000 + case 0 => 0 + case 1 => random.nextInt(breadth / 2) + case 2 => 1000 }) ref ! f } if (idleChildren.nonEmpty) self ! Work else context.system.scheduler.scheduleOnce(workSchedule, self, Work)(context.dispatcher) stay using (x - 1) - case Event(Work, _) ⇒ if (pingChildren.isEmpty) goto(LastPing) else goto(Finishing) - case Event(Died(path), _) ⇒ + case Event(Work, _) => if (pingChildren.isEmpty) goto(LastPing) else goto(Finishing) + case Event(Died(path), _) => bury(path) stay - case Event("pong", _) ⇒ + case Event("pong", _) => pingChildren -= sender() idleChildren :+= sender() stay - case Event(StateTimeout, todo) ⇒ + case Event(StateTimeout, todo) => log.info("dumping state due to StateTimeout") log.info("children: " + children.size + " pinged: " + pingChildren.size + " idle: " + idleChildren.size + " work: " + todo) pingChildren foreach println @@ -536,45 +536,45 @@ object SupervisorHierarchySpec { } onTransition { - case Stress → Finishing ⇒ ignoreFailConstr = true + case Stress -> Finishing => ignoreFailConstr = true } when(Finishing) { - case Event("pong", _) ⇒ + case Event("pong", _) => pingChildren -= sender() idleChildren :+= sender() if (pingChildren.isEmpty) goto(LastPing) else stay - case Event(Died(ref), _) ⇒ + case Event(Died(ref), _) => bury(ref) if (pingChildren.isEmpty) goto(LastPing) else stay } onTransition { - case _ → LastPing ⇒ + case _ -> LastPing => idleChildren foreach (_ ! "ping") pingChildren ++= idleChildren idleChildren = Vector.empty } when(LastPing) { - case Event("pong", _) ⇒ + case Event("pong", _) => pingChildren -= sender() idleChildren :+= sender() if (pingChildren.isEmpty) goto(Stopping) else stay - case Event(Died(ref), _) ⇒ + case Event(Died(ref), _) => bury(ref) if (pingChildren.isEmpty) goto(Stopping) else stay } onTransition { - case _ → Stopping ⇒ + case _ -> Stopping => ignoreNotResumedLogs = false hierarchy ! PingOfDeath } when(Stopping, stateTimeout = 5.seconds.dilated) { - case Event(PongOfDeath, _) ⇒ stay - case Event(Terminated(r), _) if r == hierarchy ⇒ + case Event(PongOfDeath, _) => stay + case Event(Terminated(r), _) if r == hierarchy => val undead = children filterNot (_.isTerminated) if (undead.nonEmpty) { log.info("undead:\n" + undead.mkString("\n")) @@ -599,21 +599,21 @@ object SupervisorHierarchySpec { testActor ! "stressTestSuccessful" stop } - case Event(StateTimeout, _) ⇒ - errors :+= self → ErrorLog("timeout while Stopping", Vector.empty) + case Event(StateTimeout, _) => + errors :+= self -> ErrorLog("timeout while Stopping", Vector.empty) println(system.asInstanceOf[ActorSystemImpl].printTree) getErrors(hierarchy, 10) printErrors() idleChildren foreach println testActor ! "timeout in Stopping" stop - case Event(e: ErrorLog, _) ⇒ - errors :+= sender() → e + case Event(e: ErrorLog, _) => + errors :+= sender() -> e goto(Failed) } when(GC, stateTimeout = 10 seconds) { - case Event(GCcheck(weak), _) ⇒ + case Event(GCcheck(weak), _) => val next = weak filter (_.get ne null) if (next.nonEmpty) { println(next.size + " left") @@ -624,7 +624,7 @@ object SupervisorHierarchySpec { testActor ! "stressTestSuccessful" stop } - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => testActor ! "timeout in GC" stop } @@ -632,30 +632,30 @@ object SupervisorHierarchySpec { var errors = Vector.empty[(ActorRef, ErrorLog)] when(Failed, stateTimeout = 5.seconds.dilated) { - case Event(e: ErrorLog, _) ⇒ + case Event(e: ErrorLog, _) => if (!e.msg.startsWith("not resumed") || !ignoreNotResumedLogs) - errors :+= sender() → e + errors :+= sender() -> e stay - case Event(Terminated(r), _) if r == hierarchy ⇒ + case Event(Terminated(r), _) if r == hierarchy => printErrors() testActor ! "stressTestFailed" stop - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => getErrors(hierarchy, 10) printErrors() testActor ! "timeout in Failed" stop - case Event("pong", _) ⇒ stay // don’t care? - case Event(Work, _) ⇒ stay - case Event(Died(_), _) ⇒ stay + case Event("pong", _) => stay // don’t care? + case Event(Work, _) => stay + case Event(Died(_), _) => stay } def getErrors(target: ActorRef, depth: Int): Unit = { target match { - case l: LocalActorRef ⇒ + case l: LocalActorRef => l.underlying.actor match { - case h: Hierarchy ⇒ errors :+= target → ErrorLog("forced", h.log) - case _ ⇒ errors :+= target → ErrorLog("fetched", stateCache.get(target.path).log) + case h: Hierarchy => errors :+= target -> ErrorLog("forced", h.log) + case _ => errors :+= target -> ErrorLog("fetched", stateCache.get(target.path).log) } if (depth > 0) { l.underlying.children foreach (getErrors(_, depth - 1)) @@ -665,10 +665,10 @@ object SupervisorHierarchySpec { def getErrorsUp(target: ActorRef): Unit = { target match { - case l: LocalActorRef ⇒ + case l: LocalActorRef => l.underlying.actor match { - case h: Hierarchy ⇒ errors :+= target → ErrorLog("forced", h.log) - case _ ⇒ errors :+= target → ErrorLog("fetched", stateCache.get(target.path).log) + case h: Hierarchy => errors :+= target -> ErrorLog("forced", h.log) + case _ => errors :+= target -> ErrorLog("fetched", stateCache.get(target.path).log) } if (target != hierarchy) getErrorsUp(l.getParent) } @@ -676,32 +676,32 @@ object SupervisorHierarchySpec { def printErrors(): Unit = { errors collect { - case (origin, ErrorLog("dump", _)) ⇒ getErrors(origin, 1) - case (origin, ErrorLog(msg, _)) if msg startsWith "not resumed" ⇒ getErrorsUp(origin) + case (origin, ErrorLog("dump", _)) => getErrors(origin, 1) + case (origin, ErrorLog(msg, _)) if msg startsWith "not resumed" => getErrorsUp(origin) } val merged = errors.sortBy(_._1.toString) flatMap { - case (ref, ErrorLog(msg, log)) ⇒ + case (ref, ErrorLog(msg, log)) => println("Error: " + ref + " " + msg) - log map (l ⇒ (l.time, ref, l.identity, l.msg.toString)) + log map (l => (l.time, ref, l.identity, l.msg.toString)) } println("random seed: " + randomSeed) merged.sorted.distinct foreach println } whenUnhandled { - case Event(Ready(ref), _) ⇒ + case Event(Ready(ref), _) => activeChildren :+= ref children :+= ref idleChildren :+= ref stay - case Event(e: ErrorLog, _) ⇒ + case Event(e: ErrorLog, _) => if (e.msg.startsWith("not resumed")) stay else { - errors :+= sender() → e + errors :+= sender() -> e // don’t stop the hierarchy, that is going to happen all by itself and in the right order goto(Failed) } - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => println("pingChildren:\n" + pingChildren.view.map(_.path.toString).toSeq.sorted.mkString("\n")) ignoreNotResumedLogs = false // make sure that we get the logs of the remaining pingChildren @@ -709,10 +709,10 @@ object SupervisorHierarchySpec { // this will ensure that the error logs get printed and we stop the test context stop hierarchy goto(Failed) - case Event(Abort, _) ⇒ + case Event(Abort, _) => log.info("received Abort") goto(Failed) - case Event(msg, _) ⇒ + case Event(msg, _) => testActor ! ("received unexpected msg: " + msg) stop } @@ -760,8 +760,8 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w val crasher = context.watch(context.actorOf(Props(new CountDownActor(countDownMessages, SupervisorStrategy.defaultStrategy)))) def receive = { - case "killCrasher" ⇒ crasher ! Kill - case Terminated(_) ⇒ countDownMax.countDown() + case "killCrasher" => crasher ! Kill + case Terminated(_) => countDownMax.countDown() } })) @@ -794,9 +794,9 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w "suspend children while failing" taggedAs LongRunningTest in { val latch = TestLatch() val slowResumer = system.actorOf(Props(new Actor { - override def supervisorStrategy = OneForOneStrategy() { case _ ⇒ Await.ready(latch, 4.seconds.dilated); SupervisorStrategy.Resume } + override def supervisorStrategy = OneForOneStrategy() { case _ => Await.ready(latch, 4.seconds.dilated); SupervisorStrategy.Resume } def receive = { - case "spawn" ⇒ sender() ! context.actorOf(Props[Resumer]) + case "spawn" => sender() ! context.actorOf(Props[Resumer]) } }), "slowResumer") slowResumer ! "spawn" @@ -830,7 +830,7 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w EventFilter.error(start = "changing Resume into Create")) { val failResumer = system.actorOf(Props(new Actor { override def supervisorStrategy = OneForOneStrategy() { - case e: ActorInitializationException ⇒ + case e: ActorInitializationException => if (createAttempt.get % 2 == 0) SupervisorStrategy.Resume else SupervisorStrategy.Restart } @@ -838,7 +838,7 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w val ca = createAttempt.incrementAndGet() if (ca <= 6 && ca % 3 == 0) - context.actorOf(Props(new Actor { override def receive = { case _ ⇒ } }), "workingChild") + context.actorOf(Props(new Actor { override def receive = { case _ => } }), "workingChild") if (ca < 6) { throw new IllegalArgumentException("OH NO!") @@ -850,12 +850,12 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w postRestartCalled.incrementAndGet() } override def receive = { - case m ⇒ sender() ! m + case m => sender() ! m } }), "failChild") override def receive = { - case m ⇒ child.forward(m) + case m => child.forward(m) } }), "failResumer") @@ -882,8 +882,8 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w fsm ! FSM.SubscribeTransitionCallBack(system.actorOf(Props(new Actor { def receive = { - case s: FSM.CurrentState[_] ⇒ log.info("{}", s) - case t: FSM.Transition[_] ⇒ log.info("{}", t) + case s: FSM.CurrentState[_] => log.info("{}", s) + case t: FSM.Transition[_] => log.info("{}", t) } }))) diff --git a/akka-actor-tests/src/test/scala/akka/actor/SupervisorMiscSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SupervisorMiscSpec.scala index a06804dd78..6a6adf27f0 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/SupervisorMiscSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/SupervisorMiscSpec.scala @@ -41,8 +41,8 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul val workerProps = Props(new Actor { override def postRestart(cause: Throwable): Unit = { countDownLatch.countDown() } def receive = { - case "status" ⇒ this.sender() ! "OK" - case _ ⇒ this.context.stop(self) + case "status" => this.sender() ! "OK" + case _ => this.context.stop(self) } }) @@ -59,10 +59,10 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul countDownLatch.await(10, TimeUnit.SECONDS) - Seq("actor1" → actor1, "actor2" → actor2, "actor3" → actor3, "actor4" → actor4) map { - case (id, ref) ⇒ (id, ref ? "status") + Seq("actor1" -> actor1, "actor2" -> actor2, "actor3" -> actor3, "actor4" -> actor4) map { + case (id, ref) => (id, ref ? "status") } foreach { - case (id, f) ⇒ (id, Await.result(f, timeout.duration)) should ===((id, "OK")) + case (id, f) => (id, Await.result(f, timeout.duration)) should ===((id, "OK")) } } } @@ -70,7 +70,7 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul "be able to create named children in its constructor" in { val a = system.actorOf(Props(new Actor { context.actorOf(Props.empty, "bob") - def receive = { case x: Exception ⇒ throw x } + def receive = { case x: Exception => throw x } override def preStart(): Unit = testActor ! "preStart" })) val m = "weird message" @@ -86,7 +86,7 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul val parent = system.actorOf(Props(new Actor { val kid = context.watch(context.actorOf(Props.empty, "foo")) def receive = { - case Terminated(`kid`) ⇒ + case Terminated(`kid`) => try { val newKid = context.actorOf(Props.empty, "foo") val result = @@ -97,9 +97,9 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul else "green" testActor ! result } catch { - case NonFatal(e) ⇒ testActor ! e + case NonFatal(e) => testActor ! e } - case "engage" ⇒ context.stop(kid) + case "engage" => context.stop(kid) } })) parent ! "engage" @@ -109,14 +109,14 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul "not be able to recreate child when old child is alive" in { val parent = system.actorOf(Props(new Actor { def receive = { - case "engage" ⇒ + case "engage" => try { val kid = context.actorOf(Props.empty, "foo") context.stop(kid) context.actorOf(Props.empty, "foo") testActor ! "red" } catch { - case e: InvalidActorNameException ⇒ testActor ! "green" + case e: InvalidActorNameException => testActor ! "green" } } })) @@ -133,7 +133,7 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul } } - def receive = { case "engage" ⇒ context.stop(context.actorOf(Props.empty, "Robert")) } + def receive = { case "engage" => context.stop(context.actorOf(Props.empty, "Robert")) } })) parent ! "engage" expectMsg("green") @@ -145,10 +145,10 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul "have access to the failing child’s reference in supervisorStrategy" in { val parent = system.actorOf(Props(new Actor { override val supervisorStrategy = OneForOneStrategy() { - case _: Exception ⇒ testActor ! sender(); SupervisorStrategy.Stop + case _: Exception => testActor ! sender(); SupervisorStrategy.Stop } def receive = { - case "doit" ⇒ context.actorOf(Props.empty, "child") ! Kill + case "doit" => context.actorOf(Props.empty, "child") ! Kill } })) EventFilter[ActorKilledException](occurrences = 1) intercept { diff --git a/akka-actor-tests/src/test/scala/akka/actor/SupervisorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SupervisorSpec.scala index 43815b0365..0200ddf595 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/SupervisorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/SupervisorSpec.scala @@ -39,13 +39,13 @@ object SupervisorSpec { class PingPongActor(sendTo: ActorRef) extends Actor { def receive = { - case Ping ⇒ + case Ping => sendTo ! PingMessage if (sender() != sendTo) sender() ! PongMessage - case Die ⇒ + case Die => throw new RuntimeException(ExceptionMessage) - case DieReply ⇒ + case DieReply => val e = new RuntimeException(ExceptionMessage) sender() ! Status.Failure(e) throw e @@ -64,20 +64,20 @@ object SupervisorSpec { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 0)(List(classOf[Exception])) def receive = { - case Die ⇒ temp forward Die - case Terminated(`temp`) ⇒ sendTo ! "terminated" - case Status.Failure(_) ⇒ /*Ignore*/ + case Die => temp forward Die + case Terminated(`temp`) => sendTo ! "terminated" + case Status.Failure(_) => /*Ignore*/ } } class Creator(target: ActorRef) extends Actor { override val supervisorStrategy = OneForOneStrategy() { - case ex ⇒ + case ex => target ! ((self, sender(), ex)) SupervisorStrategy.Stop } def receive = { - case p: Props ⇒ sender() ! context.actorOf(p) + case p: Props => sender() ! context.actorOf(p) } } @@ -211,15 +211,15 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter override def preStart(): Unit = { preStarts += 1; testActor ! ("preStart" + preStarts) } override def postStop(): Unit = { postStops += 1; testActor ! ("postStop" + postStops) } def receive = { - case "crash" ⇒ { testActor ! "crashed"; throw new RuntimeException("Expected") } - case "ping" ⇒ sender() ! "pong" + case "crash" => { testActor ! "crashed"; throw new RuntimeException("Expected") } + case "ping" => sender() ! "pong" } } val master = system.actorOf(Props(new Actor { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = restarts)(List(classOf[Exception])) val child = context.actorOf(Props(childInstance)) def receive = { - case msg ⇒ child forward msg + case msg => child forward msg } })) @@ -230,7 +230,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter filterEvents(EventFilter[RuntimeException]("Expected", occurrences = restarts + 1)) { (1 to restarts) foreach { - i ⇒ + i => master ! "crash" expectMsg("crashed") @@ -389,8 +389,8 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter } def receive = { - case Ping ⇒ sender() ! PongMessage - case DieReply ⇒ + case Ping => sender() ! PongMessage + case DieReply => val e = new RuntimeException("Expected") sender() ! Status.Failure(e) throw e @@ -419,14 +419,14 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter "not lose system messages when a NonFatal exception occurs when processing a system message" in { val parent = system.actorOf(Props(new Actor { override val supervisorStrategy = OneForOneStrategy()({ - case e: IllegalStateException if e.getMessage == "OHNOES" ⇒ throw e - case _ ⇒ SupervisorStrategy.Restart + case e: IllegalStateException if e.getMessage == "OHNOES" => throw e + case _ => SupervisorStrategy.Restart }) val child = context.watch(context.actorOf(Props(new Actor { override def postRestart(reason: Throwable): Unit = testActor ! "child restarted" def receive = { - case l: TestLatch ⇒ { Await.ready(l, 5 seconds); throw new IllegalStateException("OHNOES") } - case "test" ⇒ sender() ! "child green" + case l: TestLatch => { Await.ready(l, 5 seconds); throw new IllegalStateException("OHNOES") } + case "test" => sender() ! "child green" } }), "child")) @@ -439,11 +439,11 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter } def receive = { - case Terminated(a) if a.path == child.path ⇒ testActor ! "child terminated" - case l: TestLatch ⇒ child ! l - case "test" ⇒ sender() ! "green" - case "testchild" ⇒ child forward "test" - case "testchildAndAck" ⇒ child forward "test"; sender() ! "ack" + case Terminated(a) if a.path == child.path => testActor ! "child terminated" + case l: TestLatch => child ! l + case "test" => sender() ! "green" + case "testchild" => child forward "test" + case "testchildAndAck" => child forward "test"; sender() ! "ack" } })) @@ -478,7 +478,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter val middle = expectMsgType[ActorRef] middle ! creator(testActor, fail = true) expectMsgPF(hint = "ConfigurationException") { - case (top, middle, ex: ConfigurationException) ⇒ + case (top, middle, ex: ConfigurationException) => ex.getCause should ===(failure) } } @@ -495,7 +495,7 @@ class SupervisorSpec extends AkkaSpec(SupervisorSpec.config) with BeforeAndAfter val middle = expectMsgType[ActorRef] middle ! creator(testActor, fail = true).withRouter(RoundRobinPool(1)) expectMsgPF(hint = "ConfigurationException") { - case (top, middle, ex: ConfigurationException) ⇒ + case (top, middle, ex: ConfigurationException) => ex.getCause should ===(failure) } } diff --git a/akka-actor-tests/src/test/scala/akka/actor/SupervisorTreeSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/SupervisorTreeSpec.scala index a3b265823a..b68bd76451 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/SupervisorTreeSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/SupervisorTreeSpec.scala @@ -21,7 +21,7 @@ class SupervisorTreeSpec extends AkkaSpec("akka.actor.serialize-messages = off") val p = Props(new Actor { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 1 second)(List(classOf[Exception])) def receive = { - case p: Props ⇒ sender() ! context.actorOf(p) + case p: Props => sender() ! context.actorOf(p) } override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { testActor ! self.path } }) diff --git a/akka-actor-tests/src/test/scala/akka/actor/Ticket669Spec.scala b/akka-actor-tests/src/test/scala/akka/actor/Ticket669Spec.scala index 2837ffcd58..2ba153eda0 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/Ticket669Spec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/Ticket669Spec.scala @@ -53,7 +53,7 @@ class Ticket669Spec extends AkkaSpec with BeforeAndAfterAll with ImplicitSender object Ticket669Spec { class Supervised extends Actor { def receive = { - case msg ⇒ throw new Exception("test") + case msg => throw new Exception("test") } override def preRestart(reason: scala.Throwable, msg: Option[Any]): Unit = { diff --git a/akka-actor-tests/src/test/scala/akka/actor/TimerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/TimerSpec.scala index b12c398e4e..99665bd261 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/TimerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/TimerSpec.scala @@ -31,10 +31,10 @@ object TimerSpec { class Exc extends RuntimeException("simulated exc") with NoStackTrace - def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () ⇒ Int): Props = + def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () => Int): Props = Props(new Target(monitor, interval, repeat, initial)) - class Target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () ⇒ Int) extends Actor with Timers { + class Target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () => Int) extends Actor with Timers { private var bumpCount = initial() if (repeat) @@ -61,32 +61,32 @@ object TimerSpec { } override def receive = { - case Tick(n) ⇒ + case Tick(n) => monitor ! Tock(n) - case Bump ⇒ + case Bump => bump() - case SlowThenBump(latch) ⇒ + case SlowThenBump(latch) => Await.ready(latch, 10.seconds) bump() - case End ⇒ + case End => context.stop(self) - case Cancel ⇒ + case Cancel => timers.cancel("T") - case Throw(e) ⇒ + case Throw(e) => throw e - case SlowThenThrow(latch, e) ⇒ + case SlowThenThrow(latch, e) => Await.ready(latch, 10.seconds) throw e - case AutoReceive ⇒ autoReceive() + case AutoReceive => autoReceive() } } - def fsmTarget(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () ⇒ Int): Props = + def fsmTarget(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () => Int): Props = Props(new FsmTarget(monitor, interval, repeat, initial)) object TheState - class FsmTarget(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () ⇒ Int) extends FSM[TheState.type, Int] { + class FsmTarget(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () => Int) extends FSM[TheState.type, Int] { private var restarting = false @@ -119,25 +119,25 @@ object TimerSpec { } when(TheState) { - case Event(Tick(n), _) ⇒ + case Event(Tick(n), _) => monitor ! Tock(n) stay - case Event(Bump, bumpCount) ⇒ + case Event(Bump, bumpCount) => bump(bumpCount) - case Event(SlowThenBump(latch), bumpCount) ⇒ + case Event(SlowThenBump(latch), bumpCount) => Await.ready(latch, 10.seconds) bump(bumpCount) - case Event(End, _) ⇒ + case Event(End, _) => stop() - case Event(Cancel, _) ⇒ + case Event(Cancel, _) => cancelTimer("T") stay - case Event(Throw(e), _) ⇒ + case Event(Throw(e), _) => throw e - case Event(SlowThenThrow(latch, e), _) ⇒ + case Event(SlowThenThrow(latch, e), _) => Await.ready(latch, 10.seconds) throw e - case Event(AutoReceive, _) ⇒ + case Event(AutoReceive, _) => autoReceive() } @@ -148,13 +148,13 @@ object TimerSpec { class TimerSpec extends AbstractTimerSpec { override def testName: String = "Timers" - override def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () ⇒ Int = () ⇒ 1): Props = + override def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () => Int = () => 1): Props = TimerSpec.target(monitor, interval, repeat, initial) } class FsmTimerSpec extends AbstractTimerSpec { override def testName: String = "FSM Timers" - override def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () ⇒ Int = () ⇒ 1): Props = + override def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () => Int = () => 1): Props = TimerSpec.fsmTarget(monitor, interval, repeat, initial) } @@ -164,7 +164,7 @@ abstract class AbstractTimerSpec extends AkkaSpec { val interval = 1.second val dilatedInterval = interval.dilated - def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () ⇒ Int = () ⇒ 1): Props + def target(monitor: ActorRef, interval: FiniteDuration, repeat: Boolean, initial: () => Int = () => 1): Props def testName: String @@ -233,7 +233,7 @@ abstract class AbstractTimerSpec extends AkkaSpec { val probe = TestProbe() val startCounter = new AtomicInteger(0) val ref = system.actorOf(target(probe.ref, dilatedInterval, repeat = true, - initial = () ⇒ startCounter.incrementAndGet())) + initial = () => startCounter.incrementAndGet())) probe.expectMsg(Tock(1)) val latch = new TestLatch(1) @@ -300,14 +300,14 @@ class TimersAndStashSpec extends AkkaSpec { timers.startSingleTimer("key", "scheduled", 50.millis) def receive: Receive = stashing def notStashing: Receive = { - case msg ⇒ probe ! msg + case msg => probe ! msg } def stashing: Receive = { - case StopStashing ⇒ + case StopStashing => context.become(notStashing) unstashAll() - case "scheduled" ⇒ + case "scheduled" => probe ! "saw-scheduled" stash() } diff --git a/akka-actor-tests/src/test/scala/akka/actor/TypedActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/TypedActorSpec.scala index 3c0a437ef2..6810ecd290 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/TypedActorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/TypedActorSpec.scala @@ -8,7 +8,7 @@ import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.{ CountDownLatch, TimeUnit, TimeoutException } import akka.actor.TypedActor._ -import akka.japi.{ Option ⇒ JOption } +import akka.japi.{ Option => JOption } import akka.pattern.ask import akka.routing.RoundRobinGroup import akka.serialization.{ JavaSerializer, SerializerWithStringManifest } @@ -48,8 +48,8 @@ object TypedActorSpec { def findNext: T = { val currentItems = current.get val newItems = currentItems match { - case Nil ⇒ items - case xs ⇒ xs + case Nil => items + case xs => xs } if (current.compareAndSet(currentItems, newItems.tail)) newItems.head @@ -59,7 +59,7 @@ object TypedActorSpec { findNext } - override def exists(f: T ⇒ Boolean): Boolean = items exists f + override def exists(f: T => Boolean): Boolean = items exists f } trait Foo { @@ -179,25 +179,25 @@ object TypedActorSpec { class LifeCyclesImpl(val latch: CountDownLatch) extends PreStart with PostStop with PreRestart with PostRestart with LifeCycles with Receiver { - private def ensureContextAvailable[T](f: ⇒ T): T = TypedActor.context match { - case null ⇒ throw new IllegalStateException("TypedActor.context is null!") - case some ⇒ f + private def ensureContextAvailable[T](f: => T): T = TypedActor.context match { + case null => throw new IllegalStateException("TypedActor.context is null!") + case some => f } override def crash(): Unit = throw new IllegalStateException("Crash!") override def preStart(): Unit = ensureContextAvailable(latch.countDown()) - override def postStop(): Unit = ensureContextAvailable(for (i ← 1 to 3) latch.countDown()) + override def postStop(): Unit = ensureContextAvailable(for (i <- 1 to 3) latch.countDown()) - override def preRestart(reason: Throwable, message: Option[Any]): Unit = ensureContextAvailable(for (i ← 1 to 5) latch.countDown()) + override def preRestart(reason: Throwable, message: Option[Any]): Unit = ensureContextAvailable(for (i <- 1 to 5) latch.countDown()) - override def postRestart(reason: Throwable): Unit = ensureContextAvailable(for (i ← 1 to 7) latch.countDown()) + override def postRestart(reason: Throwable): Unit = ensureContextAvailable(for (i <- 1 to 7) latch.countDown()) override def onReceive(msg: Any, sender: ActorRef): Unit = { ensureContextAvailable( msg match { - case "pigdog" ⇒ sender ! "dogpig" + case "pigdog" => sender ! "dogpig" }) } } @@ -219,13 +219,13 @@ object TypedActorSpec { override def manifest(o: AnyRef): String = manifest override def toBinary(o: AnyRef): Array[Byte] = o match { - case _: WithStringSerializedClass ⇒ Array(255.toByte) - case _ ⇒ throw new IllegalArgumentException(s"Cannot serialize object of type [${o.getClass.getName}]") + case _: WithStringSerializedClass => Array(255.toByte) + case _ => throw new IllegalArgumentException(s"Cannot serialize object of type [${o.getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case manifest if bytes.length == 1 && bytes(0) == 255.toByte ⇒ WithStringSerializedClass() - case _ ⇒ throw new IllegalArgumentException(s"Cannot deserialize object with manifest $manifest") + case manifest if bytes.length == 1 && bytes(0) == 255.toByte => WithStringSerializedClass() + case _ => throw new IllegalArgumentException(s"Cannot deserialize object with manifest $manifest") } } @@ -336,8 +336,8 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config) "be able to call multiple Future-returning methods non-blockingly" in within(timeout.duration) { val t = newFooBar - val futures = for (i ← 1 to 20) yield (i, t.futurePigdog(20 millis, i)) - for ((i, f) ← futures) { + val futures = for (i <- 1 to 20) yield (i, t.futurePigdog(20 millis, i)) + for ((i, f) <- futures) { Await.result(f, remaining) should ===("Pigdog" + i) } mustStop(t) @@ -376,10 +376,10 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config) filterEvents(EventFilter[IllegalStateException]("expected")) { val boss = system.actorOf(Props(new Actor { override val supervisorStrategy = OneForOneStrategy() { - case e: IllegalStateException if e.getMessage == "expected" ⇒ SupervisorStrategy.Resume + case e: IllegalStateException if e.getMessage == "expected" => SupervisorStrategy.Resume } def receive = { - case p: TypedProps[_] ⇒ context.sender() ! TypedActor(context).typedActorOf(p) + case p: TypedProps[_] => context.sender() ! TypedActor(context).typedActorOf(p) } })) val t = Await.result((boss ? TypedProps[Bar](classOf[Foo], classOf[Bar]).withTimeout(2 seconds)).mapTo[Foo], timeout.duration) @@ -442,14 +442,14 @@ class TypedActorSpec extends AkkaSpec(TypedActorSpec.config) } "be able to use balancing dispatcher" in within(timeout.duration) { - val thais = for (i ← 1 to 60) yield newFooBar("pooled-dispatcher", 6 seconds) + val thais = for (i <- 1 to 60) yield newFooBar("pooled-dispatcher", 6 seconds) val iterator = new CyclicIterator(thais) - val results = for (i ← 1 to 120) yield (i, iterator.next.futurePigdog(200 millis, i)) + val results = for (i <- 1 to 120) yield (i, iterator.next.futurePigdog(200 millis, i)) - for ((i, r) ← results) Await.result(r, remaining) should ===("Pigdog" + i) + for ((i, r) <- results) Await.result(r, remaining) should ===("Pigdog" + i) - for (t ← thais) mustStop(t) + for (t <- thais) mustStop(t) } "be able to serialize and deserialize invocations" in { @@ -564,7 +564,7 @@ class TypedActorRouterSpec extends AkkaSpec(TypedActorSpec.config) val t2 = newFooBar val t3 = newFooBar val t4 = newFooBar - val routees = List(t1, t2, t3, t4) map { t ⇒ TypedActor(system).getActorRefFor(t).path.toStringWithoutAddress } + val routees = List(t1, t2, t3, t4) map { t => TypedActor(system).getActorRefFor(t).path.toStringWithoutAddress } TypedActor(system).isTypedActor(t1) should ===(true) TypedActor(system).isTypedActor(t2) should ===(true) diff --git a/akka-actor-tests/src/test/scala/akka/actor/UidClashTest.scala b/akka-actor-tests/src/test/scala/akka/actor/UidClashTest.scala index f8046d032e..cc1d12e4e6 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/UidClashTest.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/UidClashTest.scala @@ -38,8 +38,8 @@ object UidClashTest { class RestartedActor extends Actor { def receive = { - case PleaseRestart ⇒ throw new Exception("restart") - case Terminated(ref) ⇒ throw new TerminatedForNonWatchedActor + case PleaseRestart => throw new Exception("restart") + case Terminated(ref) => throw new TerminatedForNonWatchedActor // This is the tricky part to make this test a positive one (avoid expectNoMsg). // Since anything enqueued in postRestart will arrive before the Terminated // the bug triggers, there needs to be a bounce: @@ -47,12 +47,12 @@ object UidClashTest { // 2. As a response to pint, RestartedSafely is sent to self // 3a. if Terminated was enqueued during the restart procedure it will arrive before the RestartedSafely message // 3b. otherwise only the RestartedSafely message arrives - case PingMyself ⇒ self ! RestartedSafely - case RestartedSafely ⇒ context.parent ! RestartedSafely + case PingMyself => self ! RestartedSafely + case RestartedSafely => context.parent ! RestartedSafely } override def preRestart(reason: Throwable, message: Option[Any]): Unit = { - context.children foreach { child ⇒ + context.children foreach { child => oldActor = child context.unwatch(child) context.stop(child) @@ -69,16 +69,16 @@ object UidClashTest { class RestartingActor(probe: ActorRef) extends Actor { override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) { - case _: TerminatedForNonWatchedActor ⇒ + case _: TerminatedForNonWatchedActor => context.stop(self) Stop - case _ ⇒ Restart + case _ => Restart } val theRestartedOne = context.actorOf(Props[RestartedActor], "theRestartedOne") def receive = { - case PleaseRestart ⇒ theRestartedOne ! PleaseRestart - case RestartedSafely ⇒ probe ! RestartedSafely + case PleaseRestart => theRestartedOne ! PleaseRestart + case RestartedSafely => probe ! RestartedSafely } } diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/ActorModelSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/ActorModelSpec.scala index f9fb67fcc4..2ff7fc120a 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/ActorModelSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/ActorModelSpec.scala @@ -80,21 +80,21 @@ object ActorModelSpec { } def receive = { - case AwaitLatch(latch) ⇒ { ack(); latch.await(); busy.switchOff(()) } - case Meet(sign, wait) ⇒ { ack(); sign.countDown(); wait.await(); busy.switchOff(()) } - case Wait(time) ⇒ { ack(); Thread.sleep(time); busy.switchOff(()) } - case WaitAck(time, l) ⇒ { ack(); Thread.sleep(time); l.countDown(); busy.switchOff(()) } - case Reply(msg) ⇒ { ack(); sender() ! msg; busy.switchOff(()) } - case TryReply(msg) ⇒ { ack(); sender().tell(msg, null); busy.switchOff(()) } - case Forward(to, msg) ⇒ { ack(); to.forward(msg); busy.switchOff(()) } - case CountDown(latch) ⇒ { ack(); latch.countDown(); busy.switchOff(()) } - case Increment(count) ⇒ { ack(); count.incrementAndGet(); busy.switchOff(()) } - case CountDownNStop(l) ⇒ { ack(); l.countDown(); context.stop(self); busy.switchOff(()) } - 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 InterruptNicely(msg) ⇒ { ack(); sender() ! msg; busy.switchOff(()); Thread.currentThread().interrupt() } - case ThrowException(e: Throwable) ⇒ { ack(); busy.switchOff(()); throw e } - case DoubleStop ⇒ { ack(); context.stop(self); context.stop(self); busy.switchOff } + case AwaitLatch(latch) => { ack(); latch.await(); busy.switchOff(()) } + case Meet(sign, wait) => { ack(); sign.countDown(); wait.await(); busy.switchOff(()) } + case Wait(time) => { ack(); Thread.sleep(time); busy.switchOff(()) } + case WaitAck(time, l) => { ack(); Thread.sleep(time); l.countDown(); busy.switchOff(()) } + case Reply(msg) => { ack(); sender() ! msg; busy.switchOff(()) } + case TryReply(msg) => { ack(); sender().tell(msg, null); busy.switchOff(()) } + case Forward(to, msg) => { ack(); to.forward(msg); busy.switchOff(()) } + case CountDown(latch) => { ack(); latch.countDown(); busy.switchOff(()) } + case Increment(count) => { ack(); count.incrementAndGet(); busy.switchOff(()) } + case CountDownNStop(l) => { ack(); l.countDown(); context.stop(self); busy.switchOff(()) } + 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 InterruptNicely(msg) => { ack(); sender() ! msg; busy.switchOff(()); Thread.currentThread().interrupt() } + case ThrowException(e: Throwable) => { ack(); busy.switchOff(()); throw e } + case DoubleStop => { ack(); context.stop(self); context.stop(self); busy.switchOff } } } @@ -117,13 +117,13 @@ object ActorModelSpec { def getStats(actorRef: ActorRef) = { stats.get(actorRef) match { - case null ⇒ + case null => val is = new InterceptorStats stats.putIfAbsent(actorRef, is) match { - case null ⇒ is - case other ⇒ other + case null => is + case other => other } - case existing ⇒ existing + case existing => existing } } @@ -166,7 +166,7 @@ object ActorModelSpec { try { await(deadline)(stops == dispatcher.stops.get) } catch { - case e: Throwable ⇒ + case e: Throwable => system.eventStream.publish(Error(e, dispatcher.toString, dispatcher.getClass, "actual: stops=" + dispatcher.stops.get + " required: stops=" + stops)) throw e @@ -223,7 +223,7 @@ object ActorModelSpec { await(deadline)(stats.msgsProcessed.get() == msgsProcessed) await(deadline)(stats.restarts.get() == restarts) } catch { - case e: Throwable ⇒ + case e: Throwable => system.eventStream.publish(Error( e, Option(dispatcher).toString, @@ -235,14 +235,14 @@ object ActorModelSpec { } } - @tailrec def await(until: Long)(condition: ⇒ Boolean): Unit = + @tailrec def await(until: Long)(condition: => Boolean): Unit = if (System.currentTimeMillis() <= until) { var done = false try { done = condition if (!done) Thread.sleep(25) } catch { - case _: InterruptedException ⇒ + case _: InterruptedException => } if (!done) await(until)(condition) } else throw new AssertionError("await failed") @@ -256,8 +256,8 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa def awaitStarted(ref: ActorRef): Unit = { awaitCond(ref match { - case r: RepointableRef ⇒ r.isStarted - case _ ⇒ true + case r: RepointableRef => r.isStarted + case _ => true }, 1 second, 10 millis) } @@ -282,11 +282,11 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa msgsProcessed = 0, restarts = 0) - for (i ← 1 to 10) yield Future { i } + for (i <- 1 to 10) yield Future { i } assertDispatcher(dispatcher)(stops = 2) val a2 = newTestActor(dispatcher.id) - for (i ← 1 to 10) yield Future { i } + for (i <- 1 to 10) yield Future { i } assertDispatcher(dispatcher)(stops = 2) @@ -319,9 +319,9 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa val counter = new CountDownLatch(200) val a = newTestActor(dispatcher.id) - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { spawn { - for (_ ← 1 to 20) { + for (_ <- 1 to 20) { a ! WaitAck(1, counter) } } @@ -332,11 +332,11 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa system.stop(a) } - def spawn(f: ⇒ Unit): Unit = { + def spawn(f: => Unit): Unit = { (new Thread { override def run(): Unit = try f catch { - case e: Throwable ⇒ system.eventStream.publish(Error(e, "spawn", this.getClass, "error in spawned thread")) + case e: Throwable => system.eventStream.publish(Error(e, "spawn", this.getClass, "error in spawned thread")) } }).start() } @@ -372,8 +372,8 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa val waitTime = (20 seconds).dilated.toMillis val boss = system.actorOf(Props(new Actor { def receive = { - case "run" ⇒ for (_ ← 1 to num) context.watch(context.actorOf(props)) ! cachedMessage - case Terminated(_) ⇒ stopLatch.countDown() + case "run" => for (_ <- 1 to num) context.watch(context.actorOf(props)) ! cachedMessage + case Terminated(_) => stopLatch.countDown() } }).withDispatcher("boss")) try { @@ -389,9 +389,9 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa try { assertCountDown(cachedMessage.latch, waitTime, "Counting down from " + num) } catch { - case e: Throwable ⇒ + case e: Throwable => dispatcher match { - case dispatcher: BalancingDispatcher ⇒ + case dispatcher: BalancingDispatcher => val team = dispatcher.team val mq = dispatcher.messageQueue @@ -400,14 +400,14 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa import scala.collection.JavaConverters._ team.asScala.toList .sortBy(_.self.path) - .foreach { cell: ActorCell ⇒ + .foreach { cell: ActorCell => System.err.println(" - " + cell.self.path + " " + cell.isTerminated + " " + cell.mailbox.currentStatus + " " + cell.mailbox.numberOfMessages + " " + cell.mailbox.systemDrain(SystemMessageList.LNil).size) } System.err.println("Mailbox: " + mq.numberOfMessages + " " + mq.hasMessages) Iterator.continually(mq.dequeue) takeWhile (_ ne null) foreach System.err.println - case _ ⇒ + case _ => } throw e @@ -418,7 +418,7 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa system.stop(boss) } } - for (run ← 1 to 3) { + for (run <- 1 to 3) { flood(10000) assertDispatcher(dispatcher)(stops = run) } @@ -443,9 +443,9 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa val c = system.scheduler.scheduleOnce(2.seconds) { import collection.JavaConverters._ Thread.getAllStackTraces().asScala foreach { - case (thread, stack) ⇒ + case (thread, stack) => println(s"$thread:") - stack foreach (s ⇒ println(s"\t$s")) + stack foreach (s => println(s"\t$s")) } } assert(Await.result(f1, timeout.duration) === "foo") @@ -503,7 +503,7 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa "not double-deregister" in { implicit val dispatcher = interceptedDispatcher() - for (_ ← 1 to 1000) system.actorOf(Props.empty) + for (_ <- 1 to 1000) system.actorOf(Props.empty) val a = newTestActor(dispatcher.id) a ! DoubleStop awaitCond(statsFor(a, dispatcher).registers.get == 1) @@ -523,7 +523,7 @@ object DispatcherModelSpec { } """ + // use unique dispatcher id for each test, since MessageDispatcherInterceptor holds state - (for (n ← 1 to 30) yield """ + (for (n <- 1 to 30) yield """ test-dispatcher-%s { type = "akka.actor.dispatch.DispatcherModelSpec$MessageDispatcherInterceptorConfigurator" }""".format(n)).mkString @@ -596,7 +596,7 @@ object BalancingDispatcherModelSpec { } """ + // use unique dispatcher id for each test, since MessageDispatcherInterceptor holds state - (for (n ← 1 to 30) yield """ + (for (n <- 1 to 30) yield """ test-balancing-dispatcher-%s { type = "akka.actor.dispatch.BalancingDispatcherModelSpec$BalancingMessageDispatcherInterceptorConfigurator" throughput=1 diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/BalancingDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/BalancingDispatcherSpec.scala index 43e5b8308d..28149fbbdb 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/BalancingDispatcherSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/BalancingDispatcherSpec.scala @@ -28,7 +28,7 @@ class BalancingDispatcherSpec extends AkkaSpec(BalancingDispatcherSpec.config) { var invocationCount = 0 def receive = { - case x: Int ⇒ { + case x: Int => { Thread.sleep(delay) invocationCount += 1 finishedCounter.countDown() @@ -37,15 +37,15 @@ class BalancingDispatcherSpec extends AkkaSpec(BalancingDispatcherSpec.config) { } class FirstActor extends Actor { - def receive = { case _ ⇒ {} } + def receive = { case _ => {} } } class SecondActor extends Actor { - def receive = { case _ ⇒ {} } + def receive = { case _ => {} } } class ParentActor extends Actor { - def receive = { case _ ⇒ {} } + def receive = { case _ => {} } } class ChildActor extends ParentActor { @@ -60,7 +60,7 @@ class BalancingDispatcherSpec extends AkkaSpec(BalancingDispatcherSpec.config) { var sentToFast = 0 - for (i ← 1 to 100) { + for (i <- 1 to 100) { // send most work to slow actor if (i % 20 == 0) { fast ! i @@ -70,7 +70,7 @@ class BalancingDispatcherSpec extends AkkaSpec(BalancingDispatcherSpec.config) { } // now send some messages to actors to keep the dispatcher dispatching messages - for (i ← 1 to 10) { + for (i <- 1 to 10) { Thread.sleep(150) if (i % 2 == 0) { fast ! i diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorSpec.scala index 62ac543a94..affe649236 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorSpec.scala @@ -38,8 +38,8 @@ object DispatcherActorSpec { """ class TestActor extends Actor { def receive = { - case "Hello" ⇒ sender() ! "World" - case "Failure" ⇒ throw new RuntimeException("Expected exception; to test fault-tolerance") + case "Hello" => sender() ! "World" + case "Failure" => throw new RuntimeException("Expected exception; to test fault-tolerance") } } @@ -48,7 +48,7 @@ object DispatcherActorSpec { } class OneWayTestActor extends Actor { def receive = { - case "OneWay" ⇒ OneWayTestActor.oneWay.countDown() + case "OneWay" => OneWayTestActor.oneWay.countDown() } } } @@ -80,19 +80,19 @@ class DispatcherActorSpec extends AkkaSpec(DispatcherActorSpec.config) with Defa val latch = new CountDownLatch(100) val start = new CountDownLatch(1) val fastOne = system.actorOf( - Props(new Actor { def receive = { case "sabotage" ⇒ works.set(false) } }) + Props(new Actor { def receive = { case "sabotage" => works.set(false) } }) .withDispatcher(throughputDispatcher)) val slowOne = system.actorOf( Props(new Actor { def receive = { - case "hogexecutor" ⇒ { sender() ! "OK"; start.await } - case "ping" ⇒ if (works.get) latch.countDown() + case "hogexecutor" => { sender() ! "OK"; start.await } + case "ping" => if (works.get) latch.countDown() } }).withDispatcher(throughputDispatcher)) assert(Await.result(slowOne ? "hogexecutor", timeout.duration) === "OK") - (1 to 100) foreach { _ ⇒ slowOne ! "ping" } + (1 to 100) foreach { _ => slowOne ! "ping" } fastOne ! "sabotage" start.countDown() latch.await(10, TimeUnit.SECONDS) @@ -113,15 +113,15 @@ class DispatcherActorSpec extends AkkaSpec(DispatcherActorSpec.config) with Defa val fastOne = system.actorOf( Props(new Actor { def receive = { - case "ping" ⇒ if (works.get) latch.countDown(); context.stop(self) + case "ping" => if (works.get) latch.countDown(); context.stop(self) } }).withDispatcher(throughputDispatcher)) val slowOne = system.actorOf( Props(new Actor { def receive = { - case "hogexecutor" ⇒ { ready.countDown(); start.await } - case "ping" ⇒ { works.set(false); context.stop(self) } + case "hogexecutor" => { ready.countDown(); start.await } + case "ping" => { works.set(false); context.stop(self) } } }).withDispatcher(throughputDispatcher)) diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorsSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorsSpec.scala index 9c8df4dd98..6da237f661 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorsSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatcherActorsSpec.scala @@ -15,7 +15,7 @@ class DispatcherActorsSpec extends AkkaSpec { class SlowActor(finishedCounter: CountDownLatch) extends Actor { def receive = { - case x: Int ⇒ { + case x: Int => { Thread.sleep(50) // slow actor finishedCounter.countDown() } @@ -24,7 +24,7 @@ class DispatcherActorsSpec extends AkkaSpec { class FastActor(finishedCounter: CountDownLatch) extends Actor { def receive = { - case x: Int ⇒ { + case x: Int => { finishedCounter.countDown() } } @@ -38,12 +38,12 @@ class DispatcherActorsSpec extends AkkaSpec { val f = system.actorOf(Props(new FastActor(fFinished))) // send a lot of stuff to s - for (i ← 1 to 50) { + for (i <- 1 to 50) { s ! i } // send some messages to f - for (i ← 1 to 10) { + for (i <- 1 to 10) { f ! i } diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatchersSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatchersSpec.scala index d4d35ae401..abce01dffc 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatchersSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/DispatchersSpec.scala @@ -65,7 +65,7 @@ object DispatchersSpec { class ThreadNameEcho extends Actor { def receive = { - case _ ⇒ sender() ! Thread.currentThread.getName + case _ => sender() ! Thread.currentThread.getName } } @@ -107,19 +107,19 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend val throughput = "throughput" val id = "id" - def instance(dispatcher: MessageDispatcher): (MessageDispatcher) ⇒ Boolean = _ == dispatcher - def ofType[T <: MessageDispatcher: ClassTag]: (MessageDispatcher) ⇒ Boolean = _.getClass == implicitly[ClassTag[T]].runtimeClass + def instance(dispatcher: MessageDispatcher): (MessageDispatcher) => Boolean = _ == dispatcher + def ofType[T <: MessageDispatcher: ClassTag]: (MessageDispatcher) => Boolean = _.getClass == implicitly[ClassTag[T]].runtimeClass - def typesAndValidators: Map[String, (MessageDispatcher) ⇒ Boolean] = Map( - "PinnedDispatcher" → ofType[PinnedDispatcher], - "Dispatcher" → ofType[Dispatcher]) + def typesAndValidators: Map[String, (MessageDispatcher) => Boolean] = Map( + "PinnedDispatcher" -> ofType[PinnedDispatcher], + "Dispatcher" -> ofType[Dispatcher]) def validTypes = typesAndValidators.keys.toList val defaultDispatcherConfig = settings.config.getConfig("akka.actor.default-dispatcher") lazy val allDispatchers: Map[String, MessageDispatcher] = { - validTypes.map(t ⇒ (t, from(ConfigFactory.parseMap(Map(tipe → t, id → t).asJava). + validTypes.map(t => (t, from(ConfigFactory.parseMap(Map(tipe -> t, id -> t).asJava). withFallback(defaultDispatcherConfig)))).toMap } @@ -127,7 +127,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend actor ! "what's the name?" val Expected = R("(DispatchersSpec-myapp.mydispatcher-[1-9][0-9]*)") expectMsgPF() { - case Expected(x) ⇒ + case Expected(x) => } } @@ -157,14 +157,14 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend "throw ConfigurationException if type does not exist" in { intercept[ConfigurationException] { - from(ConfigFactory.parseMap(Map(tipe → "typedoesntexist", id → "invalid-dispatcher").asJava). + from(ConfigFactory.parseMap(Map(tipe -> "typedoesntexist", id -> "invalid-dispatcher").asJava). withFallback(defaultDispatcherConfig)) } } "get the correct types of dispatchers" in { //All created/obtained dispatchers are of the expected type/instance - assert(typesAndValidators.forall(tuple ⇒ tuple._2(allDispatchers(tuple._1)))) + assert(typesAndValidators.forall(tuple => tuple._2(allDispatchers(tuple._1)))) } "provide lookup of dispatchers by id" in { @@ -181,7 +181,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend system.actorOf(Props[ThreadNameEcho].withDispatcher("myapp.thread-pool-dispatcher")) ! "what's the name?" val Expected = R("(DispatchersSpec-myapp.thread-pool-dispatcher-[1-9][0-9]*)") expectMsgPF() { - case Expected(x) ⇒ + case Expected(x) => } } @@ -189,7 +189,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend system.actorOf(Props[ThreadNameEcho]) ! "what's the name?" val Expected = R("(DispatchersSpec-akka.actor.default-dispatcher-[1-9][0-9]*)") expectMsgPF() { - case Expected(x) ⇒ + case Expected(x) => } } @@ -197,7 +197,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend system.actorOf(Props[ThreadNameEcho].withDispatcher("myapp.my-pinned-dispatcher")) ! "what's the name?" val Expected = R("(DispatchersSpec-myapp.my-pinned-dispatcher-[1-9][0-9]*)") expectMsgPF() { - case Expected(x) ⇒ + case Expected(x) => } } @@ -205,7 +205,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend system.actorOf(Props[ThreadNameEcho].withDispatcher("myapp.balancing-dispatcher")) ! "what's the name?" val Expected = R("(DispatchersSpec-myapp.balancing-dispatcher-[1-9][0-9]*)") expectMsgPF() { - case Expected(x) ⇒ + case Expected(x) => } } @@ -225,7 +225,7 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend routee ! "what's the name?" val Expected = R("""(DispatchersSpec-akka\.actor\.deployment\./pool1\.pool-dispatcher-[1-9][0-9]*)""") expectMsgPF() { - case Expected(x) ⇒ + case Expected(x) => } } @@ -233,10 +233,10 @@ class DispatchersSpec extends AkkaSpec(DispatchersSpec.config) with ImplicitSend system.actorOf(FromConfig.props(Props[ThreadNameEcho]), name = "balanced") ! "what's the name?" val Expected = R("""(DispatchersSpec-BalancingPool-/balanced-[1-9][0-9]*)""") expectMsgPF() { - case Expected(x) ⇒ + case Expected(x) => } expectMsgPF() { - case Expected(x) ⇒ + case Expected(x) => } } } diff --git a/akka-actor-tests/src/test/scala/akka/actor/dispatch/PinnedActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dispatch/PinnedActorSpec.scala index e40246bab3..b9bede63ca 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/dispatch/PinnedActorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/dispatch/PinnedActorSpec.scala @@ -23,8 +23,8 @@ object PinnedActorSpec { class TestActor extends Actor { def receive = { - case "Hello" ⇒ sender() ! "World" - case "Failure" ⇒ throw new RuntimeException("Expected exception; to test fault-tolerance") + case "Hello" => sender() ! "World" + case "Failure" => throw new RuntimeException("Expected exception; to test fault-tolerance") } } } @@ -38,7 +38,7 @@ class PinnedActorSpec extends AkkaSpec(PinnedActorSpec.config) with BeforeAndAft "support tell" in { var oneWay = new CountDownLatch(1) - val actor = system.actorOf(Props(new Actor { def receive = { case "OneWay" ⇒ oneWay.countDown() } }).withDispatcher("pinned-dispatcher")) + val actor = system.actorOf(Props(new Actor { def receive = { case "OneWay" => oneWay.countDown() } }).withDispatcher("pinned-dispatcher")) val result = actor ! "OneWay" assert(oneWay.await(1, TimeUnit.SECONDS)) system.stop(actor) diff --git a/akka-actor-tests/src/test/scala/akka/actor/dungeon/DispatchSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/dungeon/DispatchSpec.scala index f3cd7a0661..22a6e42425 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/dungeon/DispatchSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/dungeon/DispatchSpec.scala @@ -13,7 +13,7 @@ object DispatchSpec { class UnserializableMessageClass class EmptyActor extends Actor { override def receive = { - case _: UnserializableMessageClass ⇒ // OK + case _: UnserializableMessageClass => // OK } } } diff --git a/akka-actor-tests/src/test/scala/akka/actor/routing/ListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/routing/ListenerSpec.scala index edb20ce140..862c6de2eb 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/routing/ListenerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/routing/ListenerSpec.scala @@ -21,16 +21,16 @@ class ListenerSpec extends AkkaSpec { val broadcast = system.actorOf(Props(new Actor with Listeners { def receive = listenerManagement orElse { - case "foo" ⇒ gossip("bar") + case "foo" => gossip("bar") } })) def newListener = system.actorOf(Props(new Actor { def receive = { - case "bar" ⇒ + case "bar" => barCount.incrementAndGet barLatch.countDown() - case "foo" ⇒ + case "foo" => fooLatch.countDown() } })) @@ -53,7 +53,7 @@ class ListenerSpec extends AkkaSpec { Await.ready(fooLatch, TestLatch.DefaultTimeout) - for (a ← List(broadcast, a1, a2, a3)) system.stop(a) + for (a <- List(broadcast, a1, a2, a3)) system.stop(a) } } } diff --git a/akka-actor-tests/src/test/scala/akka/dataflow/Future2Actor.scala b/akka-actor-tests/src/test/scala/akka/dataflow/Future2Actor.scala index 3de9f6d4e8..46dedb7e28 100644 --- a/akka-actor-tests/src/test/scala/akka/dataflow/Future2Actor.scala +++ b/akka-actor-tests/src/test/scala/akka/dataflow/Future2Actor.scala @@ -40,8 +40,8 @@ class Future2ActorSpec extends AkkaSpec with DefaultTimeout { "support reply via sender" in { val actor = system.actorOf(Props(new Actor { def receive = { - case "do" ⇒ Future(31) pipeTo context.sender() - case "ex" ⇒ Future(throw new AssertionError) pipeTo context.sender() + case "do" => Future(31) pipeTo context.sender() + case "ex" => Future(throw new AssertionError) pipeTo context.sender() } })) Await.result(actor ? "do", timeout.duration) should ===(31) diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ControlAwareDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ControlAwareDispatcherSpec.scala index 876c5c6a1c..213c981263 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/ControlAwareDispatcherSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/ControlAwareDispatcherSpec.scala @@ -48,7 +48,7 @@ class ControlAwareDispatcherSpec extends AkkaSpec(ControlAwareDispatcherSpec.con self ! ImportantMessage def receive = { - case x ⇒ testActor ! x + case x => testActor ! x } }).withDispatcher(dispatcherKey)) diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutionContextSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutionContextSpec.scala index 0581815f45..809e2d2ab3 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/ExecutionContextSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/ExecutionContextSpec.scala @@ -45,7 +45,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { import system.dispatcher - def batchable[T](f: ⇒ T)(implicit ec: ExecutionContext): Unit = ec.execute(new Batchable { + def batchable[T](f: => T)(implicit ec: ExecutionContext): Unit = ec.execute(new Batchable { override def isBatchable = true override def run: Unit = f }) @@ -54,7 +54,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { batchable { val lock, callingThreadLock, count = new AtomicInteger(0) callingThreadLock.compareAndSet(0, 1) // Enable the lock - (1 to 100) foreach { i ⇒ + (1 to 100) foreach { i => batchable { if (callingThreadLock.get != 0) p.tryFailure(new IllegalStateException("Batch was executed inline!")) else if (count.incrementAndGet == 100) p.trySuccess(()) //Done @@ -72,14 +72,14 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { system.dispatcher.isInstanceOf[BatchingExecutor] should ===(true) import system.dispatcher - def batchable[T](f: ⇒ T)(implicit ec: ExecutionContext): Unit = ec.execute(new Batchable { + def batchable[T](f: => T)(implicit ec: ExecutionContext): Unit = ec.execute(new Batchable { override def isBatchable = true override def run: Unit = f }) val latch = TestLatch(101) batchable { - (1 to 100) foreach { i ⇒ + (1 to 100) foreach { i => batchable { val deadlock = TestLatch(1) batchable { deadlock.open() } @@ -96,12 +96,12 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { system.dispatcher.isInstanceOf[BatchingExecutor] should be(true) import system.dispatcher - val f = Future(()).flatMap { _ ⇒ + val f = Future(()).flatMap { _ => // this needs to be within an OnCompleteRunnable so that things are added to the batch val p = Future.successful(42) // we need the callback list to be non-empty when the blocking{} call is executing - p.onComplete { _ ⇒ () } - val r = p.map { _ ⇒ + p.onComplete { _ => () } + val r = p.map { _ => // trigger the resubmitUnbatched() call blocking { () } // make sure that the other task runs to completion before continuing @@ -109,7 +109,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { // now try again to blockOn() blocking { () } } - p.onComplete { _ ⇒ () } + p.onComplete { _ => () } r } Await.result(f, 3.seconds) should be(()) @@ -119,7 +119,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { system.dispatcher.isInstanceOf[BatchingExecutor] should be(true) import system.dispatcher - val f = Future(()).flatMap { _ ⇒ + val f = Future(()).flatMap { _ => blocking { blocking { blocking { @@ -149,7 +149,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { "work with same-thread dispatcher plus blocking" in { val a = TestActorRef(Props(new Actor { def receive = { - case msg ⇒ + case msg => blocking { sender() ! msg } @@ -157,7 +157,7 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { })) val b = TestActorRef(Props(new Actor { def receive = { - case msg ⇒ a forward msg + case msg => a forward msg } })) val p = TestProbe() @@ -193,9 +193,9 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { "be suspendable and resumable" in { val sec = SerializedSuspendableExecutionContext(1)(ExecutionContext.global) val counter = new AtomicInteger(0) - def perform(f: Int ⇒ Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) } + def perform(f: Int => Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) } perform(_ + 1) - perform(x ⇒ { sec.suspend(); x * 2 }) + perform(x => { sec.suspend(); x * 2 }) awaitCond(counter.get == 2) perform(_ + 4) perform(_ * 2) @@ -220,10 +220,10 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { val throughput = 25 val sec = SerializedSuspendableExecutionContext(throughput)(underlying) sec.suspend() - def perform(f: Int ⇒ Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) } + def perform(f: Int => Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) } val total = 1000 - 1 to total foreach { _ ⇒ perform(_ + 1) } + 1 to total foreach { _ => perform(_ + 1) } sec.size() should ===(total) sec.resume() awaitCond(counter.get == total) @@ -235,9 +235,9 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { val sec = SerializedSuspendableExecutionContext(1)(ExecutionContext.global) val total = 10000 val counter = new AtomicInteger(0) - def perform(f: Int ⇒ Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) } + def perform(f: Int => Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) } - 1 to total foreach { i ⇒ perform(c ⇒ if (c == (i - 1)) c + 1 else c) } + 1 to total foreach { i => perform(c => if (c == (i - 1)) c + 1 else c) } awaitCond(counter.get == total) sec.isEmpty should ===(true) } @@ -252,10 +252,10 @@ class ExecutionContextSpec extends AkkaSpec with DefaultTimeout { val throughput = 25 val sec = SerializedSuspendableExecutionContext(throughput)(underlying) sec.suspend() - def perform(f: Int ⇒ Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) } + def perform(f: Int => Int) = sec execute new Runnable { def run = counter.set(f(counter.get)) } perform(_ + 1) - 1 to 10 foreach { _ ⇒ perform(identity) } - perform(x ⇒ { sec.suspend(); x * 2 }) + 1 to 10 foreach { _ => perform(identity) } + perform(x => { sec.suspend(); x * 2 }) perform(_ + 8) sec.size should ===(13) sec.resume() diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/ForkJoinPoolStarvationSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/ForkJoinPoolStarvationSpec.scala index e09a674055..6f4199bf5b 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/ForkJoinPoolStarvationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/ForkJoinPoolStarvationSpec.scala @@ -29,7 +29,7 @@ object ForkJoinPoolStarvationSpec { self ! "tick" override def receive = { - case "tick" ⇒ + case "tick" => self ! "tick" } } @@ -37,7 +37,7 @@ object ForkJoinPoolStarvationSpec { class InnocentActor extends Actor { override def receive = { - case "ping" ⇒ + case "ping" => sender ! "All fine" } } @@ -59,7 +59,7 @@ class ForkJoinPoolStarvationSpec extends AkkaSpec(ForkJoinPoolStarvationSpec.con val innocentActor = system.actorOf(Props(new InnocentActor).withDispatcher("actorhang.task-dispatcher")) - for (_ ← 1 to Iterations) { + for (_ <- 1 to Iterations) { // External task submission via the default dispatcher innocentActor ! "ping" expectMsg("All fine") diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala index 0968565281..e3d2f23a28 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/MailboxConfigSpec.scala @@ -17,7 +17,7 @@ import scala.concurrent.duration._ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAndAfterEach { def name: String - def factory: MailboxType ⇒ MessageQueue + def factory: MailboxType => MessageQueue def supportsBeingBounded = true @@ -47,7 +47,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn val q = factory(config) ensureInitialMailboxState(config, q) - for (i ← 1 to config.capacity) q.enqueue(testActor, exampleMessage) + for (i <- 1 to config.capacity) q.enqueue(testActor, exampleMessage) q.numberOfMessages should ===(config.capacity) q.hasMessages should ===(true) @@ -80,14 +80,14 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn } //CANDIDATE FOR TESTKIT - def spawn[T <: AnyRef](fun: ⇒ T): Future[T] = Future(fun)(ExecutionContext.global) + def spawn[T <: AnyRef](fun: => T): Future[T] = Future(fun)(ExecutionContext.global) def createMessageInvocation(msg: Any): Envelope = Envelope(msg, system.deadLetters, system) def ensureMailboxSize(q: MessageQueue, expected: Int): Unit = q.numberOfMessages match { - case -1 | `expected` ⇒ + case -1 | `expected` => q.hasMessages should ===(expected != 0) - case other ⇒ + case other => other should ===(expected) q.hasMessages should ===(expected != 0) } @@ -96,14 +96,14 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn val q = factory(config) ensureMailboxSize(q, 0) q.dequeue should ===(null) - for (i ← 1 to 100) { + for (i <- 1 to 100) { q.enqueue(testActor, exampleMessage) ensureMailboxSize(q, i) } ensureMailboxSize(q, 100) - for (i ← 99 to 0 by -1) { + for (i <- 99 to 0 by -1) { q.dequeue() should ===(exampleMessage) ensureMailboxSize(q, i) } @@ -115,12 +115,12 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn def ensureInitialMailboxState(config: MailboxType, q: MessageQueue): Unit = { q should not be null q match { - case aQueue: BlockingQueue[_] ⇒ + case aQueue: BlockingQueue[_] => config match { - case BoundedMailbox(capacity, _) ⇒ aQueue.remainingCapacity should ===(capacity) - case UnboundedMailbox() ⇒ aQueue.remainingCapacity should ===(Int.MaxValue) + case BoundedMailbox(capacity, _) => aQueue.remainingCapacity should ===(capacity) + case UnboundedMailbox() => aQueue.remainingCapacity should ===(Int.MaxValue) } - case _ ⇒ + case _ => } q.numberOfMessages should ===(0) q.hasMessages should ===(false) @@ -139,14 +139,14 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn occurrences = (enqueueN - dequeueN)) intercept { def createProducer(fromNum: Int, toNum: Int): Future[Vector[Envelope]] = spawn { - val messages = Vector() ++ (for (i ← fromNum to toNum) yield createMessageInvocation(i)) - for (i ← messages) q.enqueue(testActor, i) + val messages = Vector() ++ (for (i <- fromNum to toNum) yield createMessageInvocation(i)) + for (i <- messages) q.enqueue(testActor, i) messages } val producers = { val step = 500 - val ps = for (i ← (1 to enqueueN by step).toList) yield createProducer(i, Math.min(enqueueN, i + step - 1)) + val ps = for (i <- (1 to enqueueN by step).toList) yield createProducer(i, Math.min(enqueueN, i + step - 1)) if (parallel == false) ps foreach { Await.ready(_, remainingOrDefault) } @@ -158,7 +158,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn var r = Vector[Envelope]() while (producers.exists(_.isCompleted == false) || q.hasMessages) - Option(q.dequeue) foreach { message ⇒ r = r :+ message } + Option(q.dequeue) foreach { message => r = r :+ message } r } @@ -183,8 +183,8 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn class DefaultMailboxSpec extends MailboxSpec { lazy val name = "The default mailbox implementation" def factory = { - case u: UnboundedMailbox ⇒ u.create(None, None) - case b: BoundedMailbox ⇒ b.create(None, None) + case u: UnboundedMailbox => u.create(None, None) + case b: BoundedMailbox => b.create(None, None) } } @@ -192,8 +192,8 @@ class PriorityMailboxSpec extends MailboxSpec { val comparator = PriorityGenerator(_.##) lazy val name = "The priority mailbox implementation" def factory = { - case UnboundedMailbox() ⇒ new UnboundedPriorityMailbox(comparator).create(None, None) - case BoundedMailbox(capacity, pushTimeOut) ⇒ new BoundedPriorityMailbox(comparator, capacity, pushTimeOut).create(None, None) + case UnboundedMailbox() => new UnboundedPriorityMailbox(comparator).create(None, None) + case BoundedMailbox(capacity, pushTimeOut) => new BoundedPriorityMailbox(comparator, capacity, pushTimeOut).create(None, None) } } @@ -201,16 +201,16 @@ class StablePriorityMailboxSpec extends MailboxSpec { val comparator = PriorityGenerator(_.##) lazy val name = "The stable priority mailbox implementation" def factory = { - case UnboundedMailbox() ⇒ new UnboundedStablePriorityMailbox(comparator).create(None, None) - case BoundedMailbox(capacity, pushTimeOut) ⇒ new BoundedStablePriorityMailbox(comparator, capacity, pushTimeOut).create(None, None) + case UnboundedMailbox() => new UnboundedStablePriorityMailbox(comparator).create(None, None) + case BoundedMailbox(capacity, pushTimeOut) => new BoundedStablePriorityMailbox(comparator, capacity, pushTimeOut).create(None, None) } } class ControlAwareMailboxSpec extends MailboxSpec { lazy val name = "The control aware mailbox implementation" def factory = { - case UnboundedMailbox() ⇒ new UnboundedControlAwareMailbox().create(None, None) - case BoundedMailbox(capacity, pushTimeOut) ⇒ new BoundedControlAwareMailbox(capacity, pushTimeOut).create(None, None) + case UnboundedMailbox() => new UnboundedControlAwareMailbox().create(None, None) + case BoundedMailbox(capacity, pushTimeOut) => new BoundedControlAwareMailbox(capacity, pushTimeOut).create(None, None) } } @@ -223,8 +223,8 @@ object CustomMailboxSpec { class MyMailboxType(settings: ActorSystem.Settings, config: Config) extends MailboxType { override def create(owner: Option[ActorRef], system: Option[ActorSystem]) = owner match { - case Some(o) ⇒ new MyMailbox(o) - case None ⇒ throw new Exception("no mailbox owner given") + case Some(o) => new MyMailbox(o) + case None => throw new Exception("no mailbox owner given") } } @@ -238,8 +238,8 @@ class CustomMailboxSpec extends AkkaSpec(CustomMailboxSpec.config) { "support custom mailboxType" in { val actor = system.actorOf(Props.empty.withDispatcher("my-dispatcher")) awaitCond(actor match { - case r: RepointableRef ⇒ r.isStarted - case _ ⇒ true + case r: RepointableRef => r.isStarted + case _ => true }, 1 second, 10 millis) val queue = actor.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].mailbox.messageQueue queue.getClass should ===(classOf[CustomMailboxSpec.MyMailbox]) @@ -251,8 +251,8 @@ class SingleConsumerOnlyMailboxSpec extends MailboxSpec { lazy val name = "The single-consumer-only mailbox implementation" override def maxConsumers = 1 def factory = { - case u: UnboundedMailbox ⇒ SingleConsumerOnlyUnboundedMailbox().create(None, None) - case b @ BoundedMailbox(capacity, _) ⇒ NonBlockingBoundedMailbox(capacity).create(None, None) + case u: UnboundedMailbox => SingleConsumerOnlyUnboundedMailbox().create(None, None) + case b @ BoundedMailbox(capacity, _) => NonBlockingBoundedMailbox(capacity).create(None, None) } } @@ -281,7 +281,7 @@ class SingleConsumerOnlyMailboxVerificationSpec extends AkkaSpec(SingleConsumerO context.actorOf(Props(new Actor { var n = total / 2 def receive = { - case Ping ⇒ + case Ping => n -= 1 sender() ! Ping if (n == 0) @@ -289,8 +289,8 @@ class SingleConsumerOnlyMailboxVerificationSpec extends AkkaSpec(SingleConsumerO } }).withDispatcher(dispatcherId))) def receive = { - case Ping ⇒ a.tell(Ping, b) - case Terminated(`a` | `b`) ⇒ if (context.children.isEmpty) context stop self + case Ping => a.tell(Ping, b) + case Terminated(`a` | `b`) => if (context.children.isEmpty) context stop self } })) watch(runner) diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala index 0158c69dbb..385fe99833 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/PriorityDispatcherSpec.scala @@ -23,14 +23,14 @@ object PriorityDispatcherSpec { """ class Unbounded(settings: ActorSystem.Settings, config: Config) extends UnboundedPriorityMailbox(PriorityGenerator({ - case i: Int ⇒ i //Reverse order - case 'Result ⇒ Int.MaxValue - }: Any ⇒ Int)) + case i: Int => i //Reverse order + case 'Result => Int.MaxValue + }: Any => Int)) class Bounded(settings: ActorSystem.Settings, config: Config) extends BoundedPriorityMailbox(PriorityGenerator({ - case i: Int ⇒ i //Reverse order - case 'Result ⇒ Int.MaxValue - }: Any ⇒ Int), 1000, 10 seconds) + case i: Int => i //Reverse order + case 'Result => Int.MaxValue + }: Any => Int), 1000, 10 seconds) } @@ -60,13 +60,13 @@ class PriorityDispatcherSpec extends AkkaSpec(PriorityDispatcherSpec.config) wit val acc = scala.collection.mutable.ListBuffer[Int]() - scala.util.Random.shuffle(msgs) foreach { m ⇒ self ! m } + scala.util.Random.shuffle(msgs) foreach { m => self ! m } self.tell('Result, testActor) def receive = { - case i: Int ⇒ acc += i - case 'Result ⇒ sender() ! acc.toList + case i: Int => acc += i + case 'Result => sender() ! acc.toList } }).withDispatcher(dispatcherKey)) diff --git a/akka-actor-tests/src/test/scala/akka/dispatch/StablePriorityDispatcherSpec.scala b/akka-actor-tests/src/test/scala/akka/dispatch/StablePriorityDispatcherSpec.scala index b36df82020..bbf64251c7 100644 --- a/akka-actor-tests/src/test/scala/akka/dispatch/StablePriorityDispatcherSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/dispatch/StablePriorityDispatcherSpec.scala @@ -23,16 +23,16 @@ object StablePriorityDispatcherSpec { """ class Unbounded(settings: ActorSystem.Settings, config: Config) extends UnboundedStablePriorityMailbox(PriorityGenerator({ - case i: Int if i <= 100 ⇒ i // Small integers have high priority - case i: Int ⇒ 101 // Don't care for other integers - case 'Result ⇒ Int.MaxValue - }: Any ⇒ Int)) + case i: Int if i <= 100 => i // Small integers have high priority + case i: Int => 101 // Don't care for other integers + case 'Result => Int.MaxValue + }: Any => Int)) class Bounded(settings: ActorSystem.Settings, config: Config) extends BoundedStablePriorityMailbox(PriorityGenerator({ - case i: Int if i <= 100 ⇒ i // Small integers have high priority - case i: Int ⇒ 101 // Don't care for other integers - case 'Result ⇒ Int.MaxValue - }: Any ⇒ Int), 1000, 10 seconds) + case i: Int if i <= 100 => i // Small integers have high priority + case i: Int => 101 // Don't care for other integers + case 'Result => Int.MaxValue + }: Any => Int), 1000, 10 seconds) } @@ -64,13 +64,13 @@ class StablePriorityDispatcherSpec extends AkkaSpec(StablePriorityDispatcherSpec val acc = scala.collection.mutable.ListBuffer[Int]() - shuffled foreach { m ⇒ self ! m } + shuffled foreach { m => self ! m } self.tell('Result, testActor) def receive = { - case i: Int ⇒ acc += i - case 'Result ⇒ sender() ! acc.toList + case i: Int => acc += i + case 'Result => sender() ! acc.toList } }).withDispatcher(dispatcherKey)) diff --git a/akka-actor-tests/src/test/scala/akka/event/EventBusSpec.scala b/akka-actor-tests/src/test/scala/akka/event/EventBusSpec.scala index ddc634cbce..cf1a78a29d 100644 --- a/akka-actor-tests/src/test/scala/akka/event/EventBusSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/EventBusSpec.scala @@ -17,7 +17,7 @@ import com.typesafe.config.{ Config, ConfigFactory } object EventBusSpec { class TestActorWrapperActor(testActor: ActorRef) extends Actor { def receive = { - case x ⇒ testActor forward x + case x => testActor forward x } } } @@ -74,11 +74,11 @@ abstract class EventBusSpec(busName: String, conf: Config = ConfigFactory.empty( } "allow to add multiple subscribers" in { - val subscribers = (1 to 10) map { _ ⇒ createNewSubscriber() } + val subscribers = (1 to 10) map { _ => createNewSubscriber() } val events = createEvents(10) val classifiers = events map getClassifierFor - subscribers.zip(classifiers) forall { case (s, c) ⇒ bus.subscribe(s, c) } should ===(true) - subscribers.zip(classifiers) forall { case (s, c) ⇒ bus.unsubscribe(s, c) } should ===(true) + subscribers.zip(classifiers) forall { case (s, c) => bus.subscribe(s, c) } should ===(true) + subscribers.zip(classifiers) forall { case (s, c) => bus.unsubscribe(s, c) } should ===(true) subscribers foreach (disposeSubscriber(system, _)) } @@ -109,11 +109,11 @@ abstract class EventBusSpec(busName: String, conf: Config = ConfigFactory.empty( "publish the given event to all intended subscribers" in { val range = 0 until 10 - val subscribers = range map (_ ⇒ createNewSubscriber()) - subscribers foreach { s ⇒ bus.subscribe(s, classifier) should ===(true) } + val subscribers = range map (_ => createNewSubscriber()) + subscribers foreach { s => bus.subscribe(s, classifier) should ===(true) } bus.publish(event) - range foreach { _ ⇒ expectMsg(event) } - subscribers foreach { s ⇒ bus.unsubscribe(s, classifier) should ===(true); disposeSubscriber(system, s) } + range foreach { _ => expectMsg(event) } + subscribers foreach { s => bus.unsubscribe(s, classifier) should ===(true); disposeSubscriber(system, s) } } "not publish the given event to any other subscribers than the intended ones" in { @@ -261,16 +261,16 @@ class ActorEventBusSpec(conf: Config) extends EventBusSpec("ActorEventBus", conf private def expectUnsubscribedByUnsubscriber(p: TestProbe, a: ActorRef): Unit = { val expectedMsg = s"actor $a has terminated, unsubscribing it from $bus" p.fishForMessage(1 second, hint = expectedMsg) { - case Logging.Debug(_, _, msg) if msg equals expectedMsg ⇒ true - case other ⇒ false + case Logging.Debug(_, _, msg) if msg equals expectedMsg => true + case other => false } } private def expectUnregisterFromUnsubscriber(p: TestProbe, a: ActorRef): Unit = { val expectedMsg = s"unregistered watch of $a in $bus" p.fishForMessage(1 second, hint = expectedMsg) { - case Logging.Debug(_, _, msg) if msg equals expectedMsg ⇒ true - case other ⇒ false + case Logging.Debug(_, _, msg) if msg equals expectedMsg => true + case other => false } } } diff --git a/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala b/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala index 1f09f17e8a..0f48ab9edd 100644 --- a/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala @@ -42,13 +42,13 @@ object EventStreamSpec { class MyLog extends Actor { var dst: ActorRef = context.system.deadLetters def receive = { - case Logging.InitializeLogger(bus) ⇒ + case Logging.InitializeLogger(bus) => bus.subscribe(context.self, classOf[SetTarget]) bus.subscribe(context.self, classOf[UnhandledMessage]) sender() ! Logging.LoggerInitialized - case SetTarget(ref) ⇒ { dst = ref; dst ! "OK" } - case e: Logging.LogEvent ⇒ dst ! e - case u: UnhandledMessage ⇒ dst ! u + case SetTarget(ref) => { dst = ref; dst ! "OK" } + case e: Logging.LogEvent => dst ! e + case u: UnhandledMessage => dst ! u } } @@ -289,7 +289,7 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) { val tm = new A val target = sys.actorOf(Props(new Actor { - def receive = { case in ⇒ a1.ref forward in } + def receive = { case in => a1.ref forward in } }), "to-be-killed") es.subscribe(a2.ref, classOf[Any]) @@ -317,7 +317,7 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) { val a1, a2 = TestProbe() val target = system.actorOf(Props(new Actor { - def receive = { case in ⇒ a1.ref forward in } + def receive = { case in => a1.ref forward in } }), "to-be-killed") watch(target) @@ -416,8 +416,8 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) { private def fishForDebugMessage(a: TestProbe, messagePrefix: String, max: Duration = 3 seconds): Unit = { a.fishForMessage(max, hint = "expected debug message prefix: " + messagePrefix) { - case Logging.Debug(_, _, msg: String) if msg startsWith messagePrefix ⇒ true - case other ⇒ false + case Logging.Debug(_, _, msg: String) if msg startsWith messagePrefix => true + case other => false } } diff --git a/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala b/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala index 8f15e925ff..7f446250f5 100644 --- a/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala @@ -89,16 +89,16 @@ object LoggerSpec { abstract class TestLogger(qualifier: Int) extends Actor with Logging.StdOutLogger { var target: Option[ActorRef] = None override def receive: Receive = { - case InitializeLogger(bus) ⇒ + case InitializeLogger(bus) => bus.subscribe(context.self, classOf[SetTarget]) sender() ! LoggerInitialized - case SetTarget(ref, `qualifier`) ⇒ + case SetTarget(ref, `qualifier`) => target = Some(ref) ref ! ("OK") - case event: LogEvent if !event.mdc.isEmpty ⇒ + case event: LogEvent if !event.mdc.isEmpty => print(event) target foreach { _ ! event } - case event: LogEvent ⇒ + case event: LogEvent => print(event) target foreach { _ ! event.message } } @@ -107,11 +107,11 @@ object LoggerSpec { class SlowLogger extends Logging.DefaultLogger { override def aroundReceive(r: Receive, msg: Any): Unit = { msg match { - case event: LogEvent ⇒ + case event: LogEvent => if (event.message.toString.startsWith("msg1")) Thread.sleep(500) // slow super.aroundReceive(r, msg) - case _ ⇒ super.aroundReceive(r, msg) + case _ => super.aroundReceive(r, msg) } } @@ -122,17 +122,17 @@ object LoggerSpec { override def mdc(currentMessage: Any): MDC = { reqId += 1 - val always = Map("requestId" → reqId) + val always = Map("requestId" -> reqId) val cmim = "Current Message in MDC" val perMessage = currentMessage match { - case `cmim` ⇒ Map[String, Any]("currentMsg" → cmim, "currentMsgLength" → cmim.length) - case _ ⇒ Map() + case `cmim` => Map[String, Any]("currentMsg" -> cmim, "currentMsgLength" -> cmim.length) + case _ => Map() } always ++ perMessage } def receive: Receive = { - case m: String ⇒ log.warning(m) + case m: String => log.warning(m) } } @@ -154,8 +154,8 @@ class LoggerSpec extends WordSpec with Matchers { // since logging is asynchronous ensure that it propagates if (shouldLog) { probe.fishForMessage(0.5.seconds.dilated) { - case "Danger! Danger!" ⇒ true - case _ ⇒ false + case "Danger! Danger!" => true + case _ => false } } else { probe.expectNoMsg(0.5.seconds.dilated) @@ -238,12 +238,12 @@ class LoggerSpec extends WordSpec with Matchers { ref ! "Processing new Request" probe.expectMsgPF(max = 3.seconds) { - case w @ Warning(_, _, "Processing new Request") if w.mdc.size == 1 && w.mdc("requestId") == 1 ⇒ + case w @ Warning(_, _, "Processing new Request") if w.mdc.size == 1 && w.mdc("requestId") == 1 => } ref ! "Processing another Request" probe.expectMsgPF(max = 3.seconds) { - case w @ Warning(_, _, "Processing another Request") if w.mdc.size == 1 && w.mdc("requestId") == 2 ⇒ + case w @ Warning(_, _, "Processing another Request") if w.mdc.size == 1 && w.mdc("requestId") == 2 => } ref ! "Current Message in MDC" @@ -251,12 +251,12 @@ class LoggerSpec extends WordSpec with Matchers { case w @ Warning(_, _, "Current Message in MDC") if w.mdc.size == 3 && w.mdc("requestId") == 3 && w.mdc("currentMsg") == "Current Message in MDC" && - w.mdc("currentMsgLength") == 22 ⇒ + w.mdc("currentMsgLength") == 22 => } ref ! "Current Message removed from MDC" probe.expectMsgPF(max = 3.seconds) { - case w @ Warning(_, _, "Current Message removed from MDC") if w.mdc.size == 1 && w.mdc("requestId") == 4 ⇒ + case w @ Warning(_, _, "Current Message removed from MDC") if w.mdc.size == 1 && w.mdc("requestId") == 4 => } } finally { diff --git a/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala b/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala index 1b53947b49..50fe07bd94 100644 --- a/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala @@ -19,7 +19,7 @@ object LoggingReceiveSpec { class TestLogActor extends Actor { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 5 seconds)(List(classOf[Throwable])) - def receive = { case _ ⇒ } + def receive = { case _ => } } } @@ -30,14 +30,14 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { akka.loglevel=DEBUG # test verifies debug akka.actor.serialize-messages = off # debug noise from serialization """).withFallback(AkkaSpec.testConf) - val appLogging = ActorSystem("logging", ConfigFactory.parseMap(Map("akka.actor.debug.receive" → true).asJava).withFallback(config)) - val appAuto = ActorSystem("autoreceive", ConfigFactory.parseMap(Map("akka.actor.debug.autoreceive" → true).asJava).withFallback(config)) - val appLifecycle = ActorSystem("lifecycle", ConfigFactory.parseMap(Map("akka.actor.debug.lifecycle" → true).asJava).withFallback(config)) + val appLogging = ActorSystem("logging", ConfigFactory.parseMap(Map("akka.actor.debug.receive" -> true).asJava).withFallback(config)) + val appAuto = ActorSystem("autoreceive", ConfigFactory.parseMap(Map("akka.actor.debug.autoreceive" -> true).asJava).withFallback(config)) + val appLifecycle = ActorSystem("lifecycle", ConfigFactory.parseMap(Map("akka.actor.debug.lifecycle" -> true).asJava).withFallback(config)) val filter = TestEvent.Mute(EventFilter.custom { - case _: Logging.Debug ⇒ true - case _: Logging.Info ⇒ true - case _ ⇒ false + case _: Logging.Debug => true + case _: Logging.Info => true + case _ => false }) appLogging.eventStream.publish(filter) appAuto.eventStream.publish(filter) @@ -45,7 +45,7 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { def ignoreMute(t: TestKit): Unit = { t.ignoreMsg { - case (_: TestEvent.Mute | _: TestEvent.UnMute) ⇒ true + case (_: TestEvent.Mute | _: TestEvent.UnMute) => true } } @@ -63,7 +63,7 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { system.eventStream.subscribe(testActor, classOf[UnhandledMessage]) val a = system.actorOf(Props(new Actor { def receive = new LoggingReceive(Some("funky"), { - case null ⇒ + case null => }) })) a ! "hallo" @@ -80,13 +80,13 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { system.eventStream.subscribe(testActor, classOf[UnhandledMessage]) val r: Actor.Receive = { - case null ⇒ + case null => } val actor = TestActorRef(new Actor { - def switch: Actor.Receive = { case "becomenull" ⇒ context.become(r, false) } + def switch: Actor.Receive = { case "becomenull" => context.become(r, false) } def receive = switch orElse LoggingReceive { - case x ⇒ sender() ! "x" + case x => sender() ! "x" } }) @@ -100,7 +100,7 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { actor ! "bah" expectMsgPF() { - case UnhandledMessage("bah", testActor, `actor`) ⇒ true + case UnhandledMessage("bah", testActor, `actor`) => true } } } @@ -110,7 +110,7 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { system.eventStream.subscribe(testActor, classOf[Logging.Debug]) val actor = TestActorRef(new Actor { def receive = LoggingReceive(LoggingReceive { - case _ ⇒ sender() ! "x" + case _ => sender() ! "x" }) }) actor ! "buh" @@ -123,16 +123,16 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { "log with MDC" in { new TestKit(appLogging) { system.eventStream.subscribe(testActor, classOf[Logging.Debug]) - val myMDC = Map("hello" → "mdc") + val myMDC = Map("hello" -> "mdc") val a = system.actorOf(Props(new Actor with DiagnosticActorLogging { override def mdc(currentMessage: Any) = myMDC def receive = LoggingReceive { - case "hello" ⇒ + case "hello" => } })) a ! "hello" expectMsgPF(hint = "Logging.Debug2") { - case m: Logging.Debug2 if m.mdc == myMDC ⇒ () + case m: Logging.Debug2 if m.mdc == myMDC => () } } } @@ -142,7 +142,7 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { system.eventStream.subscribe(testActor, classOf[Logging.Info]) val actor = TestActorRef(new Actor { def receive = LoggingReceive(Logging.InfoLevel) { - case _ ⇒ sender() ! "x" + case _ => sender() ! "x" } }) actor ! "buh" @@ -161,14 +161,14 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { system.eventStream.subscribe(testActor, classOf[Logging.Debug]) val actor = TestActorRef(new Actor { def receive = { - case _ ⇒ + case _ => } }) val name = actor.path.toString actor ! PoisonPill fishForMessage(hint = "received AutoReceiveMessage Envelope(PoisonPill") { - case Logging.Debug(`name`, _, msg: String) if msg startsWith "received AutoReceiveMessage Envelope(PoisonPill" ⇒ true - case _ ⇒ false + case Logging.Debug(`name`, _, msg: String) if msg startsWith "received AutoReceiveMessage Envelope(PoisonPill" => true + case _ => false } awaitCond(actor.isTerminated) } @@ -184,15 +184,15 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { val sname = supervisor.path.toString fishForMessage(hint = "now supervising") { - case Logging.Debug(`lname`, _, msg: String) if msg startsWith "now supervising" ⇒ true - case _ ⇒ false + case Logging.Debug(`lname`, _, msg: String) if msg startsWith "now supervising" => true + case _ => false } TestActorRef[TestLogActor](Props[TestLogActor], supervisor, "none") fishForMessage(hint = "now supervising") { - case Logging.Debug(`sname`, _, msg: String) if msg startsWith "now supervising" ⇒ true - case _ ⇒ false + case Logging.Debug(`sname`, _, msg: String) if msg startsWith "now supervising" => true + case _ => false } } } @@ -209,14 +209,14 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { supervisor watch actor fishForMessage(hint = "now watched by") { - case Logging.Debug(`aname`, `sclass`, msg: String) if msg.startsWith("now watched by") ⇒ true - case m ⇒ false + case Logging.Debug(`aname`, `sclass`, msg: String) if msg.startsWith("now watched by") => true + case m => false } supervisor unwatch actor fishForMessage(hint = "no longer watched by") { - case Logging.Debug(`aname`, `sclass`, msg: String) if msg.startsWith("no longer watched by") ⇒ true - case _ ⇒ false + case Logging.Debug(`aname`, `sclass`, msg: String) if msg.startsWith("no longer watched by") => true + case _ => false } } } @@ -232,8 +232,8 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { val sclass = classOf[TestLogActor] expectMsgAllPF(messages = 2) { - case Logging.Debug(`sname`, `sclass`, msg: String) if msg startsWith "started" ⇒ 0 - case Logging.Debug(_, _, msg: String) if msg startsWith "now supervising" ⇒ 1 + case Logging.Debug(`sname`, `sclass`, msg: String) if msg startsWith "started" => 0 + case Logging.Debug(_, _, msg: String) if msg startsWith "now supervising" => 1 } val actor = TestActorRef[TestLogActor](Props[TestLogActor], supervisor, "none") @@ -241,16 +241,16 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll { val aclass = classOf[TestLogActor] expectMsgAllPF(messages = 2) { - case Logging.Debug(`aname`, `aclass`, msg: String) if msg.startsWith("started (" + classOf[TestLogActor].getName) ⇒ 0 - case Logging.Debug(`sname`, `sclass`, msg: String) if msg == s"now supervising TestActor[$aname]" ⇒ 1 + case Logging.Debug(`aname`, `aclass`, msg: String) if msg.startsWith("started (" + classOf[TestLogActor].getName) => 0 + case Logging.Debug(`sname`, `sclass`, msg: String) if msg == s"now supervising TestActor[$aname]" => 1 } EventFilter[ActorKilledException](occurrences = 1) intercept { actor ! Kill expectMsgAllPF(messages = 3) { - case Logging.Error(_: ActorKilledException, `aname`, _, "Kill") ⇒ 0 - case Logging.Debug(`aname`, `aclass`, "restarting") ⇒ 1 - case Logging.Debug(`aname`, `aclass`, "restarted") ⇒ 2 + case Logging.Error(_: ActorKilledException, `aname`, _, "Kill") => 0 + case Logging.Debug(`aname`, `aclass`, "restarting") => 1 + case Logging.Debug(`aname`, `aclass`, "restarted") => 2 } } diff --git a/akka-actor-tests/src/test/scala/akka/event/MarkerLoggingSpec.scala b/akka-actor-tests/src/test/scala/akka/event/MarkerLoggingSpec.scala index 882810caaa..125f25595d 100644 --- a/akka-actor-tests/src/test/scala/akka/event/MarkerLoggingSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/MarkerLoggingSpec.scala @@ -9,7 +9,7 @@ import akka.testkit._ class MarkerLoggingSpec extends AkkaSpec with ImplicitSender { "A MarkerLoggerAdapter" should { - val markerLogging = new MarkerLoggingAdapter(system.eventStream, getClass.getName, this.getClass, new DefaultLoggingFilter(() ⇒ Logging.InfoLevel)) + val markerLogging = new MarkerLoggingAdapter(system.eventStream, getClass.getName, this.getClass, new DefaultLoggingFilter(() => Logging.InfoLevel)) "add markers to logging" in { system.eventStream.subscribe(self, classOf[Info]) diff --git a/akka-actor-tests/src/test/scala/akka/event/jul/JavaLoggerSpec.scala b/akka-actor-tests/src/test/scala/akka/event/jul/JavaLoggerSpec.scala index a02ed7af1a..1310dbc710 100644 --- a/akka-actor-tests/src/test/scala/akka/event/jul/JavaLoggerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/jul/JavaLoggerSpec.scala @@ -21,9 +21,9 @@ object JavaLoggerSpec { class LogProducer extends Actor with ActorLogging { def receive = { - case e: Exception ⇒ + case e: Exception => log.error(e, e.getMessage) - case (s: String, x: Int) ⇒ + case (s: String, x: Int) => log.info(s, x) } } diff --git a/akka-actor-tests/src/test/scala/akka/io/InetAddressDnsResolverSpec.scala b/akka-actor-tests/src/test/scala/akka/io/InetAddressDnsResolverSpec.scala index 29cf3b9b74..fc0049c889 100644 --- a/akka-actor-tests/src/test/scala/akka/io/InetAddressDnsResolverSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/InetAddressDnsResolverSpec.scala @@ -14,7 +14,7 @@ class InetAddressDnsResolverSpec extends AkkaSpec(""" akka.io.dns.inet-address.positive-ttl = default akka.io.dns.inet-address.negative-ttl = default akka.actor.serialize-creators = on - """) { thisSpecs ⇒ + """) { thisSpecs => "The DNS resolver default ttl's" must { "use the default value for positive caching if it is not overridden" in { @@ -96,23 +96,23 @@ class InetAddressDnsResolverSpec extends AkkaSpec(""" actorRef.underlyingActor } - private def withNewSystemProperty[T](property: String, testValue: String)(test: ⇒ T): T = { + private def withNewSystemProperty[T](property: String, testValue: String)(test: => T): T = { val oldValue = Option(System.getProperty(property)) try { System.setProperty(property, testValue) test } finally { - oldValue.foreach(v ⇒ System.setProperty(property, v)) + oldValue.foreach(v => System.setProperty(property, v)) } } - private def withNewSecurityProperty[T](property: String, testValue: String)(test: ⇒ T): T = { + private def withNewSecurityProperty[T](property: String, testValue: String)(test: => T): T = { val oldValue = Option(Security.getProperty(property)) try { Security.setProperty(property, testValue) test } finally { - oldValue.foreach(v ⇒ Security.setProperty(property, v)) + oldValue.foreach(v => Security.setProperty(property, v)) } } @@ -123,7 +123,7 @@ class InetAddressDnsResolverConfigSpec extends AkkaSpec( akka.io.dns.inet-address.negative-ttl = never akka.actor.serialize-creators = on """) { - thisSpecs ⇒ + thisSpecs => "The DNS resolver parsed ttl's" must { "use ttl=Long.MaxValue if user provides 'forever' " in { diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala index 3440a47e29..4a75039e57 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala @@ -46,7 +46,7 @@ class TcpConnectionSpec extends AkkaSpec(""" akka.io.tcp.trace-logging = on akka.io.tcp.register-timeout = 500ms akka.actor.serialize-creators = on - """) with WithLogCapturing { thisSpecs ⇒ + """) with WithLogCapturing { thisSpecs => import TcpConnectionSpec._ // Helper to avoid Windows localization specific differences @@ -67,7 +67,7 @@ class TcpConnectionSpec extends AkkaSpec(""" clientSocket.read(ByteBuffer.allocate(1)) null } catch { - case NonFatal(e) ⇒ e.getMessage + case NonFatal(e) => e.getMessage } } @@ -81,7 +81,7 @@ class TcpConnectionSpec extends AkkaSpec(""" clientSocket.write(ByteBuffer.allocate(1)) null } catch { - case NonFatal(e) ⇒ e.getMessage.take(15) + case NonFatal(e) => e.getMessage.take(15) } } @@ -248,7 +248,7 @@ class TcpConnectionSpec extends AkkaSpec(""" val writer = Files.newBufferedWriter(tmpFile) val oneKByteOfF = Array.fill[Char](1000)('F') // 10 mb of f:s in a file - for (_ ← 0 to 10000) { + for (_ <- 0 to 10000) { writer.write(oneKByteOfF) } writer.flush() @@ -718,7 +718,7 @@ class TcpConnectionSpec extends AkkaSpec(""" } // dump the NACKs writer.receiveWhile(1.second) { - case CommandFailed(write) ⇒ written -= 1 + case CommandFailed(write) => written -= 1 } writer.msgAvailable should ===(false) @@ -756,7 +756,7 @@ class TcpConnectionSpec extends AkkaSpec(""" } // dump the NACKs writer.receiveWhile(1.second) { - case CommandFailed(write) ⇒ written -= 1 + case CommandFailed(write) => written -= 1 } // drain the queue until it works again @@ -792,7 +792,7 @@ class TcpConnectionSpec extends AkkaSpec(""" } // dump the NACKs writer.receiveWhile(1.second) { - case CommandFailed(write) ⇒ written -= 1 + case CommandFailed(write) => written -= 1 } writer.msgAvailable should ===(false) @@ -825,7 +825,7 @@ class TcpConnectionSpec extends AkkaSpec(""" } // dump the NACKs writer.receiveWhile(1.second) { - case CommandFailed(write) ⇒ written -= 1 + case CommandFailed(write) => written -= 1 } // drain the queue until it works again @@ -859,7 +859,7 @@ class TcpConnectionSpec extends AkkaSpec(""" expectTerminated(connectionActor) an[IOException] should be thrownBy { socket.getInputStream.read() } } catch { - case e: SocketTimeoutException ⇒ + case e: SocketTimeoutException => // thrown by serverSocket.accept, this may happen if network is offline info(e.getMessage) pending @@ -895,7 +895,7 @@ class TcpConnectionSpec extends AkkaSpec(""" if (Helpers.isWindows) interestCallReceiver.expectMsg(OP_CONNECT) } - def run(body: ⇒ Unit): Unit = { + def run(body: => Unit): Unit = { try { setServerSocketOptions() localServerChannel.socket.bind(serverAddress) @@ -923,10 +923,10 @@ class TcpConnectionSpec extends AkkaSpec(""" new ChannelRegistration { def enableInterest(op: Int): Unit = interestCallReceiver.ref ! op def disableInterest(op: Int): Unit = interestCallReceiver.ref ! -op - def cancelAndClose(andThen: () ⇒ Unit): Unit = onCancelAndClose(andThen) + def cancelAndClose(andThen: () => Unit): Unit = onCancelAndClose(andThen) } - protected def onCancelAndClose(andThen: () ⇒ Unit): Unit = andThen() + protected def onCancelAndClose(andThen: () => Unit): Unit = andThen() def createConnectionActorWithoutRegistration( serverAddress: InetSocketAddress = serverAddress, @@ -940,7 +940,7 @@ class TcpConnectionSpec extends AkkaSpec(""" }) } - trait SmallRcvBuffer { _: LocalServerTest ⇒ + trait SmallRcvBuffer { _: LocalServerTest => override def setServerSocketOptions(): Unit = localServerChannel.socket.setReceiveBufferSize(1024) } @@ -950,7 +950,7 @@ class TcpConnectionSpec extends AkkaSpec(""" // calling .underlyingActor ensures that the actor is actually created at this point lazy val clientSideChannel = connectionActor.underlyingActor.channel - override def run(body: ⇒ Unit): Unit = super.run { + override def run(body: => Unit): Unit = super.run { registerCallReceiver.expectMsg(Registration(clientSideChannel, 0)) registerCallReceiver.sender should ===(connectionActor) body @@ -984,7 +984,7 @@ class TcpConnectionSpec extends AkkaSpec(""" if (Helpers.isWindows) clientSelectionKey.interestOps(OP_CONNECT) } - override def run(body: ⇒ Unit): Unit = super.run { + override def run(body: => Unit): Unit = super.run { try { serverSideChannel.configureBlocking(false) serverSideChannel should not be (null) @@ -1039,7 +1039,7 @@ class TcpConnectionSpec extends AkkaSpec(""" (sel, key) } - override protected def onCancelAndClose(andThen: () ⇒ Unit): Unit = + override protected def onCancelAndClose(andThen: () => Unit): Unit = try { if (clientSideChannel.isOpen) clientSideChannel.close() if (nioSelector.isOpen) { @@ -1072,9 +1072,9 @@ class TcpConnectionSpec extends AkkaSpec(""" if (nioSelector.selectedKeys().contains(serverSelectionKey)) { if (into eq defaultbuffer) into.clear() serverSideChannel.read(into) match { - case -1 ⇒ throw new IllegalStateException("Connection was closed unexpectedly with remaining bytes " + remaining) - case 0 ⇒ throw new IllegalStateException("Made no progress") - case other ⇒ other + case -1 => throw new IllegalStateException("Connection was closed unexpectedly with remaining bytes " + remaining) + case 0 => throw new IllegalStateException("Made no progress") + case other => other } } else 0 @@ -1111,14 +1111,14 @@ class TcpConnectionSpec extends AkkaSpec(""" } val interestsNames = - Seq(OP_ACCEPT → "accepting", OP_CONNECT → "connecting", OP_READ → "reading", OP_WRITE → "writing") + Seq(OP_ACCEPT -> "accepting", OP_CONNECT -> "connecting", OP_READ -> "reading", OP_WRITE -> "writing") def interestsDesc(interests: Int): String = - interestsNames.filter(i ⇒ (i._1 & interests) != 0).map(_._2).mkString(", ") + interestsNames.filter(i => (i._1 & interests) != 0).map(_._2).mkString(", ") def abortClose(channel: SocketChannel): Unit = { try channel.socket.setSoLinger(true, 0) // causes the following close() to send TCP RST catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // setSoLinger can fail due to http://bugs.sun.com/view_bug.do?bug_id=6799574 // (also affected: OS/X Java 1.6.0_37) log.debug("setSoLinger(true, 0) failed with {}", e) diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala index 3129f869ad..50eca143b4 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala @@ -171,7 +171,7 @@ class TcpIntegrationSpec extends AkkaSpec(""" val endpoint = new InetSocketAddress("192.0.2.1", 23825) connectCommander.send(IO(Tcp), Connect(endpoint)) // expecting CommandFailed or no reply (within timeout) - val replies = connectCommander.receiveWhile(1.second) { case m: Connected ⇒ m } + val replies = connectCommander.receiveWhile(1.second) { case m: Connected => m } replies should ===(Nil) } @@ -188,7 +188,7 @@ class TcpIntegrationSpec extends AkkaSpec(""" try { accept.getInputStream.read() should ===(-1) } catch { - case e: IOException ⇒ // this is also fine + case e: IOException => // this is also fine } } verifyActorTermination(connectionActor) @@ -203,7 +203,7 @@ class TcpIntegrationSpec extends AkkaSpec(""" rounds: Int = 100) = { val testData = ByteString(0) - (1 to rounds) foreach { _ ⇒ + (1 to rounds) foreach { _ => clientHandler.send(clientConnection, Write(testData)) serverHandler.expectMsg(Received(testData)) serverHandler.send(serverConnection, Write(testData)) diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala index e17c3d8267..ef5942be1d 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala @@ -14,14 +14,14 @@ import Tcp._ import akka.actor.ActorSystem import akka.dispatch.ExecutionContexts -trait TcpIntegrationSpecSupport { _: AkkaSpec ⇒ +trait TcpIntegrationSpecSupport { _: AkkaSpec => class TestSetup(shouldBindServer: Boolean = true, runClientInExtraSystem: Boolean = true) { val clientSystem = if (runClientInExtraSystem) { val res = ActorSystem("TcpIntegrationSpec-client", system.settings.config) // terminate clientSystem after server system - system.whenTerminated.onComplete { _ ⇒ res.terminate() }(ExecutionContexts.sameThreadExecutionContext) + system.whenTerminated.onComplete { _ => res.terminate() }(ExecutionContexts.sameThreadExecutionContext) res } else system val bindHandler = TestProbe() diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala index bec9f81e4a..3cef395921 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala @@ -30,7 +30,7 @@ class TcpListenerSpec extends AkkaSpec(""" listener ! new ChannelRegistration { def disableInterest(op: Int) = () def enableInterest(op: Int) = () - def cancelAndClose(andThen: () ⇒ Unit): Unit = () + def cancelAndClose(andThen: () => Unit): Unit = () } bindCommander.expectMsgType[Bound] } @@ -152,7 +152,7 @@ class TcpListenerSpec extends AkkaSpec(""" listener ! new ChannelRegistration { def enableInterest(op: Int): Unit = interestCallReceiver.ref ! op def disableInterest(op: Int): Unit = interestCallReceiver.ref ! -op - def cancelAndClose(andThen: () ⇒ Unit): Unit = { + def cancelAndClose(andThen: () => Unit): Unit = { register.channel.close() require(!register.channel.isRegistered) andThen() @@ -167,7 +167,7 @@ class TcpListenerSpec extends AkkaSpec(""" def expectWorkerForCommand: SocketChannel = selectorRouter.expectMsgPF() { - case WorkerForCommand(RegisterIncoming(chan), commander, _) ⇒ + case WorkerForCommand(RegisterIncoming(chan), commander, _) => chan.isOpen should ===(true) commander should ===(listener) chan @@ -180,7 +180,7 @@ class TcpListenerSpec extends AkkaSpec(""" name = "test-listener-" + counter.next()) parent.watch(listener) def receive: Receive = { - case msg ⇒ parent.ref forward msg + case msg => parent.ref forward msg } override def supervisorStrategy = SupervisorStrategy.stoppingStrategy diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpConnectedIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpConnectedIntegrationSpec.scala index b4755d9247..aa7d7584a5 100644 --- a/akka-actor-tests/src/test/scala/akka/io/UdpConnectedIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/UdpConnectedIntegrationSpec.scala @@ -41,7 +41,7 @@ class UdpConnectedIntegrationSpec extends AkkaSpec(""" connectUdp(localAddress = None, serverAddress, testActor) ! UdpConnected.Send(data1) val clientAddress = expectMsgPF() { - case Udp.Received(d, a) ⇒ + case Udp.Received(d, a) => d should ===(data1) a } @@ -60,7 +60,7 @@ class UdpConnectedIntegrationSpec extends AkkaSpec(""" connectUdp(Some(clientAddress), serverAddress, testActor) ! UdpConnected.Send(data1) expectMsgPF() { - case Udp.Received(d, a) ⇒ + case Udp.Received(d, a) => d should ===(data1) a should ===(clientAddress) } diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpIntegrationSpec.scala index b8cab1c144..ab0cc7ea59 100644 --- a/akka-actor-tests/src/test/scala/akka/io/UdpIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/UdpIntegrationSpec.scala @@ -73,7 +73,7 @@ class UdpIntegrationSpec extends AkkaSpec(""" def checkSendingToClient(): Unit = { server ! Send(data, clientAddress) expectMsgPF() { - case Received(d, a) ⇒ + case Received(d, a) => d should ===(data) a should ===(serverAddress) } @@ -81,15 +81,15 @@ class UdpIntegrationSpec extends AkkaSpec(""" def checkSendingToServer(): Unit = { client ! Send(data, serverAddress) expectMsgPF() { - case Received(d, a) ⇒ + case Received(d, a) => d should ===(data) a should ===(clientAddress) } } - (0 until 20).foreach(_ ⇒ checkSendingToServer()) - (0 until 20).foreach(_ ⇒ checkSendingToClient()) - (0 until 20).foreach { i ⇒ + (0 until 20).foreach(_ => checkSendingToServer()) + (0 until 20).foreach(_ => checkSendingToClient()) + (0 until 20).foreach { i => if (i % 2 == 0) checkSendingToServer() else checkSendingToClient() } diff --git a/akka-actor-tests/src/test/scala/akka/io/dns/AsyncDnsResolverIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/dns/AsyncDnsResolverIntegrationSpec.scala index 981e033312..8731a14925 100644 --- a/akka-actor-tests/src/test/scala/akka/io/dns/AsyncDnsResolverIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/dns/AsyncDnsResolverIntegrationSpec.scala @@ -90,12 +90,12 @@ class AsyncDnsResolverIntegrationSpec extends AkkaSpec( val answer = resolve(name) answer.name shouldEqual name - answer.records.collect { case r: ARecord ⇒ r.ip }.toSet shouldEqual Set( + answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set( InetAddress.getByName("192.168.1.23"), InetAddress.getByName("192.168.1.24") ) - answer.records.collect { case r: AAAARecord ⇒ r.ip }.toSet shouldEqual Set( + answer.records.collect { case r: AAAARecord => r.ip }.toSet shouldEqual Set( InetAddress.getByName("fd4d:36b2:3eca:a2d8:0:0:0:4"), InetAddress.getByName("fd4d:36b2:3eca:a2d8:0:0:0:5") ) @@ -105,10 +105,10 @@ class AsyncDnsResolverIntegrationSpec extends AkkaSpec( val name = "cname-ext.foo.test" val answer = (IO(Dns) ? DnsProtocol.Resolve(name)).mapTo[DnsProtocol.Resolved].futureValue answer.name shouldEqual name - answer.records.collect { case r: CNameRecord ⇒ r.canonicalName }.toSet shouldEqual Set( + answer.records.collect { case r: CNameRecord => r.canonicalName }.toSet shouldEqual Set( "a-single.bar.example" ) - answer.records.collect { case r: ARecord ⇒ r.ip }.toSet shouldEqual Set( + answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set( InetAddress.getByName("192.168.2.20") ) } @@ -117,10 +117,10 @@ class AsyncDnsResolverIntegrationSpec extends AkkaSpec( val name = "cname-in.foo.test" val answer = resolve(name) answer.name shouldEqual name - answer.records.collect { case r: CNameRecord ⇒ r.canonicalName }.toSet shouldEqual Set( + answer.records.collect { case r: CNameRecord => r.canonicalName }.toSet shouldEqual Set( "a-double.foo.test" ) - answer.records.collect { case r: ARecord ⇒ r.ip }.toSet shouldEqual Set( + answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set( InetAddress.getByName("192.168.1.21"), InetAddress.getByName("192.168.1.22") ) @@ -131,7 +131,7 @@ class AsyncDnsResolverIntegrationSpec extends AkkaSpec( val answer = resolve(name, Srv) answer.name shouldEqual name - answer.records.collect { case r: SRVRecord ⇒ r }.toSet shouldEqual Set( + answer.records.collect { case r: SRVRecord => r }.toSet shouldEqual Set( SRVRecord("_service._tcp.foo.test", Ttl.fromPositive(86400.seconds), 10, 65534, 5060, "a-single.foo.test"), SRVRecord("_service._tcp.foo.test", Ttl.fromPositive(86400.seconds), 65533, 40, 65535, "a-double.foo.test") ) diff --git a/akka-actor-tests/src/test/scala/akka/io/dns/DockerBindDnsService.scala b/akka-actor-tests/src/test/scala/akka/io/dns/DockerBindDnsService.scala index d252da87eb..321c102a48 100644 --- a/akka-actor-tests/src/test/scala/akka/io/dns/DockerBindDnsService.scala +++ b/akka-actor-tests/src/test/scala/akka/io/dns/DockerBindDnsService.scala @@ -15,7 +15,7 @@ import scala.concurrent.duration._ import scala.util.Try import scala.util.control.NonFatal -trait DockerBindDnsService extends Eventually { self: AkkaSpec ⇒ +trait DockerBindDnsService extends Eventually { self: AkkaSpec => val client = DefaultDockerClient.fromEnv().build() val hostPort: Int @@ -33,7 +33,7 @@ trait DockerBindDnsService extends Eventually { self: AkkaSpec ⇒ try { client.pull(image) } catch { - case NonFatal(_) ⇒ + case NonFatal(_) => log.warning(s"Failed to pull docker image [$image], is docker running?") return } @@ -56,7 +56,7 @@ trait DockerBindDnsService extends Eventually { self: AkkaSpec ⇒ val containerName = "akka-test-dns-" + getClass.getCanonicalName client.listContainers(ListContainersParam.allContainers()).asScala - .find(_.names().asScala.exists(_.contains(containerName))).foreach(c ⇒ { + .find(_.names().asScala.exists(_.contains(containerName))).foreach(c => { if ("running" == c.state()) { client.killContainer(c.id) } diff --git a/akka-actor-tests/src/test/scala/akka/io/dns/internal/AsyncDnsResolverSpec.scala b/akka-actor-tests/src/test/scala/akka/io/dns/internal/AsyncDnsResolverSpec.scala index 8b8744e64a..97d49f9b15 100644 --- a/akka-actor-tests/src/test/scala/akka/io/dns/internal/AsyncDnsResolverSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/dns/internal/AsyncDnsResolverSpec.scala @@ -17,7 +17,7 @@ import akka.testkit.{ AkkaSpec, TestProbe } import com.typesafe.config.ConfigFactory import akka.testkit.WithLogCapturing -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } import scala.concurrent.duration._ class AsyncDnsResolverSpec extends AkkaSpec( @@ -77,7 +77,7 @@ class AsyncDnsResolverSpec extends AkkaSpec( "fails if all dns clients timeout" in new Setup { r ! Resolve("cats.com", Ip(ipv4 = true, ipv6 = false)) senderProbe.expectMsgPF(remainingOrDefault) { - case Failure(ResolveFailedException(_)) ⇒ + case Failure(ResolveFailedException(_)) => } } @@ -88,7 +88,7 @@ class AsyncDnsResolverSpec extends AkkaSpec( dnsClient2.expectMsg(Question4(2, "cats.com")) dnsClient2.reply(Failure(new RuntimeException("Yet another fail"))) senderProbe.expectMsgPF(remainingOrDefault) { - case Failure(ResolveFailedException(_)) ⇒ + case Failure(ResolveFailedException(_)) => } } @@ -105,7 +105,7 @@ class AsyncDnsResolverSpec extends AkkaSpec( r ! Resolve(name) dnsClient1.expectNoMessage(50.millis) val answer = senderProbe.expectMsgType[Resolved] - answer.records.collect { case r: ARecord ⇒ r }.toSet shouldEqual Set( + answer.records.collect { case r: ARecord => r }.toSet shouldEqual Set( ARecord("127.0.0.1", Ttl.effectivelyForever, InetAddress.getByName("127.0.0.1")) ) } @@ -115,7 +115,7 @@ class AsyncDnsResolverSpec extends AkkaSpec( r ! Resolve(name) dnsClient1.expectNoMessage(50.millis) val answer = senderProbe.expectMsgType[Resolved] - val Seq(AAAARecord("1:2:3:0:0:0:0:0", Ttl.effectivelyForever, _)) = answer.records.collect { case r: AAAARecord ⇒ r } + val Seq(AAAARecord("1:2:3:0:0:0:0:0", Ttl.effectivelyForever, _)) = answer.records.collect { case r: AAAARecord => r } } "return additional records for SRV requests" in new Setup { @@ -141,7 +141,7 @@ class AsyncDnsResolverSpec extends AkkaSpec( search-domains = [] ndots = 1 """)) - system.actorOf(Props(new AsyncDnsResolver(settings, new AsyncDnsCache(), (_, _) ⇒ { + system.actorOf(Props(new AsyncDnsResolver(settings, new AsyncDnsCache(), (_, _) => { clients }))) } diff --git a/akka-actor-tests/src/test/scala/akka/pattern/AskSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/AskSpec.scala index 1eaf6764b4..8d4731e707 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/AskSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/AskSpec.scala @@ -19,7 +19,7 @@ class AskSpec extends AkkaSpec { "The “ask” pattern" must { "send request to actor and wrap the answer in Future" in { implicit val timeout = Timeout(5.seconds) - val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } })) + val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } })) val f = echo ? "ping" f.futureValue should ===("ping") } @@ -30,8 +30,8 @@ class AskSpec extends AkkaSpec { val f = dead.ask(42)(1 second) f.isCompleted should ===(true) f.value.get match { - case Failure(_: AskTimeoutException) ⇒ - case v ⇒ fail(v + " was not Failure(AskTimeoutException)") + case Failure(_: AskTimeoutException) => + case v => fail(v + " was not Failure(AskTimeoutException)") } } @@ -41,8 +41,8 @@ class AskSpec extends AkkaSpec { val f = empty ? 3.14 f.isCompleted should ===(true) f.value.get match { - case Failure(_: AskTimeoutException) ⇒ - case v ⇒ fail(v + " was not Failure(AskTimeoutException)") + case Failure(_: AskTimeoutException) => + case v => fail(v + " was not Failure(AskTimeoutException)") } } @@ -58,7 +58,7 @@ class AskSpec extends AkkaSpec { "return broken promises on 0 timeout" in { implicit val timeout = Timeout(0 seconds) - val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } })) + val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } })) val f = echo ? "foo" val expectedMsg = s"Timeout length must be positive, question not sent to [$echo]. Message of type [java.lang.String]." intercept[IllegalArgumentException] { @@ -68,7 +68,7 @@ class AskSpec extends AkkaSpec { "return broken promises on < 0 timeout" in { implicit val timeout = Timeout(-1000 seconds) - val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } })) + val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } })) val f = echo ? "foo" val expectedMsg = s"Timeout length must be positive, question not sent to [$echo]. Message of type [java.lang.String]." intercept[IllegalArgumentException] { @@ -113,7 +113,7 @@ class AskSpec extends AkkaSpec { "work for ActorSelection" in { implicit val timeout = Timeout(5 seconds) import system.dispatcher - val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ sender() ! x } }), "select-echo") + val echo = system.actorOf(Props(new Actor { def receive = { case x => sender() ! x } }), "select-echo") val identityFuture = (system.actorSelection("/user/select-echo") ? Identify(None)) .mapTo[ActorIdentity].map(_.ref.get) @@ -125,7 +125,7 @@ class AskSpec extends AkkaSpec { val deadListener = TestProbe() system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter]) - val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ context.actorSelection(sender().path) ! x } }), "select-echo2") + val echo = system.actorOf(Props(new Actor { def receive = { case x => context.actorSelection(sender().path) ! x } }), "select-echo2") val f = echo ? "hi" Await.result(f, 1 seconds) should ===("hi") @@ -138,7 +138,7 @@ class AskSpec extends AkkaSpec { val deadListener = TestProbe() system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter]) - val echo = system.actorOf(Props(new Actor { def receive = { case x ⇒ context.actorSelection("/temp/*") ! x } }), "select-echo3") + val echo = system.actorOf(Props(new Actor { def receive = { case x => context.actorSelection("/temp/*") ! x } }), "select-echo3") val f = echo ? "hi" intercept[AskTimeoutException] { Await.result(f, 1 seconds) @@ -154,7 +154,7 @@ class AskSpec extends AkkaSpec { val echo = system.actorOf(Props(new Actor { def receive = { - case x ⇒ + case x => val name = sender.path.name val parent = sender.path.parent context.actorSelection(parent / ".." / "temp" / name) ! x @@ -175,7 +175,7 @@ class AskSpec extends AkkaSpec { val echo = system.actorOf(Props(new Actor { def receive = { - case x ⇒ + case x => val name = sender.path.name val parent = sender.path.parent context.actorSelection(parent / "missing") ! x @@ -195,7 +195,7 @@ class AskSpec extends AkkaSpec { val echo = system.actorOf(Props(new Actor { def receive = { - case x ⇒ + case x => context.actorSelection(sender().path / "missing") ! x } }), "select-echo6") @@ -212,7 +212,7 @@ class AskSpec extends AkkaSpec { val act = system.actorOf(Props(new Actor { def receive = { - case msg ⇒ p.ref ! sender() → msg + case msg => p.ref ! sender() -> msg } })) diff --git a/akka-actor-tests/src/test/scala/akka/pattern/BackoffOnRestartSupervisorSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/BackoffOnRestartSupervisorSpec.scala index 027b638378..0ca342998d 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/BackoffOnRestartSupervisorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/BackoffOnRestartSupervisorSpec.scala @@ -28,11 +28,11 @@ class TestActor(probe: ActorRef) extends Actor { probe ! "STARTED" def receive = { - case "DIE" ⇒ context.stop(self) - case "THROW" ⇒ throw new TestActor.NormalException - case "THROW_STOPPING_EXCEPTION" ⇒ throw new TestActor.StoppingException - case ("TO_PARENT", msg) ⇒ context.parent ! msg - case other ⇒ probe ! other + case "DIE" => context.stop(self) + case "THROW" => throw new TestActor.NormalException + case "THROW_STOPPING_EXCEPTION" => throw new TestActor.StoppingException + case ("TO_PARENT", msg) => context.parent ! msg + case other => probe ! other } } @@ -45,7 +45,7 @@ class TestParentActor(probe: ActorRef, supervisorProps: Props) extends Actor { val supervisor = context.actorOf(supervisorProps) def receive = { - case other ⇒ probe.forward(other) + case other => probe.forward(other) } } @@ -54,7 +54,7 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender { def supervisorProps(probeRef: ActorRef) = { val options = Backoff.onFailure(TestActor.props(probeRef), "someChildName", 200 millis, 10 seconds, 0.0, maxNrOfRetries = -1) .withSupervisorStrategy(OneForOneStrategy(maxNrOfRetries = 4, withinTimeRange = 30 seconds) { - case _: TestActor.StoppingException ⇒ SupervisorStrategy.Stop + case _: TestActor.StoppingException => SupervisorStrategy.Stop }) BackoffSupervisor.props(options) } @@ -125,10 +125,10 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender { class SlowlyFailingActor(latch: CountDownLatch) extends Actor { def receive = { - case "THROW" ⇒ + case "THROW" => sender ! "THROWN" throw new NormalException - case "PING" ⇒ + case "PING" => sender ! "PONG" } @@ -141,7 +141,7 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender { val postStopLatch = new CountDownLatch(1) val options = Backoff.onFailure(Props(new SlowlyFailingActor(postStopLatch)), "someChildName", 1 nanos, 1 nanos, 0.0, maxNrOfRetries = -1) .withSupervisorStrategy(OneForOneStrategy(loggingEnabled = false) { - case _: TestActor.StoppingException ⇒ SupervisorStrategy.Stop + case _: TestActor.StoppingException => SupervisorStrategy.Stop }) val supervisor = system.actorOf(BackoffSupervisor.props(options)) @@ -179,7 +179,7 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender { filterException[TestActor.TestException] { probe.watch(supervisor) // Have the child throw an exception 5 times, which is more than the max restarts allowed. - for (i ← 1 to 5) { + for (i <- 1 to 5) { supervisor ! "THROW" if (i < 5) { // Since we should've died on this throw, don't expect to be started. @@ -199,14 +199,14 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender { // that is acceptable. val options = Backoff.onFailure(TestActor.props(probe.ref), "someChildName", 300 millis, 10 seconds, 0.0, maxNrOfRetries = -1) .withSupervisorStrategy(OneForOneStrategy(withinTimeRange = 1 seconds, maxNrOfRetries = 3) { - case _: TestActor.StoppingException ⇒ SupervisorStrategy.Stop + case _: TestActor.StoppingException => SupervisorStrategy.Stop }) val supervisor = system.actorOf(BackoffSupervisor.props(options)) probe.expectMsg("STARTED") filterException[TestActor.TestException] { probe.watch(supervisor) // Throw three times rapidly - for (_ ← 1 to 3) { + for (_ <- 1 to 3) { supervisor ! "THROW" probe.expectMsg("STARTED") } diff --git a/akka-actor-tests/src/test/scala/akka/pattern/BackoffSupervisorSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/BackoffSupervisorSpec.scala index 30316b2c26..6947cec26c 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/BackoffSupervisorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/BackoffSupervisorSpec.scala @@ -23,8 +23,8 @@ object BackoffSupervisorSpec { class Child(probe: ActorRef) extends Actor { def receive = { - case "boom" ⇒ throw new TestException - case msg ⇒ probe ! msg + case "boom" => throw new TestException + case msg => probe ! msg } } @@ -35,8 +35,8 @@ object BackoffSupervisorSpec { class ManualChild(probe: ActorRef) extends Actor { def receive = { - case "boom" ⇒ throw new TestException - case msg ⇒ + case "boom" => throw new TestException + case msg => probe ! msg context.parent ! BackoffSupervisor.Reset } @@ -89,10 +89,10 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender with Eventually } filterException[TestException] { val stoppingStrategy = OneForOneStrategy() { - case _: TestException ⇒ SupervisorStrategy.Stop + case _: TestException => SupervisorStrategy.Stop } val restartingStrategy = OneForOneStrategy() { - case _: TestException ⇒ SupervisorStrategy.Restart + case _: TestException => SupervisorStrategy.Restart } assertCustomStrategy( @@ -159,10 +159,10 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender with Eventually } val stoppingStrategy = OneForOneStrategy() { - case _: TestException ⇒ SupervisorStrategy.Stop + case _: TestException => SupervisorStrategy.Stop } val restartingStrategy = OneForOneStrategy() { - case _: TestException ⇒ SupervisorStrategy.Restart + case _: TestException => SupervisorStrategy.Restart } assertManualReset( @@ -237,7 +237,7 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender with Eventually minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, - expectedResult: FiniteDuration) ⇒ + expectedResult: FiniteDuration) => val calculatedValue = BackoffSupervisor.calculateDelay(restartCount, minBackoff, maxBackoff, randomFactor) assert(calculatedValue === expectedResult) diff --git a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerMTSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerMTSpec.scala index 63aafa15fb..92bebbaf9e 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerMTSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerMTSpec.scala @@ -22,24 +22,24 @@ class CircuitBreakerMTSpec extends AkkaSpec { // returns true if the breaker is open def failingCall(): Boolean = Await.result(breaker.withCircuitBreaker(Future(throw new RuntimeException("FAIL"))) recover { - case _: CircuitBreakerOpenException ⇒ true - case _ ⇒ false + case _: CircuitBreakerOpenException => true + case _ => false }, remainingOrDefault) // fire some failing calls - 1 to (maxFailures + 1) foreach { _ ⇒ failingCall() } + 1 to (maxFailures + 1) foreach { _ => failingCall() } // and then continue with failing calls until the breaker is open awaitCond(failingCall()) } def testCallsWithBreaker(): immutable.IndexedSeq[Future[String]] = { val aFewActive = new TestLatch(5) - for (_ ← 1 to numberOfTestCalls) yield breaker.withCircuitBreaker(Future { + for (_ <- 1 to numberOfTestCalls) yield breaker.withCircuitBreaker(Future { aFewActive.countDown() Await.ready(aFewActive, 5.seconds.dilated) "succeed" }) recoverWith { - case _: CircuitBreakerOpenException ⇒ + case _: CircuitBreakerOpenException => aFewActive.countDown() Future.successful("CBO") } diff --git a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerSpec.scala index 67050f6c00..f425914e7b 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerSpec.scala @@ -28,24 +28,24 @@ object CircuitBreakerSpec { val callTimeoutLatch = new TestLatch(1) val callBreakerOpenLatch = new TestLatch(1) - val callSuccessConsumerMock = mock[Long ⇒ Unit] - val callFailureConsumerMock = mock[Long ⇒ Unit] - val callTimeoutConsumerMock = mock[Long ⇒ Unit] + val callSuccessConsumerMock = mock[Long => Unit] + val callFailureConsumerMock = mock[Long => Unit] + val callTimeoutConsumerMock = mock[Long => Unit] def apply(): CircuitBreaker = instance instance .onClose(closedLatch.countDown()) .onHalfOpen(halfOpenLatch.countDown()) .onOpen(openLatch.countDown()) - .onCallSuccess(value ⇒ { + .onCallSuccess(value => { callSuccessConsumerMock(value) callSuccessLatch.countDown() }) - .onCallFailure(value ⇒ { + .onCallFailure(value => { callFailureConsumerMock(value) callFailureLatch.countDown() }) - .onCallTimeout(value ⇒ { + .onCallTimeout(value => { callTimeoutConsumerMock(value) callTimeoutLatch.countDown() }) @@ -73,9 +73,9 @@ object CircuitBreakerSpec { def nonOneFactorCb()(implicit system: ActorSystem, ec: ExecutionContext): Breaker = new Breaker(new CircuitBreaker(system.scheduler, 1, 2000.millis.dilated, 1000.millis.dilated, 1.day.dilated, 5)) - val evenNumberIsFailure: Try[Int] ⇒ Boolean = { - case Success(i) ⇒ i % 2 == 0 - case _ ⇒ true + val evenNumberIsFailure: Try[Int] => Boolean = { + case Success(i) => i % 2 == 0 + case _ => true } } @@ -171,7 +171,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } checkLatch(breaker.halfOpenLatch) - val allReturnIsSuccess: Try[String] ⇒ Boolean = _ ⇒ false + val allReturnIsSuccess: Try[String] => Boolean = _ => false intercept[TestException] { breaker().withSyncCircuitBreaker(throwException, allReturnIsSuccess) } checkLatch(breaker.closedLatch) @@ -343,9 +343,9 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar breaker().currentFailureCount should ===(1) val harmlessException = new TestException - val harmlessExceptionAsSuccess: Try[String] ⇒ Boolean = { - case Success(_) ⇒ false - case Failure(ex) ⇒ ex != harmlessException + val harmlessExceptionAsSuccess: Try[String] => Boolean = { + case Success(_) => false + case Failure(ex) => ex != harmlessException } intercept[TestException] { @@ -517,7 +517,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar val breaker = CircuitBreakerSpec.shortResetTimeoutCb() breaker().withCircuitBreaker(Future(throwException)) checkLatch(breaker.halfOpenLatch) - val allReturnIsSuccess: Try[String] ⇒ Boolean = _ ⇒ false + val allReturnIsSuccess: Try[String] => Boolean = _ => false Await.ready(breaker().withCircuitBreaker(Future(throwException), allReturnIsSuccess), awaitTimeout) checkLatch(breaker.closedLatch) } @@ -658,7 +658,7 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar "reset failure count after success" in { val breaker = CircuitBreakerSpec.multiFailureCb() breaker().withCircuitBreaker(Future(sayHi)) - for (_ ← 1 to 4) breaker().withCircuitBreaker(Future(throwException)) + for (_ <- 1 to 4) breaker().withCircuitBreaker(Future(throwException)) awaitCond(breaker().currentFailureCount == 4, awaitTimeout) breaker().withCircuitBreaker(Future(sayHi)) awaitCond(breaker().currentFailureCount == 0, awaitTimeout) @@ -668,13 +668,13 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar "exception is defined as Success" in { val breaker: CircuitBreakerSpec.Breaker = CircuitBreakerSpec.multiFailureCb() - for (_ ← 1 to 4) breaker().withCircuitBreaker(Future(throwException)) + for (_ <- 1 to 4) breaker().withCircuitBreaker(Future(throwException)) awaitCond(breaker().currentFailureCount == 4, awaitTimeout, message = s"Current failure count: ${breaker().currentFailureCount}") val harmlessException = new TestException - val harmlessExceptionAsSuccess: Try[String] ⇒ Boolean = { - case Success(_) ⇒ false - case Failure(ex) ⇒ ex != harmlessException + val harmlessExceptionAsSuccess: Try[String] => Boolean = { + case Success(_) => false + case Failure(ex) => ex != harmlessException } breaker().withCircuitBreaker(Future(throw harmlessException), harmlessExceptionAsSuccess) diff --git a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerStressSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerStressSpec.scala index 29cc2aaf2a..e23e55a01c 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerStressSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/CircuitBreakerStressSpec.scala @@ -39,19 +39,19 @@ object CircuitBreakerStressSpec { } override def receive = { - case JobDone ⇒ + case JobDone => doneCount += 1 breaker.withCircuitBreaker(job).pipeTo(self) - case Failure(_: CircuitBreakerOpenException) ⇒ + case Failure(_: CircuitBreakerOpenException) => circCount += 1 breaker.withCircuitBreaker(job).pipeTo(self) - case Failure(_: TimeoutException) ⇒ + case Failure(_: TimeoutException) => timeoutCount += 1 breaker.withCircuitBreaker(job).pipeTo(self) - case Failure(_) ⇒ + case Failure(_) => failCount += 1 breaker.withCircuitBreaker(job).pipeTo(self) - case GetResult ⇒ + case GetResult => sender() ! Result(doneCount, timeoutCount, failCount, circCount) } } @@ -68,12 +68,12 @@ class CircuitBreakerStressSpec extends AkkaSpec with ImplicitSender { val stressActors = Vector.fill(3) { system.actorOf(Props(classOf[StressActor], breaker)) } - for (_ ← 0 to 1000; a ← stressActors) { + for (_ <- 0 to 1000; a <- stressActors) { a ! JobDone } // let them work for a while Thread.sleep(3000) - stressActors.foreach { a ⇒ + stressActors.foreach { a => a ! GetResult val result = expectMsgType[Result] result.failCount should be(0) diff --git a/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala index b3138854e5..595f2da8fb 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/PatternSpec.scala @@ -15,7 +15,7 @@ object PatternSpec { final case class Work(duration: Duration) class TargetActor extends Actor { def receive = { - case (testLatch: TestLatch, duration: FiniteDuration) ⇒ + case (testLatch: TestLatch, duration: FiniteDuration) => Await.ready(testLatch, duration) } } diff --git a/akka-actor-tests/src/test/scala/akka/pattern/PromiseRefSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/PromiseRefSpec.scala index 3c48f0b6e5..2f49fc80dc 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/PromiseRefSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/PromiseRefSpec.scala @@ -27,7 +27,7 @@ class PromiseRefSpec extends AkkaSpec with ImplicitSender { val promiseRef = PromiseRef(5.seconds) val target = system.actorOf(Props(new Actor { - def receive = { case Request(replyTo) ⇒ replyTo ! Response } + def receive = { case Request(replyTo) => replyTo ! Response } })) target ! Request(promiseRef.ref) @@ -57,13 +57,13 @@ class PromiseRefSpec extends AkkaSpec with ImplicitSender { val promise = Promise[Int]() val alice = system.actorOf(Props(new Actor { - def receive = { case Response ⇒ promise.success(42) } + def receive = { case Response => promise.success(42) } })) val promiseRef = PromiseRef.wrap(alice, promise) val bob = system.actorOf(Props(new Actor { - def receive = { case Request(replyTo) ⇒ replyTo ! Response } + def receive = { case Request(replyTo) => replyTo ! Response } })) bob ! Request(promiseRef.ref) diff --git a/akka-actor-tests/src/test/scala/akka/pattern/RetrySpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/RetrySpec.scala index 9e541f5427..d726a90f9c 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/RetrySpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/RetrySpec.scala @@ -19,7 +19,7 @@ class RetrySpec extends AkkaSpec with RetrySupport { "pattern.retry" must { "run a successful Future immediately" in { val retried = retry( - () ⇒ Future.successful(5), + () => Future.successful(5), 5, 1 second ) @@ -32,7 +32,7 @@ class RetrySpec extends AkkaSpec with RetrySupport { "run a successful Future only once" in { @volatile var counter = 0 val retried = retry( - () ⇒ Future.successful({ + () => Future.successful({ counter += 1 counter }), @@ -47,7 +47,7 @@ class RetrySpec extends AkkaSpec with RetrySupport { "eventually return a failure for a Future that will never succeed" in { val retried = retry( - () ⇒ Future.failed(new IllegalStateException("Mexico")), + () => Future.failed(new IllegalStateException("Mexico")), 5, 100 milliseconds ) @@ -68,7 +68,7 @@ class RetrySpec extends AkkaSpec with RetrySupport { } val retried = retry( - () ⇒ attempt, + () => attempt, 10, 100 milliseconds ) @@ -89,7 +89,7 @@ class RetrySpec extends AkkaSpec with RetrySupport { } val retried = retry( - () ⇒ attempt, + () => attempt, 5, 100 milliseconds ) diff --git a/akka-actor-tests/src/test/scala/akka/pattern/extended/ExplicitAskSpec.scala b/akka-actor-tests/src/test/scala/akka/pattern/extended/ExplicitAskSpec.scala index 3a91cb0c6e..7dcef6485b 100644 --- a/akka-actor-tests/src/test/scala/akka/pattern/extended/ExplicitAskSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/pattern/extended/ExplicitAskSpec.scala @@ -23,11 +23,11 @@ class ExplicitAskSpec extends AkkaSpec { val target = system.actorOf(Props(new Actor { def receive = { - case Request(respondTo) ⇒ respondTo ! Response(self) + case Request(respondTo) => respondTo ! Response(self) } })) - val f = target ? (respondTo ⇒ Request(respondTo)) + val f = target ? (respondTo => Request(respondTo)) f.futureValue should ===(Response(target)) } @@ -36,12 +36,12 @@ class ExplicitAskSpec extends AkkaSpec { val target = system.actorOf(Props(new Actor { def receive = { - case Request(respondTo) ⇒ respondTo ! Response(self) + case Request(respondTo) => respondTo ! Response(self) } }), "select-echo") val selection = system.actorSelection("/user/select-echo") - val f = selection ? (respondTo ⇒ Request(respondTo)) + val f = selection ? (respondTo => Request(respondTo)) f.futureValue should ===(Response(target)) } } diff --git a/akka-actor-tests/src/test/scala/akka/routing/BalancingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/BalancingSpec.scala index f0984f5feb..83b11d8def 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/BalancingSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/BalancingSpec.scala @@ -22,7 +22,7 @@ object BalancingSpec { override def preStart(): Unit = latch.countDown() def receive = { - case msg: Int ⇒ + case msg: Int => if (id != 1) Await.ready(latch, 1.minute) else if (msg <= 10) @@ -36,7 +36,7 @@ object BalancingSpec { Props(classOf[Worker], TestLatch(0)(context.system)))) def receive = { - case msg ⇒ pool.forward(msg) + case msg => pool.forward(msg) } } } @@ -75,7 +75,7 @@ class BalancingSpec extends AkkaSpec( latch.reset() val iterationCount = 100 - for (i ← 1 to iterationCount) { + for (i <- 1 to iterationCount) { pool ! i } diff --git a/akka-actor-tests/src/test/scala/akka/routing/BroadcastSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/BroadcastSpec.scala index ec84339577..3873c99d83 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/BroadcastSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/BroadcastSpec.scala @@ -12,7 +12,7 @@ import akka.pattern.ask object BroadcastSpec { class TestActor extends Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } } } @@ -26,16 +26,16 @@ class BroadcastSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val counter1 = new AtomicInteger val actor1 = system.actorOf(Props(new Actor { def receive = { - case "end" ⇒ doneLatch.countDown() - case msg: Int ⇒ counter1.addAndGet(msg) + case "end" => doneLatch.countDown() + case msg: Int => counter1.addAndGet(msg) } })) val counter2 = new AtomicInteger val actor2 = system.actorOf(Props(new Actor { def receive = { - case "end" ⇒ doneLatch.countDown() - case msg: Int ⇒ counter2.addAndGet(msg) + case "end" => doneLatch.countDown() + case msg: Int => counter2.addAndGet(msg) } })) @@ -56,8 +56,8 @@ class BroadcastSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val counter1 = new AtomicInteger val actor1 = system.actorOf(Props(new Actor { def receive = { - case "end" ⇒ doneLatch.countDown() - case msg: Int ⇒ + case "end" => doneLatch.countDown() + case msg: Int => counter1.addAndGet(msg) sender() ! "ack" } @@ -66,8 +66,8 @@ class BroadcastSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val counter2 = new AtomicInteger val actor2 = system.actorOf(Props(new Actor { def receive = { - case "end" ⇒ doneLatch.countDown() - case msg: Int ⇒ counter2.addAndGet(msg) + case "end" => doneLatch.countDown() + case msg: Int => counter2.addAndGet(msg) } })) diff --git a/akka-actor-tests/src/test/scala/akka/routing/ConfiguredLocalRoutingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/ConfiguredLocalRoutingSpec.scala index f0fe4655bb..616df89c66 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/ConfiguredLocalRoutingSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/ConfiguredLocalRoutingSpec.scala @@ -82,18 +82,18 @@ object ConfiguredLocalRoutingSpec { class EchoProps extends Actor { def receive = { - case "get" ⇒ sender() ! context.props + case "get" => sender() ! context.props } } class SendRefAtStartup(testActor: ActorRef) extends Actor { testActor ! self - def receive = { case _ ⇒ } + def receive = { case _ => } } class Parent extends Actor { def receive = { - case (p: Props, name: String) ⇒ + case (p: Props, name: String) => sender() ! context.actorOf(p, name) } } @@ -104,15 +104,15 @@ class ConfiguredLocalRoutingSpec extends AkkaSpec(ConfiguredLocalRoutingSpec.con import ConfiguredLocalRoutingSpec._ def routerConfig(ref: ActorRef): akka.routing.RouterConfig = ref match { - case r: RoutedActorRef ⇒ + case r: RoutedActorRef => r.underlying match { - case c: RoutedActorCell ⇒ c.routerConfig - case _: UnstartedCell ⇒ awaitCond(r.isStarted, 1 second, 10 millis); routerConfig(ref) + case c: RoutedActorCell => c.routerConfig + case _: UnstartedCell => awaitCond(r.isStarted, 1 second, 10 millis); routerConfig(ref) } } def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = { - for (i ← 1 to n) yield { + for (i <- 1 to n) yield { val msg = i.toString router.tell(msg, probe.ref) probe.expectMsg(msg) @@ -162,8 +162,8 @@ class ConfiguredLocalRoutingSpec extends AkkaSpec(ConfiguredLocalRoutingSpec.con "not get confused when trying to wildcard-configure children" in { system.actorOf(FromConfig.props(routeeProps = Props(classOf[SendRefAtStartup], testActor)), "weird") - val recv = Set() ++ (for (_ ← 1 to 3) yield expectMsgType[ActorRef]) - val expc = Set('a', 'b', 'c') map (i ⇒ system.actorFor("/user/weird/$" + i)) + val recv = Set() ++ (for (_ <- 1 to 3) yield expectMsgType[ActorRef]) + val expc = Set('a', 'b', 'c') map (i => system.actorFor("/user/weird/$" + i)) recv should ===(expc) expectNoMessage(1 second) } diff --git a/akka-actor-tests/src/test/scala/akka/routing/ConsistentHashingRouterSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/ConsistentHashingRouterSpec.scala index 73aaadaee4..f6ea1d585d 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/ConsistentHashingRouterSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/ConsistentHashingRouterSpec.scala @@ -33,8 +33,8 @@ object ConsistentHashingRouterSpec { class Echo extends Actor { def receive = { - case x: ConsistentHashableEnvelope ⇒ sender() ! s"Unexpected envelope: $x" - case _ ⇒ sender() ! self + case x: ConsistentHashableEnvelope => sender() ! s"Unexpected envelope: $x" + case _ => sender() ! self } } @@ -78,7 +78,7 @@ class ConsistentHashingRouterSpec extends AkkaSpec(ConsistentHashingRouterSpec.c "select destination with defined hashMapping" in { def hashMapping: ConsistentHashMapping = { - case Msg2(key, _) ⇒ key + case Msg2(key, _) => key } val router2 = system.actorOf(ConsistentHashingPool(nrOfInstances = 1, hashMapping = hashMapping). props(Props[Echo]), "router2") diff --git a/akka-actor-tests/src/test/scala/akka/routing/MetricsBasedResizerSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/MetricsBasedResizerSpec.scala index 38212a5167..e26d848f45 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/MetricsBasedResizerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/MetricsBasedResizerSpec.scala @@ -30,7 +30,7 @@ object MetricsBasedResizerSpec { class TestLatchingActor(implicit timeout: Timeout) extends Actor { def receive = { - case Latches(first, second) ⇒ + case Latches(first, second) => first.countDown() Try(Await.ready(second, timeout.duration)) } @@ -39,7 +39,7 @@ object MetricsBasedResizerSpec { def routee(implicit system: ActorSystem, timeout: Timeout): ActorRefRoutee = ActorRefRoutee(system.actorOf(Props(new TestLatchingActor))) - def routees(num: Int = 10)(implicit system: ActorSystem, timeout: Timeout) = (1 to num).map(_ ⇒ routee).toVector + def routees(num: Int = 10)(implicit system: ActorSystem, timeout: Timeout) = (1 to num).map(_ => routee).toVector case class TestRouter(routees: Vector[ActorRefRoutee])(implicit system: ActorSystem, timeout: Timeout) { @@ -61,7 +61,7 @@ object MetricsBasedResizerSpec { def close(): Unit = msgs.foreach(_.open()) def sendToAll(await: Boolean): Seq[Latches] = { - val sentMessages = routees.indices.map(i ⇒ mockSend(await, routeeIdx = i)) + val sentMessages = routees.indices.map(i => mockSend(await, routeeIdx = i)) sentMessages } @@ -245,7 +245,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT Thread.sleep(300) // wait for routees to update their mail boxes - msgs2.foreach(l ⇒ Await.ready(l.first, timeout.duration)) + msgs2.foreach(l => Await.ready(l.first, timeout.duration)) resizer.reportMessageCount(router.routees, router.msgs.size) @@ -262,7 +262,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT val resizer = DefaultOptimalSizeExploringResizer( weightOfLatestMetric = 0.5) - resizer.performanceLog = Map(2 → oldSpeed.milliseconds) + resizer.performanceLog = Map(2 -> oldSpeed.milliseconds) val router = TestRouter(routees(2)) val msgs1 = router.sendToAll(await = true) @@ -277,7 +277,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT Thread.sleep(300) // wait for routees to update their mail boxes - msgs2.foreach(l ⇒ Await.ready(l.first, timeout.duration)) + msgs2.foreach(l => Await.ready(l.first, timeout.duration)) resizer.reportMessageCount(router.routees, router.msgs.size) @@ -323,10 +323,10 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT val resizer = DefaultOptimalSizeExploringResizer( exploreStepSize = 0.3, explorationProbability = 1) - resizer.performanceLog = Map(11 → 1.milli, 13 → 1.millis, 12 → 3.millis) + resizer.performanceLog = Map(11 -> 1.milli, 13 -> 1.millis, 12 -> 3.millis) - val exploreSamples = (1 to 100).map(_ ⇒ resizer.resize(routees(10))) - exploreSamples.forall(change ⇒ Math.abs(change) >= 1 && Math.abs(change) <= (10 * 0.3)) should be(true) + val exploreSamples = (1 to 100).map(_ => resizer.resize(routees(10))) + exploreSamples.forall(change => Math.abs(change) >= 1 && Math.abs(change) <= (10 * 0.3)) should be(true) } } @@ -334,7 +334,7 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT "MetricsBasedResizer optimize" must { "optimize towards the fastest pool size" in { val resizer = DefaultOptimalSizeExploringResizer(explorationProbability = 0) - resizer.performanceLog = Map(7 → 5.millis, 10 → 3.millis, 11 → 2.millis, 12 → 4.millis) + resizer.performanceLog = Map(7 -> 5.millis, 10 -> 3.millis, 11 -> 2.millis, 12 -> 4.millis) resizer.resize(routees(10)) should be(1) resizer.resize(routees(12)) should be(-1) resizer.resize(routees(7)) should be(2) @@ -343,12 +343,12 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT "ignore further away sample data when optmizing" in { val resizer = DefaultOptimalSizeExploringResizer(explorationProbability = 0, numOfAdjacentSizesToConsiderDuringOptimization = 4) resizer.performanceLog = Map( - 7 → 5.millis, - 8 → 2.millis, - 10 → 3.millis, - 11 → 4.millis, - 12 → 3.millis, - 13 → 1.millis) + 7 -> 5.millis, + 8 -> 2.millis, + 10 -> 3.millis, + 11 -> 4.millis, + 12 -> 3.millis, + 13 -> 1.millis) resizer.resize(routees(10)) should be(-1) } diff --git a/akka-actor-tests/src/test/scala/akka/routing/RandomSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RandomSpec.scala index 0df1ba38f1..2dab6eaa16 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/RandomSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/RandomSpec.scala @@ -21,7 +21,7 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val actor = system.actorOf(RandomPool(7).props(Props(new Actor { def receive = { - case "hello" ⇒ sender() ! "world" + case "hello" => sender() ! "world" } override def postStop(): Unit = { @@ -36,7 +36,7 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { actor ! "hello" within(2 seconds) { - for (_ ← 1 to 5) expectMsg("world") + for (_ <- 1 to 5) expectMsg("world") } system.stop(actor) @@ -50,23 +50,23 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val counter = new AtomicInteger var replies = Map.empty[Int, Int] - for (i ← 0 until connectionCount) { - replies = replies + (i → 0) + for (i <- 0 until connectionCount) { + replies = replies + (i -> 0) } val actor = system.actorOf(RandomPool(connectionCount).props(routeeProps = Props(new Actor { lazy val id = counter.getAndIncrement() def receive = { - case "hit" ⇒ sender() ! id - case "end" ⇒ doneLatch.countDown() + case "hit" => sender() ! id + case "end" => doneLatch.countDown() } })), name = "random") - for (_ ← 0 until iterationCount) { - for (_ ← 0 until connectionCount) { + for (_ <- 0 until iterationCount) { + for (_ <- 0 until connectionCount) { val id = Await.result((actor ? "hit").mapTo[Int], timeout.duration) - replies = replies + (id → (replies(id) + 1)) + replies = replies + (id -> (replies(id) + 1)) } } @@ -85,7 +85,7 @@ class RandomSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val actor = system.actorOf(RandomPool(6).props(routeeProps = Props(new Actor { def receive = { - case "hello" ⇒ helloLatch.countDown() + case "hello" => helloLatch.countDown() } override def postStop(): Unit = { diff --git a/akka-actor-tests/src/test/scala/akka/routing/ResizerSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/ResizerSpec.scala index 027dd62c30..846099359b 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/ResizerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/ResizerSpec.scala @@ -31,7 +31,7 @@ object ResizerSpec { class TestActor extends Actor { def receive = { - case latch: TestLatch ⇒ latch.countDown() + case latch: TestLatch => latch.countDown() } } @@ -185,9 +185,9 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props( Props(new Actor { def receive = { - case d: FiniteDuration ⇒ + case d: FiniteDuration => Thread.sleep(d.dilated.toMillis); sender() ! "done" - case "echo" ⇒ sender() ! "reply" + case "echo" => sender() ! "reply" } }))) @@ -198,13 +198,13 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with routeeSize(router) should ===(resizer.lowerBound) def loop(loops: Int, d: FiniteDuration) = { - for (_ ← 0 until loops) { + for (_ <- 0 until loops) { router ! d // sending in too quickly will result in skipped resize due to many resizeInProgress conflicts Thread.sleep(20.millis.dilated.toMillis) } within((d * loops / resizer.lowerBound) + 2.seconds.dilated) { - for (_ ← 0 until loops) expectMsg("done") + for (_ <- 0 until loops) expectMsg("done") } } @@ -230,13 +230,13 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props( Props(new Actor { def receive = { - case n: Int if n <= 0 ⇒ // done - case n: Int ⇒ Thread.sleep((n millis).dilated.toMillis) + case n: Int if n <= 0 => // done + case n: Int => Thread.sleep((n millis).dilated.toMillis) } }))) // put some pressure on the router - for (_ ← 0 until 15) { + for (_ <- 0 until 15) { router ! 150 Thread.sleep((20 millis).dilated.toMillis) } diff --git a/akka-actor-tests/src/test/scala/akka/routing/RoundRobinSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RoundRobinSpec.scala index b3085ca50a..e1188a7e0b 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/RoundRobinSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/RoundRobinSpec.scala @@ -28,7 +28,7 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val actor = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor { def receive = { - case "hello" ⇒ helloLatch.countDown() + case "hello" => helloLatch.countDown() } override def postStop(): Unit = { @@ -58,14 +58,14 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val actor = system.actorOf(RoundRobinPool(connectionCount).props(routeeProps = Props(new Actor { lazy val id = counter.getAndIncrement() def receive = { - case "hit" ⇒ sender() ! id - case "end" ⇒ doneLatch.countDown() + case "hit" => sender() ! id + case "end" => doneLatch.countDown() } })), "round-robin") - for (_ ← 1 to iterationCount; _ ← 1 to connectionCount) { + for (_ <- 1 to iterationCount; _ <- 1 to connectionCount) { val id = Await.result((actor ? "hit").mapTo[Int], timeout.duration) - replies += (id → (replies(id) + 1)) + replies += (id -> (replies(id) + 1)) } counter.get should ===(connectionCount) @@ -82,7 +82,7 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val actor = system.actorOf(RoundRobinPool(5).props(routeeProps = Props(new Actor { def receive = { - case "hello" ⇒ helloLatch.countDown() + case "hello" => helloLatch.countDown() } override def postStop(): Unit = { @@ -125,11 +125,11 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { var replies: Map[String, Int] = Map.empty.withDefaultValue(0) - val paths = (1 to connectionCount) map { n ⇒ + val paths = (1 to connectionCount) map { n => val ref = system.actorOf(Props(new Actor { def receive = { - case "hit" ⇒ sender() ! self.path.name - case "end" ⇒ doneLatch.countDown() + case "hit" => sender() ! self.path.name + case "end" => doneLatch.countDown() } }), name = "target-" + n) ref.path.toStringWithoutAddress @@ -137,9 +137,9 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val actor = system.actorOf(RoundRobinGroup(paths).props(), "round-robin-group1") - for (_ ← 1 to iterationCount; _ ← 1 to connectionCount) { + for (_ <- 1 to iterationCount; _ <- 1 to connectionCount) { val id = Await.result((actor ? "hit").mapTo[String], timeout.duration) - replies += (id → (replies(id) + 1)) + replies += (id -> (replies(id) + 1)) } actor ! akka.routing.Broadcast("end") @@ -161,31 +161,31 @@ class RoundRobinSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { var router = Router(RoundRobinRoutingLogic()) def receive = { - case p: Props ⇒ + case p: Props => n += 1 val c = context.actorOf(p, name = "child-" + n) context.watch(c) router = router.addRoutee(c) - case Terminated(c) ⇒ + case Terminated(c) => router = router.removeRoutee(c) if (router.routees.isEmpty) context.stop(self) - case other ⇒ router.route(other, sender()) + case other => router.route(other, sender()) } })) val childProps = Props(new Actor { def receive = { - case "hit" ⇒ sender() ! self.path.name - case "end" ⇒ context.stop(self) + case "hit" => sender() ! self.path.name + case "end" => context.stop(self) } }) - (1 to connectionCount) foreach { _ ⇒ actor ! childProps } + (1 to connectionCount) foreach { _ => actor ! childProps } - for (_ ← 1 to iterationCount; _ ← 1 to connectionCount) { + for (_ <- 1 to iterationCount; _ <- 1 to connectionCount) { val id = Await.result((actor ? "hit").mapTo[String], timeout.duration) - replies += (id → (replies(id) + 1)) + replies += (id -> (replies(id) + 1)) } watch(actor) diff --git a/akka-actor-tests/src/test/scala/akka/routing/RouteeCreationSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RouteeCreationSpec.scala index e7b44becaf..72e7e51911 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/RouteeCreationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/RouteeCreationSpec.scala @@ -21,10 +21,10 @@ class RouteeCreationSpec extends AkkaSpec { system.actorSelection(self.path).tell(Identify(self.path), testActor) def receive = Actor.emptyBehavior }))) - for (i ← 1 to N) { + for (i <- 1 to N) { expectMsgType[ActorIdentity] match { - case ActorIdentity(_, Some(_)) ⇒ // fine - case x ⇒ fail(s"routee $i was not found $x") + case ActorIdentity(_, Some(_)) => // fine + case x => fail(s"routee $i was not found $x") } } } @@ -34,11 +34,11 @@ class RouteeCreationSpec extends AkkaSpec { system.actorOf(RoundRobinPool(N).props(Props(new Actor { context.parent ! "one" def receive = { - case "one" ⇒ testActor forward "two" + case "one" => testActor forward "two" } }))) val gotit = receiveWhile(messages = N) { - case "two" ⇒ lastSender.toString + case "two" => lastSender.toString } expectNoMsg(100.millis) if (gotit.size != N) { diff --git a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala index 9d3c7a5b26..3b7e0b8101 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala @@ -36,12 +36,12 @@ object RoutingSpec { """ class TestActor extends Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } } class Echo extends Actor { def receive = { - case _ ⇒ sender() ! self + case _ => sender() ! self } } @@ -69,7 +69,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with router ! "" router ! "" val res = receiveWhile(100 millis, messages = 2) { - case x: ActorRef ⇒ x + case x: ActorRef => x } res == Seq(c1, c1) } @@ -135,7 +135,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with //#supervision val escalator = OneForOneStrategy() { //#custom-strategy - case e ⇒ testActor ! e; SupervisorStrategy.Escalate + case e => testActor ! e; SupervisorStrategy.Escalate //#custom-strategy } val router = system.actorOf(RoundRobinPool(1, supervisorStrategy = escalator).props( @@ -158,7 +158,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with "set supplied supervisorStrategy for FromConfig" in { val escalator = OneForOneStrategy() { - case e ⇒ testActor ! e; SupervisorStrategy.Escalate + case e => testActor ! e; SupervisorStrategy.Escalate } val router = system.actorOf(FromConfig.withSupervisorStrategy(escalator).props( routeeProps = Props[TestActor]), "router1") @@ -171,12 +171,12 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with "default to all-for-one-always-escalate strategy" in { val restarter = OneForOneStrategy() { - case e ⇒ testActor ! e; SupervisorStrategy.Restart + case e => testActor ! e; SupervisorStrategy.Restart } val supervisor = system.actorOf(Props(new Supervisor(restarter))) supervisor ! RoundRobinPool(3).props(routeeProps = Props(new Actor { def receive = { - case x: String ⇒ throw new Exception(x) + case x: String => throw new Exception(x) } override def postRestart(reason: Throwable): Unit = testActor ! "restarted" })) @@ -193,9 +193,9 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with "start in-line for context.actorOf()" in { system.actorOf(Props(new Actor { def receive = { - case "start" ⇒ + case "start" => context.actorOf(RoundRobinPool(2).props(routeeProps = Props(new Actor { - def receive = { case x ⇒ sender() ! x } + def receive = { case x => sender() ! x } }))) ? "hello" pipeTo sender() } })) ! "start" @@ -209,7 +209,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with "send message to connection" in { class Actor1 extends Actor { def receive = { - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } diff --git a/akka-actor-tests/src/test/scala/akka/routing/ScatterGatherFirstCompletedSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/ScatterGatherFirstCompletedSpec.scala index e14570650f..488be74d94 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/ScatterGatherFirstCompletedSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/ScatterGatherFirstCompletedSpec.scala @@ -17,7 +17,7 @@ import akka.testkit.TestProbe object ScatterGatherFirstCompletedSpec { class TestActor extends Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } } final case class Stop(id: Option[Int] = None) @@ -25,10 +25,10 @@ object ScatterGatherFirstCompletedSpec { def newActor(id: Int, shudownLatch: Option[TestLatch] = None)(implicit system: ActorSystem) = system.actorOf(Props(new Actor { def receive = { - case Stop(None) ⇒ context.stop(self) - case Stop(Some(_id)) if (_id == id) ⇒ context.stop(self) - case _id: Int if (_id == id) ⇒ - case _ ⇒ { + case Stop(None) => context.stop(self) + case Stop(Some(_id)) if (_id == id) => context.stop(self) + case _id: Int if (_id == id) => + case _ => { Thread sleep 100 * id sender() ! id } @@ -51,16 +51,16 @@ class ScatterGatherFirstCompletedSpec extends AkkaSpec with DefaultTimeout with val counter1 = new AtomicInteger val actor1 = system.actorOf(Props(new Actor { def receive = { - case "end" ⇒ doneLatch.countDown() - case msg: Int ⇒ counter1.addAndGet(msg) + case "end" => doneLatch.countDown() + case msg: Int => counter1.addAndGet(msg) } })) val counter2 = new AtomicInteger val actor2 = system.actorOf(Props(new Actor { def receive = { - case "end" ⇒ doneLatch.countDown() - case msg: Int ⇒ counter2.addAndGet(msg) + case "end" => doneLatch.countDown() + case msg: Int => counter2.addAndGet(msg) } })) diff --git a/akka-actor-tests/src/test/scala/akka/routing/SmallestMailboxSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/SmallestMailboxSpec.scala index 4ddd8ec6eb..f072f02ef9 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/SmallestMailboxSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/SmallestMailboxSpec.scala @@ -18,15 +18,15 @@ class SmallestMailboxSpec extends AkkaSpec("akka.actor.serialize-messages = off" val usedActors = new ConcurrentHashMap[Int, String]() val router = system.actorOf(SmallestMailboxPool(3).props(routeeProps = Props(new Actor { def receive = { - case (busy: TestLatch, receivedLatch: TestLatch) ⇒ + case (busy: TestLatch, receivedLatch: TestLatch) => usedActors.put(0, self.path.toString) self ! "another in busy mailbox" receivedLatch.countDown() Await.ready(busy, TestLatch.DefaultTimeout) - case (msg: Int, receivedLatch: TestLatch) ⇒ + case (msg: Int, receivedLatch: TestLatch) => usedActors.put(msg, self.path.toString) receivedLatch.countDown() - case _: String ⇒ + case _: String => } }))) diff --git a/akka-actor-tests/src/test/scala/akka/routing/TailChoppingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/TailChoppingSpec.scala index b63d19703f..578afe2808 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/TailChoppingSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/TailChoppingSpec.scala @@ -18,9 +18,9 @@ object TailChoppingSpec { var times: Int = _ def receive = { - case "stop" ⇒ context.stop(self) - case "times" ⇒ sender() ! times - case _ ⇒ + case "stop" => context.stop(self) + case "times" => sender() ! times + case _ => times += 1 Thread sleep sleepTime.toMillis sender ! "ack" @@ -31,14 +31,14 @@ object TailChoppingSpec { class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { import TailChoppingSpec._ - def oneOfShouldEqual(what: Any, default: Any, ref: ActorRef*)(f: ActorRef ⇒ Any): Unit = { - val results = ref.map(p ⇒ f(p)) + def oneOfShouldEqual(what: Any, default: Any, ref: ActorRef*)(f: ActorRef => Any): Unit = { + val results = ref.map(p => f(p)) results.count(_ == what) should equal(1) results.count(_ == default) should equal(results.size - 1) } - def allShouldEqual(what: Any, ref: ActorRef*)(f: ActorRef ⇒ Any): Unit = { - val results = ref.map(p ⇒ f(p)) + def allShouldEqual(what: Any, ref: ActorRef*)(f: ActorRef => Any): Unit = { + val results = ref.map(p => f(p)) results.count(_ == what) should equal(results.size) } @@ -50,16 +50,16 @@ class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender val counter1 = new AtomicInteger val actor1 = system.actorOf(Props(new Actor { def receive = { - case "end" ⇒ doneLatch.countDown() - case msg: Int ⇒ counter1.addAndGet(msg) + case "end" => doneLatch.countDown() + case msg: Int => counter1.addAndGet(msg) } })) val counter2 = new AtomicInteger val actor2 = system.actorOf(Props(new Actor { def receive = { - case "end" ⇒ doneLatch.countDown() - case msg: Int ⇒ counter2.addAndGet(msg) + case "end" => doneLatch.countDown() + case msg: Int => counter2.addAndGet(msg) } })) @@ -84,7 +84,7 @@ class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender probe.send(routedActor, "") probe.expectMsg("ack") - oneOfShouldEqual(1, 1, actor1, actor2)(ref ⇒ Await.result(ref ? "times", timeout.duration)) + oneOfShouldEqual(1, 1, actor1, actor2)(ref => Await.result(ref ? "times", timeout.duration)) routedActor ! Broadcast("stop") } @@ -99,10 +99,10 @@ class TailChoppingSpec extends AkkaSpec with DefaultTimeout with ImplicitSender probe.send(routedActor, "") probe.expectMsgPF() { - case Failure(_: AskTimeoutException) ⇒ + case Failure(_: AskTimeoutException) => } - allShouldEqual(1, actor1, actor2)(ref ⇒ Await.result(ref ? "times", timeout.duration)) + allShouldEqual(1, actor1, actor2)(ref => Await.result(ref ? "times", timeout.duration)) routedActor ! Broadcast("stop") } diff --git a/akka-actor-tests/src/test/scala/akka/serialization/AsyncSerializeSpec.scala b/akka-actor-tests/src/test/scala/akka/serialization/AsyncSerializeSpec.scala index dffd1b2b07..7f482ad689 100644 --- a/akka-actor-tests/src/test/scala/akka/serialization/AsyncSerializeSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/serialization/AsyncSerializeSpec.scala @@ -42,23 +42,23 @@ object AsyncSerializeSpec { override def toBinaryAsync(o: AnyRef): Future[Array[Byte]] = { o match { - case Message1(msg) ⇒ Future.successful(msg.getBytes) - case Message2(msg) ⇒ Future.successful(msg.getBytes) + case Message1(msg) => Future.successful(msg.getBytes) + case Message2(msg) => Future.successful(msg.getBytes) } } override def fromBinaryAsync(bytes: Array[Byte], manifest: String): Future[AnyRef] = { manifest match { - case "1" ⇒ Future.successful(Message1(new String(bytes))) - case "2" ⇒ Future.successful(Message2(new String(bytes))) + case "1" => Future.successful(Message1(new String(bytes))) + case "2" => Future.successful(Message2(new String(bytes))) } } override def identifier: Int = 9000 override def manifest(o: AnyRef): String = o match { - case _: Message1 ⇒ "1" - case _: Message2 ⇒ "2" + case _: Message1 => "1" + case _: Message2 => "2" } } @@ -66,23 +66,23 @@ object AsyncSerializeSpec { override def toBinaryAsyncCS(o: AnyRef): CompletionStage[Array[Byte]] = { o match { - case Message3(msg) ⇒ CompletableFuture.completedFuture(msg.getBytes) - case Message4(msg) ⇒ CompletableFuture.completedFuture(msg.getBytes) + case Message3(msg) => CompletableFuture.completedFuture(msg.getBytes) + case Message4(msg) => CompletableFuture.completedFuture(msg.getBytes) } } override def fromBinaryAsyncCS(bytes: Array[Byte], manifest: String): CompletionStage[AnyRef] = { manifest match { - case "1" ⇒ CompletableFuture.completedFuture(Message3(new String(bytes))) - case "2" ⇒ CompletableFuture.completedFuture(Message4(new String(bytes))) + case "1" => CompletableFuture.completedFuture(Message3(new String(bytes))) + case "2" => CompletableFuture.completedFuture(Message4(new String(bytes))) } } override def identifier: Int = 9001 override def manifest(o: AnyRef): String = o match { - case _: Message3 ⇒ "1" - case _: Message4 ⇒ "2" + case _: Message3 => "1" + case _: Message4 => "2" } } diff --git a/akka-actor-tests/src/test/scala/akka/serialization/SerializationSetupSpec.scala b/akka-actor-tests/src/test/scala/akka/serialization/SerializationSetupSpec.scala index efe295abe7..1de7f02180 100644 --- a/akka-actor-tests/src/test/scala/akka/serialization/SerializationSetupSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/serialization/SerializationSetupSpec.scala @@ -6,8 +6,8 @@ package akka.serialization import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger -import java.util.{ BitSet ⇒ ProgrammaticJavaDummy } -import java.util.{ Date ⇒ SerializableDummy } +import java.util.{ BitSet => ProgrammaticJavaDummy } +import java.util.{ Date => SerializableDummy } import akka.actor.setup.ActorSystemSetup import akka.actor.{ ActorSystem, BootstrapSetup, ExtendedActorSystem } @@ -49,7 +49,7 @@ object SerializationSetupSpec { val programmaticDummySerializer = new FakeSerializer val testSerializer = new NoopSerializer - val serializationSettings = SerializationSetup { _ ⇒ + val serializationSettings = SerializationSetup { _ => List( SerializerDetails("test", programmaticDummySerializer, List(classOf[ProgrammaticDummy]))) } @@ -121,7 +121,7 @@ class SerializationSetupSpec extends AkkaSpec( // that they'd need a different actor system to be able to create it... someone MAY pick a system with // allow-java-serialization=on to create the SerializationSetup and use that SerializationSetup // in another system with allow-java-serialization=off - val addedJavaSerializationSettings = SerializationSetup { _ ⇒ + val addedJavaSerializationSettings = SerializationSetup { _ => List( SerializerDetails("test", programmaticDummySerializer, List(classOf[ProgrammaticDummy])), SerializerDetails("java-manual", new JavaSerializer(system.asInstanceOf[ExtendedActorSystem]), List(classOf[ProgrammaticJavaDummy]))) diff --git a/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala b/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala index b198b91eff..2a0e1cffd7 100644 --- a/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala @@ -94,7 +94,7 @@ object SerializationTests { class FooActor extends Actor { def receive = { - case s: String ⇒ sender() ! s + case s: String => sender() ! s } } @@ -105,7 +105,7 @@ object SerializationTests { class NonSerializableActor(system: ActorSystem) extends Actor { def receive = { - case s: String ⇒ sender() ! s + case s: String => sender() ! s } } @@ -157,8 +157,8 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) { "Serialization" must { "have correct bindings" in { - ser.bindings.collectFirst { case (c, s) if c == address.getClass ⇒ s.getClass } should ===(Some(classOf[JavaSerializer])) - ser.bindings.collectFirst { case (c, s) if c == classOf[PlainMessage] ⇒ s.getClass } should ===(Some(classOf[NoopSerializer])) + ser.bindings.collectFirst { case (c, s) if c == address.getClass => s.getClass } should ===(Some(classOf[JavaSerializer])) + ser.bindings.collectFirst { case (c, s) if c == classOf[PlainMessage] => s.getClass } should ===(Some(classOf[NoopSerializer])) } "serialize Address" in { @@ -177,8 +177,8 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) { "not serialize ActorCell" in { val a = system.actorOf(Props(new Actor { def receive = { - case o: ObjectOutputStream ⇒ - try o.writeObject(this) catch { case _: NotSerializableException ⇒ testActor ! "pass" } + case o: ObjectOutputStream => + try o.writeObject(this) catch { case _: NotSerializableException => testActor ! "pass" } } })) a ! new ObjectOutputStream(new ByteArrayOutputStream()) @@ -263,7 +263,7 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) { val byteSerializer = ser.serializerFor(classOf[Array[Byte]]) byteSerializer.getClass should be theSameInstanceAs classOf[ByteArraySerializer] - for (a ← Seq("foo".getBytes("UTF-8"), null: Array[Byte], Array[Byte]())) + for (a <- Seq("foo".getBytes("UTF-8"), null: Array[Byte], Array[Byte]())) byteSerializer.fromBinary(byteSerializer.toBinary(a)) should be theSameInstanceAs a intercept[IllegalArgumentException] { @@ -342,7 +342,7 @@ class ReferenceSerializationSpec extends AkkaSpec(SerializationTests.mostlyRefer "declare Serializable classes to be use JavaSerializer" in { serializerMustBe(classOf[Serializable], classOf[JavaSerializer]) serializerMustBe(classOf[String], classOf[JavaSerializer]) - for (smc ← systemMessageClasses) { + for (smc <- systemMessageClasses) { serializerMustBe(smc, classOf[JavaSerializer]) } } @@ -356,7 +356,7 @@ class ReferenceSerializationSpec extends AkkaSpec(SerializationTests.mostlyRefer } "serialize function with JavaSerializer" in { - val f = (i: Int) ⇒ i + 1 + val f = (i: Int) => i + 1 val serializer = ser.serializerFor(f.getClass) serializer.getClass should ===(classOf[JavaSerializer]) val bytes = ser.serialize(f).get @@ -463,7 +463,7 @@ class OverriddenSystemMessageSerializationSpec extends AkkaSpec(SerializationTes "resolve to a single serializer" in { EventFilter.warning(start = "Multiple serializers found", occurrences = 0) intercept { - for (smc ← systemMessageClasses) { + for (smc <- systemMessageClasses) { ser.serializerFor(smc).getClass should ===(classOf[NoopSerializer]) } } diff --git a/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala b/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala index 3628f6cc38..64fbd934d7 100644 --- a/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/testkit/CallingThreadDispatcherModelSpec.scala @@ -22,7 +22,7 @@ object CallingThreadDispatcherModelSpec { } """ + // use unique dispatcher id for each test, since MessageDispatcherInterceptor holds state - (for (n ← 1 to 30) yield """ + (for (n <- 1 to 30) yield """ test-calling-thread-%s { type = "akka.testkit.CallingThreadDispatcherModelSpec$CallingThreadDispatcherInterceptorConfigurator" }""".format(n)).mkString diff --git a/akka-actor-tests/src/test/scala/akka/util/BoundedBlockingQueueSpec.scala b/akka-actor-tests/src/test/scala/akka/util/BoundedBlockingQueueSpec.scala index 8a2e51b872..aaa685277a 100644 --- a/akka-actor-tests/src/test/scala/akka/util/BoundedBlockingQueueSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/util/BoundedBlockingQueueSpec.scala @@ -617,10 +617,10 @@ trait CustomContainsMatcher { def attemptMatch(remainingTruth: List[A], remainingSequence: List[A]): MatchResult = (remainingTruth, remainingSequence) match { - case (_, Nil) ⇒ matchResult(true) - case (Nil, _) ⇒ matchResult(false) - case (x :: xs, y :: ys) if x.equals(y) ⇒ attemptMatch(xs, ys) - case (x :: xs, ys) ⇒ attemptMatch(xs, ys) + case (_, Nil) => matchResult(true) + case (Nil, _) => matchResult(false) + case (x :: xs, y :: ys) if x.equals(y) => attemptMatch(xs, ys) + case (x :: xs, ys) => attemptMatch(xs, ys) } def matchResult(success: Boolean): MatchResult = @@ -651,7 +651,7 @@ trait BlockingHelpers { * Delay execution of some code until the timespan has passed. * The action is wrapped in a Future that initially calls `Thread.sleep()` */ - def after(timespan: Span)(action: ⇒ Unit): Future[Unit] = Future { + def after(timespan: Span)(action: => Unit): Future[Unit] = Future { LockSupport.parkNanos(timespan.toNanos) action } @@ -659,7 +659,7 @@ trait BlockingHelpers { /** * Check that a call does not return within a set timespan. */ - def mustBlockFor(timeout: Span)(action: ⇒ Unit)(implicit pos: Position): Unit = + def mustBlockFor(timeout: Span)(action: => Unit)(implicit pos: Position): Unit = Exception.ignoring(classOf[TestFailedDueToTimeoutException]) { failAfter(timeout)(action) fail("Expected action to block for at least " + timeout.prettyString + " but it completed.") @@ -742,7 +742,7 @@ trait QueueSetupHelper { def advanceTime(timespan: Span): Unit = { waiting match { - case Some(manual) ⇒ + case Some(manual) => val newWaitTime = manual.waitTime - timespan.toNanos waiting = if (newWaitTime <= 0 && manual.waitingThread.isDefined) { @@ -752,7 +752,7 @@ trait QueueSetupHelper { Some(manual.copy(waitTime = newWaitTime)) } - case None ⇒ + case None => sys.error("Called advance time but hasn't enabled manualTimeControl") } } @@ -774,7 +774,7 @@ trait QueueSetupHelper { try { this.await() } catch { - case _: InterruptedException ⇒ + case _: InterruptedException => } waitTime } diff --git a/akka-actor-tests/src/test/scala/akka/util/ByteStringSpec.scala b/akka-actor-tests/src/test/scala/akka/util/ByteStringSpec.scala index d1fa3ed9d2..9fbb586040 100644 --- a/akka-actor-tests/src/test/scala/akka/util/ByteStringSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/util/ByteStringSpec.scala @@ -24,17 +24,17 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { implicit val betterGeneratorDrivenConfig = PropertyCheckConfig().copy(minSuccessful = 1000) def genSimpleByteString(min: Int, max: Int) = for { - n ← Gen.choose(min, max) - b ← Gen.containerOfN[Array, Byte](n, arbitrary[Byte]) - from ← Gen.choose(0, b.length) - until ← Gen.choose(from, from max b.length) + n <- Gen.choose(min, max) + b <- Gen.containerOfN[Array, Byte](n, arbitrary[Byte]) + from <- Gen.choose(0, b.length) + until <- Gen.choose(from, from max b.length) } yield ByteString(b).slice(from, until) implicit val arbitraryByteString: Arbitrary[ByteString] = Arbitrary { - Gen.sized { s ⇒ + Gen.sized { s => for { - chunks ← Gen.choose(0, s) - bytes ← Gen.listOfN(chunks, genSimpleByteString(1, 1 max (s / (chunks max 1)))) + chunks <- Gen.choose(0, s) + bytes <- Gen.listOfN(chunks, genSimpleByteString(1, 1 max (s / (chunks max 1)))) } yield bytes.foldLeft(ByteString.empty)(_ ++ _) } } @@ -43,9 +43,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { implicit val arbitraryByteStringSlice: Arbitrary[ByteStringSlice] = Arbitrary { for { - xs ← arbitraryByteString.arbitrary - from ← Gen.choose(0, 0 max (xs.length - 1)) - until ← { + xs <- arbitraryByteString.arbitrary + from <- Gen.choose(0, 0 max (xs.length - 1)) + until <- { require(from <= xs.length) Gen.choose(from, xs.length) } @@ -56,8 +56,8 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { implicit val arbitraryByteStringGrouped = Arbitrary { for { - xs ← arbitraryByteString.arbitrary - size ← Gen.choose(1, 1 max xs.length) + xs <- arbitraryByteString.arbitrary + size <- Gen.choose(1, 1 max xs.length) } yield ByteStringGrouped(xs, size) } @@ -65,9 +65,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { def arbSlice[A](arbArray: Arbitrary[Array[A]]): Arbitrary[ArraySlice[A]] = Arbitrary { for { - xs ← arbArray.arbitrary - from ← Gen.choose(0, xs.length) - until ← Gen.choose(from, xs.length) + xs <- arbArray.arbitrary + from <- Gen.choose(0, xs.length) + until <- Gen.choose(from, xs.length) } yield (xs, from, until) } @@ -95,58 +95,58 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { String valueOf encodeHex(os.toByteArray) } - val arbitraryByteArray: Arbitrary[Array[Byte]] = Arbitrary { Gen.sized { n ⇒ Gen.containerOfN[Array, Byte](n, arbitrary[Byte]) } } + val arbitraryByteArray: Arbitrary[Array[Byte]] = Arbitrary { Gen.sized { n => Gen.containerOfN[Array, Byte](n, arbitrary[Byte]) } } implicit val arbitraryByteArraySlice: Arbitrary[ArraySlice[Byte]] = arbSlice(arbitraryByteArray) - val arbitraryShortArray: Arbitrary[Array[Short]] = Arbitrary { Gen.sized { n ⇒ Gen.containerOfN[Array, Short](n, arbitrary[Short]) } } + val arbitraryShortArray: Arbitrary[Array[Short]] = Arbitrary { Gen.sized { n => Gen.containerOfN[Array, Short](n, arbitrary[Short]) } } implicit val arbitraryShortArraySlice: Arbitrary[ArraySlice[Short]] = arbSlice(arbitraryShortArray) - val arbitraryIntArray: Arbitrary[Array[Int]] = Arbitrary { Gen.sized { n ⇒ Gen.containerOfN[Array, Int](n, arbitrary[Int]) } } + val arbitraryIntArray: Arbitrary[Array[Int]] = Arbitrary { Gen.sized { n => Gen.containerOfN[Array, Int](n, arbitrary[Int]) } } implicit val arbitraryIntArraySlice: Arbitrary[ArraySlice[Int]] = arbSlice(arbitraryIntArray) - val arbitraryLongArray: Arbitrary[Array[Long]] = Arbitrary { Gen.sized { n ⇒ Gen.containerOfN[Array, Long](n, arbitrary[Long]) } } + val arbitraryLongArray: Arbitrary[Array[Long]] = Arbitrary { Gen.sized { n => Gen.containerOfN[Array, Long](n, arbitrary[Long]) } } implicit val arbitraryLongArraySlice: Arbitrary[ArraySlice[Long]] = arbSlice(arbitraryLongArray) - val arbitraryFloatArray: Arbitrary[Array[Float]] = Arbitrary { Gen.sized { n ⇒ Gen.containerOfN[Array, Float](n, arbitrary[Float]) } } + val arbitraryFloatArray: Arbitrary[Array[Float]] = Arbitrary { Gen.sized { n => Gen.containerOfN[Array, Float](n, arbitrary[Float]) } } implicit val arbitraryFloatArraySlice: Arbitrary[ArraySlice[Float]] = arbSlice(arbitraryFloatArray) - val arbitraryDoubleArray: Arbitrary[Array[Double]] = Arbitrary { Gen.sized { n ⇒ Gen.containerOfN[Array, Double](n, arbitrary[Double]) } } + val arbitraryDoubleArray: Arbitrary[Array[Double]] = Arbitrary { Gen.sized { n => Gen.containerOfN[Array, Double](n, arbitrary[Double]) } } implicit val arbitraryDoubleArraySlice: Arbitrary[ArraySlice[Double]] = arbSlice(arbitraryDoubleArray) type ArrayNumBytes[A] = (Array[A], Int) implicit val arbitraryLongArrayNumBytes: Arbitrary[ArrayNumBytes[Long]] = Arbitrary { for { - xs ← arbitraryLongArray.arbitrary - from ← Gen.choose(0, xs.length) - until ← Gen.choose(from, xs.length) - bytes ← Gen.choose(0, 8) + xs <- arbitraryLongArray.arbitrary + from <- Gen.choose(0, xs.length) + until <- Gen.choose(from, xs.length) + bytes <- Gen.choose(0, 8) } yield (xs.slice(from, until), bytes) } implicit val arbitraryByteStringBuilder: Arbitrary[ByteStringBuilder] = Arbitrary(ByteString.newBuilder) - def likeVector(bs: ByteString)(body: IndexedSeq[Byte] ⇒ Any): Boolean = { + def likeVector(bs: ByteString)(body: IndexedSeq[Byte] => Any): Boolean = { val vec = Vector(bs: _*) body(bs) == body(vec) } - def likeVectors(bsA: ByteString, bsB: ByteString)(body: (IndexedSeq[Byte], IndexedSeq[Byte]) ⇒ Any): Boolean = { + def likeVectors(bsA: ByteString, bsB: ByteString)(body: (IndexedSeq[Byte], IndexedSeq[Byte]) => Any): Boolean = { val vecA = Vector(bsA: _*) val vecB = Vector(bsB: _*) body(bsA, bsB) == body(vecA, vecB) } - def likeVecIt(bs: ByteString)(body: BufferedIterator[Byte] ⇒ Any, strict: Boolean = true): Boolean = { + def likeVecIt(bs: ByteString)(body: BufferedIterator[Byte] => Any, strict: Boolean = true): Boolean = { val bsIterator = bs.iterator val vecIterator = Vector(bs: _*).iterator.buffered (body(bsIterator) == body(vecIterator)) && (!strict || (bsIterator.toSeq == vecIterator.toSeq)) } - def likeVecIts(a: ByteString, b: ByteString)(body: (BufferedIterator[Byte], BufferedIterator[Byte]) ⇒ Any, strict: Boolean = true): Boolean = { + def likeVecIts(a: ByteString, b: ByteString)(body: (BufferedIterator[Byte], BufferedIterator[Byte]) => Any, strict: Boolean = true): Boolean = { val (bsAIt, bsBIt) = (a.iterator, b.iterator) val (vecAIt, vecBIt) = (Vector(a: _*).iterator.buffered, Vector(b: _*).iterator.buffered) (body(bsAIt, bsBIt) == body(vecAIt, vecBIt)) && - (!strict || (bsAIt.toSeq → bsBIt.toSeq) == (vecAIt.toSeq → vecBIt.toSeq)) + (!strict || (bsAIt.toSeq -> bsBIt.toSeq) == (vecAIt.toSeq -> vecBIt.toSeq)) } - def likeVecBld(body: Builder[Byte, _] ⇒ Unit): Boolean = { + def likeVecBld(body: Builder[Byte, _] => Unit): Boolean = { val bsBuilder = ByteString.newBuilder val vecBuilder = Vector.newBuilder[Byte] @@ -164,9 +164,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { bytes.asByteBuffer.order(byteOrder).asShortBuffer.get(reference, 0, n) val input = bytes.iterator val decoded = new Array[Short](n) - for (i ← 0 until a) decoded(i) = input.getShort(byteOrder) + for (i <- 0 until a) decoded(i) = input.getShort(byteOrder) input.getShorts(decoded, a, b - a)(byteOrder) - for (i ← b until n) decoded(i) = input.getShort(byteOrder) + for (i <- b until n) decoded(i) = input.getShort(byteOrder) (decoded.toSeq == reference.toSeq) && (input.toSeq == bytes.drop(n * elemSize)) } @@ -178,9 +178,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { bytes.asByteBuffer.order(byteOrder).asIntBuffer.get(reference, 0, n) val input = bytes.iterator val decoded = new Array[Int](n) - for (i ← 0 until a) decoded(i) = input.getInt(byteOrder) + for (i <- 0 until a) decoded(i) = input.getInt(byteOrder) input.getInts(decoded, a, b - a)(byteOrder) - for (i ← b until n) decoded(i) = input.getInt(byteOrder) + for (i <- b until n) decoded(i) = input.getInt(byteOrder) (decoded.toSeq == reference.toSeq) && (input.toSeq == bytes.drop(n * elemSize)) } @@ -192,9 +192,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { bytes.asByteBuffer.order(byteOrder).asLongBuffer.get(reference, 0, n) val input = bytes.iterator val decoded = new Array[Long](n) - for (i ← 0 until a) decoded(i) = input.getLong(byteOrder) + for (i <- 0 until a) decoded(i) = input.getLong(byteOrder) input.getLongs(decoded, a, b - a)(byteOrder) - for (i ← b until n) decoded(i) = input.getLong(byteOrder) + for (i <- b until n) decoded(i) = input.getLong(byteOrder) (decoded.toSeq == reference.toSeq) && (input.toSeq == bytes.drop(n * elemSize)) } @@ -206,9 +206,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { bytes.asByteBuffer.order(byteOrder).asFloatBuffer.get(reference, 0, n) val input = bytes.iterator val decoded = new Array[Float](n) - for (i ← 0 until a) decoded(i) = input.getFloat(byteOrder) + for (i <- 0 until a) decoded(i) = input.getFloat(byteOrder) input.getFloats(decoded, a, b - a)(byteOrder) - for (i ← b until n) decoded(i) = input.getFloat(byteOrder) + for (i <- b until n) decoded(i) = input.getFloat(byteOrder) ((decoded.toSeq map floatToRawIntBits) == (reference.toSeq map floatToRawIntBits)) && (input.toSeq == bytes.drop(n * elemSize)) } @@ -221,9 +221,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { bytes.asByteBuffer.order(byteOrder).asDoubleBuffer.get(reference, 0, n) val input = bytes.iterator val decoded = new Array[Double](n) - for (i ← 0 until a) decoded(i) = input.getDouble(byteOrder) + for (i <- 0 until a) decoded(i) = input.getDouble(byteOrder) input.getDoubles(decoded, a, b - a)(byteOrder) - for (i ← b until n) decoded(i) = input.getDouble(byteOrder) + for (i <- b until n) decoded(i) = input.getDouble(byteOrder) ((decoded.toSeq map doubleToRawLongBits) == (reference.toSeq map doubleToRawLongBits)) && (input.toSeq == bytes.drop(n * elemSize)) } @@ -234,9 +234,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { val reference = new Array[Byte](data.length * elemSize) ByteBuffer.wrap(reference).order(byteOrder).asShortBuffer.put(data) val builder = ByteString.newBuilder - for (i ← 0 until from) builder.putShort(data(i))(byteOrder) + for (i <- 0 until from) builder.putShort(data(i))(byteOrder) builder.putShorts(data, from, to - from)(byteOrder) - for (i ← to until data.length) builder.putShort(data(i))(byteOrder) + for (i <- to until data.length) builder.putShort(data(i))(byteOrder) reference.toSeq == builder.result } @@ -246,9 +246,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { val reference = new Array[Byte](data.length * elemSize) ByteBuffer.wrap(reference).order(byteOrder).asIntBuffer.put(data) val builder = ByteString.newBuilder - for (i ← 0 until from) builder.putInt(data(i))(byteOrder) + for (i <- 0 until from) builder.putInt(data(i))(byteOrder) builder.putInts(data, from, to - from)(byteOrder) - for (i ← to until data.length) builder.putInt(data(i))(byteOrder) + for (i <- to until data.length) builder.putInt(data(i))(byteOrder) reference.toSeq == builder.result } @@ -258,9 +258,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { val reference = new Array[Byte](data.length * elemSize) ByteBuffer.wrap(reference).order(byteOrder).asLongBuffer.put(data) val builder = ByteString.newBuilder - for (i ← 0 until from) builder.putLong(data(i))(byteOrder) + for (i <- 0 until from) builder.putLong(data(i))(byteOrder) builder.putLongs(data, from, to - from)(byteOrder) - for (i ← to until data.length) builder.putLong(data(i))(byteOrder) + for (i <- to until data.length) builder.putLong(data(i))(byteOrder) reference.toSeq == builder.result } @@ -271,11 +271,11 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { val reference = new Array[Byte](data.length * elemSize) ByteBuffer.wrap(reference).order(byteOrder).asLongBuffer.put(data) val builder = ByteString.newBuilder - for (i ← 0 until data.length) builder.putLongPart(data(i), nBytes)(byteOrder) + for (i <- 0 until data.length) builder.putLongPart(data(i), nBytes)(byteOrder) reference.zipWithIndex.collect({ // Since there is no partial put on LongBuffer, we need to collect only the interesting bytes - case (r, i) if byteOrder == ByteOrder.LITTLE_ENDIAN && i % elemSize < nBytes ⇒ r - case (r, i) if byteOrder == ByteOrder.BIG_ENDIAN && i % elemSize >= (elemSize - nBytes) ⇒ r + case (r, i) if byteOrder == ByteOrder.LITTLE_ENDIAN && i % elemSize < nBytes => r + case (r, i) if byteOrder == ByteOrder.BIG_ENDIAN && i % elemSize >= (elemSize - nBytes) => r }).toSeq == builder.result } @@ -285,9 +285,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { val reference = new Array[Byte](data.length * elemSize) ByteBuffer.wrap(reference).order(byteOrder).asFloatBuffer.put(data) val builder = ByteString.newBuilder - for (i ← 0 until from) builder.putFloat(data(i))(byteOrder) + for (i <- 0 until from) builder.putFloat(data(i))(byteOrder) builder.putFloats(data, from, to - from)(byteOrder) - for (i ← to until data.length) builder.putFloat(data(i))(byteOrder) + for (i <- to until data.length) builder.putFloat(data(i))(byteOrder) reference.toSeq == builder.result } @@ -297,9 +297,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { val reference = new Array[Byte](data.length * elemSize) ByteBuffer.wrap(reference).order(byteOrder).asDoubleBuffer.put(data) val builder = ByteString.newBuilder - for (i ← 0 until from) builder.putDouble(data(i))(byteOrder) + for (i <- 0 until from) builder.putDouble(data(i))(byteOrder) builder.putDoubles(data, from, to - from)(byteOrder) - for (i ← to until data.length) builder.putDouble(data(i))(byteOrder) + for (i <- to until data.length) builder.putDouble(data(i))(byteOrder) reference.toSeq == builder.result } @@ -616,23 +616,23 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { "A ByteString" must { "have correct size" when { - "concatenating" in { check((a: ByteString, b: ByteString) ⇒ (a ++ b).size == a.size + b.size) } - "dropping" in { check((a: ByteString, b: ByteString) ⇒ (a ++ b).drop(b.size).size == a.size) } - "taking" in { check((a: ByteString, b: ByteString) ⇒ (a ++ b).take(a.size) == a) } - "takingRight" in { check((a: ByteString, b: ByteString) ⇒ (a ++ b).takeRight(b.size) == b) } - "dropping then taking" in { check((a: ByteString, b: ByteString) ⇒ (b ++ a ++ b).drop(b.size).take(a.size) == a) } - "droppingRight" in { check((a: ByteString, b: ByteString) ⇒ (b ++ a ++ b).drop(b.size).dropRight(b.size) == a) } + "concatenating" in { check((a: ByteString, b: ByteString) => (a ++ b).size == a.size + b.size) } + "dropping" in { check((a: ByteString, b: ByteString) => (a ++ b).drop(b.size).size == a.size) } + "taking" in { check((a: ByteString, b: ByteString) => (a ++ b).take(a.size) == a) } + "takingRight" in { check((a: ByteString, b: ByteString) => (a ++ b).takeRight(b.size) == b) } + "dropping then taking" in { check((a: ByteString, b: ByteString) => (b ++ a ++ b).drop(b.size).take(a.size) == a) } + "droppingRight" in { check((a: ByteString, b: ByteString) => (b ++ a ++ b).drop(b.size).dropRight(b.size) == a) } } "be sequential" when { - "taking" in { check((a: ByteString, b: ByteString) ⇒ (a ++ b).take(a.size) == a) } - "dropping" in { check((a: ByteString, b: ByteString) ⇒ (a ++ b).drop(a.size) == b) } + "taking" in { check((a: ByteString, b: ByteString) => (a ++ b).take(a.size) == a) } + "dropping" in { check((a: ByteString, b: ByteString) => (a ++ b).drop(a.size) == b) } } "be equal to the original" when { - "compacting" in { check { xs: ByteString ⇒ val ys = xs.compact; (xs == ys) && ys.isCompact } } + "compacting" in { check { xs: ByteString => val ys = xs.compact; (xs == ys) && ys.isCompact } } "recombining" in { - check { (xs: ByteString, from: Int, until: Int) ⇒ + check { (xs: ByteString, from: Int, until: Int) => val (tmp, c) = xs.splitAt(until) val (a, b) = tmp.splitAt(from) (a ++ b ++ c) == xs @@ -656,10 +656,10 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "behave as expected" when { - "created from and decoding to String" in { check { s: String ⇒ ByteString(s, "UTF-8").decodeString("UTF-8") == s } } + "created from and decoding to String" in { check { s: String => ByteString(s, "UTF-8").decodeString("UTF-8") == s } } "compacting" in { - check { a: ByteString ⇒ + check { a: ByteString => val wasCompact = a.isCompact val b = a.compact ((!wasCompact) || (b eq a)) && @@ -670,28 +670,28 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "asByteBuffers" in { - check { (a: ByteString) ⇒ if (a.isCompact) a.asByteBuffers.size == 1 && a.asByteBuffers.head == a.asByteBuffer else a.asByteBuffers.size > 0 } - check { (a: ByteString) ⇒ a.asByteBuffers.foldLeft(ByteString.empty) { (bs, bb) ⇒ bs ++ ByteString(bb) } == a } - check { (a: ByteString) ⇒ a.asByteBuffers.forall(_.isReadOnly) } - check { (a: ByteString) ⇒ + check { (a: ByteString) => if (a.isCompact) a.asByteBuffers.size == 1 && a.asByteBuffers.head == a.asByteBuffer else a.asByteBuffers.size > 0 } + check { (a: ByteString) => a.asByteBuffers.foldLeft(ByteString.empty) { (bs, bb) => bs ++ ByteString(bb) } == a } + check { (a: ByteString) => a.asByteBuffers.forall(_.isReadOnly) } + check { (a: ByteString) => import scala.collection.JavaConverters.iterableAsScalaIterableConverter - a.asByteBuffers.zip(a.getByteBuffers().asScala).forall(x ⇒ x._1 == x._2) + a.asByteBuffers.zip(a.getByteBuffers().asScala).forall(x => x._1 == x._2) } } "toString should start with ByteString(" in { - check { (bs: ByteString) ⇒ + check { (bs: ByteString) => bs.toString.startsWith("ByteString(") } } } "behave like a Vector" when { - "concatenating" in { check { (a: ByteString, b: ByteString) ⇒ likeVectors(a, b) { _ ++ _ } } } + "concatenating" in { check { (a: ByteString, b: ByteString) => likeVectors(a, b) { _ ++ _ } } } "calling apply" in { - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => slice match { - case (xs, i1, i2) ⇒ likeVector(xs) { seq ⇒ + case (xs, i1, i2) => likeVector(xs) { seq => (if ((i1 >= 0) && (i1 < seq.length)) seq(i1) else 0, if ((i2 >= 0) && (i2 < seq.length)) seq(i2) else 0) } @@ -699,30 +699,30 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } } - "calling head" in { check { a: ByteString ⇒ a.isEmpty || likeVector(a) { _.head } } } - "calling tail" in { check { a: ByteString ⇒ a.isEmpty || likeVector(a) { _.tail } } } - "calling last" in { check { a: ByteString ⇒ a.isEmpty || likeVector(a) { _.last } } } - "calling init" in { check { a: ByteString ⇒ a.isEmpty || likeVector(a) { _.init } } } - "calling length" in { check { a: ByteString ⇒ likeVector(a) { _.length } } } + "calling head" in { check { a: ByteString => a.isEmpty || likeVector(a) { _.head } } } + "calling tail" in { check { a: ByteString => a.isEmpty || likeVector(a) { _.tail } } } + "calling last" in { check { a: ByteString => a.isEmpty || likeVector(a) { _.last } } } + "calling init" in { check { a: ByteString => a.isEmpty || likeVector(a) { _.init } } } + "calling length" in { check { a: ByteString => likeVector(a) { _.length } } } - "calling span" in { check { (a: ByteString, b: Byte) ⇒ likeVector(a)({ _.span(_ != b) match { case (a, b) ⇒ (a, b) } }) } } + "calling span" in { check { (a: ByteString, b: Byte) => likeVector(a)({ _.span(_ != b) match { case (a, b) => (a, b) } }) } } - "calling takeWhile" in { check { (a: ByteString, b: Byte) ⇒ likeVector(a)({ _.takeWhile(_ != b) }) } } - "calling dropWhile" in { check { (a: ByteString, b: Byte) ⇒ likeVector(a) { _.dropWhile(_ != b) } } } - "calling indexWhere" in { check { (a: ByteString, b: Byte) ⇒ likeVector(a) { _.indexWhere(_ == b) } } } - "calling indexOf" in { check { (a: ByteString, b: Byte) ⇒ likeVector(a) { _.indexOf(b) } } } + "calling takeWhile" in { check { (a: ByteString, b: Byte) => likeVector(a)({ _.takeWhile(_ != b) }) } } + "calling dropWhile" in { check { (a: ByteString, b: Byte) => likeVector(a) { _.dropWhile(_ != b) } } } + "calling indexWhere" in { check { (a: ByteString, b: Byte) => likeVector(a) { _.indexWhere(_ == b) } } } + "calling indexOf" in { check { (a: ByteString, b: Byte) => likeVector(a) { _.indexOf(b) } } } // this actually behave weird for Vector and negative indexes - SI9936, fixed in Scala 2.12 // so let's just skip negative indexes (doesn't make much sense anyway) - "calling indexOf(elem, idx)" in { check { (a: ByteString, b: Byte, idx: Int) ⇒ likeVector(a) { _.indexOf(b, math.max(0, idx)) } } } + "calling indexOf(elem, idx)" in { check { (a: ByteString, b: Byte, idx: Int) => likeVector(a) { _.indexOf(b, math.max(0, idx)) } } } - "calling foreach" in { check { a: ByteString ⇒ likeVector(a) { it ⇒ var acc = 0; it foreach { acc += _ }; acc } } } - "calling foldLeft" in { check { a: ByteString ⇒ likeVector(a) { _.foldLeft(0) { _ + _ } } } } - "calling toArray" in { check { a: ByteString ⇒ likeVector(a) { _.toArray.toSeq } } } + "calling foreach" in { check { a: ByteString => likeVector(a) { it => var acc = 0; it foreach { acc += _ }; acc } } } + "calling foldLeft" in { check { a: ByteString => likeVector(a) { _.foldLeft(0) { _ + _ } } } } + "calling toArray" in { check { a: ByteString => likeVector(a) { _.toArray.toSeq } } } "calling slice" in { - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => slice match { - case (xs, from, until) ⇒ likeVector(xs)({ + case (xs, from, until) => likeVector(xs)({ _.slice(from, until) }) } @@ -730,9 +730,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "calling take and drop" in { - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => slice match { - case (xs, from, until) ⇒ likeVector(xs)({ + case (xs, from, until) => likeVector(xs)({ _.drop(from).take(until - from) }) } @@ -740,7 +740,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "calling grouped" in { - check { grouped: ByteStringGrouped ⇒ + check { grouped: ByteStringGrouped => likeVector(grouped.bs) { _.grouped(grouped.size).toIndexedSeq } @@ -748,9 +748,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "calling copyToArray" in { - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => slice match { - case (xs, from, until) ⇒ likeVector(xs)({ it ⇒ + case (xs, from, until) => likeVector(xs)({ it => val array = new Array[Byte](xs.length) it.slice(from, until).copyToArray(array, from, until) array.toSeq @@ -775,7 +775,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "given all types of ByteString" in { - check { bs: ByteString ⇒ + check { bs: ByteString => testSer(bs) } } @@ -791,32 +791,32 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { "A ByteStringIterator" must { "behave like a buffered Vector Iterator" when { - "concatenating" in { check { (a: ByteString, b: ByteString) ⇒ likeVecIts(a, b) { (a, b) ⇒ (a ++ b).toSeq } } } + "concatenating" in { check { (a: ByteString, b: ByteString) => likeVecIts(a, b) { (a, b) => (a ++ b).toSeq } } } - "calling head" in { check { a: ByteString ⇒ a.isEmpty || likeVecIt(a) { _.head } } } - "calling next" in { check { a: ByteString ⇒ a.isEmpty || likeVecIt(a) { _.next() } } } - "calling hasNext" in { check { a: ByteString ⇒ likeVecIt(a) { _.hasNext } } } - "calling length" in { check { a: ByteString ⇒ likeVecIt(a) { _.length } } } - "calling duplicate" in { check { a: ByteString ⇒ likeVecIt(a)({ _.duplicate match { case (a, b) ⇒ (a.toSeq, b.toSeq) } }, strict = false) } } + "calling head" in { check { a: ByteString => a.isEmpty || likeVecIt(a) { _.head } } } + "calling next" in { check { a: ByteString => a.isEmpty || likeVecIt(a) { _.next() } } } + "calling hasNext" in { check { a: ByteString => likeVecIt(a) { _.hasNext } } } + "calling length" in { check { a: ByteString => likeVecIt(a) { _.length } } } + "calling duplicate" in { check { a: ByteString => likeVecIt(a)({ _.duplicate match { case (a, b) => (a.toSeq, b.toSeq) } }, strict = false) } } // Have to used toList instead of toSeq here, iterator.span (new in // Scala-2.9) seems to be broken in combination with toSeq for the // scala.collection default Iterator (see Scala issue SI-5838). - "calling span" in { check { (a: ByteString, b: Byte) ⇒ likeVecIt(a)({ _.span(_ != b) match { case (a, b) ⇒ (a.toList, b.toList) } }, strict = false) } } + "calling span" in { check { (a: ByteString, b: Byte) => likeVecIt(a)({ _.span(_ != b) match { case (a, b) => (a.toList, b.toList) } }, strict = false) } } - "calling takeWhile" in { check { (a: ByteString, b: Byte) ⇒ likeVecIt(a)({ _.takeWhile(_ != b).toSeq }, strict = false) } } - "calling dropWhile" in { check { (a: ByteString, b: Byte) ⇒ likeVecIt(a) { _.dropWhile(_ != b).toSeq } } } - "calling indexWhere" in { check { (a: ByteString, b: Byte) ⇒ likeVecIt(a) { _.indexWhere(_ == b) } } } - "calling indexOf" in { check { (a: ByteString, b: Byte) ⇒ likeVecIt(a) { _.indexOf(b) } } } - "calling toSeq" in { check { a: ByteString ⇒ likeVecIt(a) { _.toSeq } } } - "calling foreach" in { check { a: ByteString ⇒ likeVecIt(a) { it ⇒ var acc = 0; it foreach { acc += _ }; acc } } } - "calling foldLeft" in { check { a: ByteString ⇒ likeVecIt(a) { _.foldLeft(0) { _ + _ } } } } - "calling toArray" in { check { a: ByteString ⇒ likeVecIt(a) { _.toArray.toSeq } } } + "calling takeWhile" in { check { (a: ByteString, b: Byte) => likeVecIt(a)({ _.takeWhile(_ != b).toSeq }, strict = false) } } + "calling dropWhile" in { check { (a: ByteString, b: Byte) => likeVecIt(a) { _.dropWhile(_ != b).toSeq } } } + "calling indexWhere" in { check { (a: ByteString, b: Byte) => likeVecIt(a) { _.indexWhere(_ == b) } } } + "calling indexOf" in { check { (a: ByteString, b: Byte) => likeVecIt(a) { _.indexOf(b) } } } + "calling toSeq" in { check { a: ByteString => likeVecIt(a) { _.toSeq } } } + "calling foreach" in { check { a: ByteString => likeVecIt(a) { it => var acc = 0; it foreach { acc += _ }; acc } } } + "calling foldLeft" in { check { a: ByteString => likeVecIt(a) { _.foldLeft(0) { _ + _ } } } } + "calling toArray" in { check { a: ByteString => likeVecIt(a) { _.toArray.toSeq } } } "calling slice" in { - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => slice match { - case (xs, from, until) ⇒ likeVecIt(xs)({ + case (xs, from, until) => likeVecIt(xs)({ _.slice(from, until).toSeq }, strict = false) } @@ -824,9 +824,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "calling take and drop" in { - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => slice match { - case (xs, from, until) ⇒ likeVecIt(xs)({ + case (xs, from, until) => likeVecIt(xs)({ _.drop(from).take(until - from).toSeq }, strict = false) } @@ -834,9 +834,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "calling copyToArray" in { - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => slice match { - case (xs, from, until) ⇒ likeVecIt(xs)({ it ⇒ + case (xs, from, until) => likeVecIt(xs)({ it => val array = new Array[Byte](xs.length) it.slice(from, until).copyToArray(array, from, until) array.toSeq @@ -849,20 +849,20 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { "function as expected" when { "getting Bytes, using getByte and getBytes" in { // mixing getByte and getBytes here for more rigorous testing - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => val (bytes, from, to) = slice val input = bytes.iterator val output = new Array[Byte](bytes.length) - for (i ← 0 until from) output(i) = input.getByte + for (i <- 0 until from) output(i) = input.getByte input.getBytes(output, from, to - from) - for (i ← to until bytes.length) output(i) = input.getByte + for (i <- to until bytes.length) output(i) = input.getByte (output.toSeq == bytes) && (input.isEmpty) } } "getting Bytes with a given length" in { check { - slice: ByteStringSlice ⇒ + slice: ByteStringSlice => val (bytes, _, _) = slice val input = bytes.iterator (input.getBytes(bytes.length).toSeq == bytes) && input.isEmpty @@ -871,7 +871,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { "getting ByteString with a given length" in { check { - slice: ByteStringSlice ⇒ + slice: ByteStringSlice => val (bytes, _, _) = slice val input = bytes.iterator (input.getByteString(bytes.length) == bytes) && input.isEmpty @@ -880,7 +880,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { "getting Bytes, using the InputStream wrapper" in { // combining skip and both read methods here for more rigorous testing - check { slice: ByteStringSlice ⇒ + check { slice: ByteStringSlice => val (bytes, from, to) = slice val a = (0 max from) min bytes.length val b = (a max to) min bytes.length @@ -898,7 +898,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } if (eof) throw new RuntimeException("Unexpected EOF") - for (i ← b until bytes.length) output(i) = input.asInputStream.read().toByte + for (i <- b until bytes.length) output(i) = input.asInputStream.read().toByte (output.toSeq.drop(a) == bytes.drop(a)) && (input.asInputStream.read() == -1) && @@ -907,7 +907,7 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "calling copyToBuffer" in { - check { bytes: ByteString ⇒ + check { bytes: ByteString => import java.nio.ByteBuffer val buffer = ByteBuffer.allocate(bytes.size) bytes.copyToBuffer(buffer) @@ -929,28 +929,28 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { } "decode data correctly" when { - "decoding Short in big-endian" in { check { slice: ByteStringSlice ⇒ testShortDecoding(slice, BIG_ENDIAN) } } - "decoding Short in little-endian" in { check { slice: ByteStringSlice ⇒ testShortDecoding(slice, LITTLE_ENDIAN) } } - "decoding Int in big-endian" in { check { slice: ByteStringSlice ⇒ testIntDecoding(slice, BIG_ENDIAN) } } - "decoding Int in little-endian" in { check { slice: ByteStringSlice ⇒ testIntDecoding(slice, LITTLE_ENDIAN) } } - "decoding Long in big-endian" in { check { slice: ByteStringSlice ⇒ testLongDecoding(slice, BIG_ENDIAN) } } - "decoding Long in little-endian" in { check { slice: ByteStringSlice ⇒ testLongDecoding(slice, LITTLE_ENDIAN) } } - "decoding Float in big-endian" in { check { slice: ByteStringSlice ⇒ testFloatDecoding(slice, BIG_ENDIAN) } } - "decoding Float in little-endian" in { check { slice: ByteStringSlice ⇒ testFloatDecoding(slice, LITTLE_ENDIAN) } } - "decoding Double in big-endian" in { check { slice: ByteStringSlice ⇒ testDoubleDecoding(slice, BIG_ENDIAN) } } - "decoding Double in little-endian" in { check { slice: ByteStringSlice ⇒ testDoubleDecoding(slice, LITTLE_ENDIAN) } } + "decoding Short in big-endian" in { check { slice: ByteStringSlice => testShortDecoding(slice, BIG_ENDIAN) } } + "decoding Short in little-endian" in { check { slice: ByteStringSlice => testShortDecoding(slice, LITTLE_ENDIAN) } } + "decoding Int in big-endian" in { check { slice: ByteStringSlice => testIntDecoding(slice, BIG_ENDIAN) } } + "decoding Int in little-endian" in { check { slice: ByteStringSlice => testIntDecoding(slice, LITTLE_ENDIAN) } } + "decoding Long in big-endian" in { check { slice: ByteStringSlice => testLongDecoding(slice, BIG_ENDIAN) } } + "decoding Long in little-endian" in { check { slice: ByteStringSlice => testLongDecoding(slice, LITTLE_ENDIAN) } } + "decoding Float in big-endian" in { check { slice: ByteStringSlice => testFloatDecoding(slice, BIG_ENDIAN) } } + "decoding Float in little-endian" in { check { slice: ByteStringSlice => testFloatDecoding(slice, LITTLE_ENDIAN) } } + "decoding Double in big-endian" in { check { slice: ByteStringSlice => testDoubleDecoding(slice, BIG_ENDIAN) } } + "decoding Double in little-endian" in { check { slice: ByteStringSlice => testDoubleDecoding(slice, LITTLE_ENDIAN) } } } } "A ByteStringBuilder" must { "function like a VectorBuilder" when { "adding various contents using ++= and +=" in { - check { (array1: Array[Byte], array2: Array[Byte], bs1: ByteString, bs2: ByteString, bs3: ByteString) ⇒ - likeVecBld { builder ⇒ + check { (array1: Array[Byte], array2: Array[Byte], bs1: ByteString, bs2: ByteString, bs3: ByteString) => + likeVecBld { builder => builder ++= array1 - bs1 foreach { b ⇒ builder += b } + bs1 foreach { b => builder += b } builder ++= bs2 - bs3 foreach { b ⇒ builder += b } + bs3 foreach { b => builder += b } builder ++= Vector(array2: _*) } } @@ -959,50 +959,50 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers { "function as expected" when { "putting Bytes, using putByte and putBytes" in { // mixing putByte and putBytes here for more rigorous testing - check { slice: ArraySlice[Byte] ⇒ + check { slice: ArraySlice[Byte] => val (data, from, to) = slice val builder = ByteString.newBuilder - for (i ← 0 until from) builder.putByte(data(i)) + for (i <- 0 until from) builder.putByte(data(i)) builder.putBytes(data, from, to - from) - for (i ← to until data.length) builder.putByte(data(i)) + for (i <- to until data.length) builder.putByte(data(i)) data.toSeq == builder.result } } "putting Bytes, using the OutputStream wrapper" in { // mixing the write methods here for more rigorous testing - check { slice: ArraySlice[Byte] ⇒ + check { slice: ArraySlice[Byte] => val (data, from, to) = slice val builder = ByteString.newBuilder - for (i ← 0 until from) builder.asOutputStream.write(data(i).toInt) + for (i <- 0 until from) builder.asOutputStream.write(data(i).toInt) builder.asOutputStream.write(data, from, to - from) - for (i ← to until data.length) builder.asOutputStream.write(data(i).toInt) + for (i <- to until data.length) builder.asOutputStream.write(data(i).toInt) data.toSeq == builder.result } } } "encode data correctly" when { - "encoding Short in big-endian" in { check { slice: ArraySlice[Short] ⇒ testShortEncoding(slice, BIG_ENDIAN) } } - "encoding Short in little-endian" in { check { slice: ArraySlice[Short] ⇒ testShortEncoding(slice, LITTLE_ENDIAN) } } - "encoding Int in big-endian" in { check { slice: ArraySlice[Int] ⇒ testIntEncoding(slice, BIG_ENDIAN) } } - "encoding Int in little-endian" in { check { slice: ArraySlice[Int] ⇒ testIntEncoding(slice, LITTLE_ENDIAN) } } - "encoding Long in big-endian" in { check { slice: ArraySlice[Long] ⇒ testLongEncoding(slice, BIG_ENDIAN) } } - "encoding Long in little-endian" in { check { slice: ArraySlice[Long] ⇒ testLongEncoding(slice, LITTLE_ENDIAN) } } - "encoding LongPart in big-endian" in { check { slice: ArrayNumBytes[Long] ⇒ testLongPartEncoding(slice, BIG_ENDIAN) } } - "encoding LongPart in little-endian" in { check { slice: ArrayNumBytes[Long] ⇒ testLongPartEncoding(slice, LITTLE_ENDIAN) } } - "encoding Float in big-endian" in { check { slice: ArraySlice[Float] ⇒ testFloatEncoding(slice, BIG_ENDIAN) } } - "encoding Float in little-endian" in { check { slice: ArraySlice[Float] ⇒ testFloatEncoding(slice, LITTLE_ENDIAN) } } - "encoding Double in big-endian" in { check { slice: ArraySlice[Double] ⇒ testDoubleEncoding(slice, BIG_ENDIAN) } } - "encoding Double in little-endian" in { check { slice: ArraySlice[Double] ⇒ testDoubleEncoding(slice, LITTLE_ENDIAN) } } + "encoding Short in big-endian" in { check { slice: ArraySlice[Short] => testShortEncoding(slice, BIG_ENDIAN) } } + "encoding Short in little-endian" in { check { slice: ArraySlice[Short] => testShortEncoding(slice, LITTLE_ENDIAN) } } + "encoding Int in big-endian" in { check { slice: ArraySlice[Int] => testIntEncoding(slice, BIG_ENDIAN) } } + "encoding Int in little-endian" in { check { slice: ArraySlice[Int] => testIntEncoding(slice, LITTLE_ENDIAN) } } + "encoding Long in big-endian" in { check { slice: ArraySlice[Long] => testLongEncoding(slice, BIG_ENDIAN) } } + "encoding Long in little-endian" in { check { slice: ArraySlice[Long] => testLongEncoding(slice, LITTLE_ENDIAN) } } + "encoding LongPart in big-endian" in { check { slice: ArrayNumBytes[Long] => testLongPartEncoding(slice, BIG_ENDIAN) } } + "encoding LongPart in little-endian" in { check { slice: ArrayNumBytes[Long] => testLongPartEncoding(slice, LITTLE_ENDIAN) } } + "encoding Float in big-endian" in { check { slice: ArraySlice[Float] => testFloatEncoding(slice, BIG_ENDIAN) } } + "encoding Float in little-endian" in { check { slice: ArraySlice[Float] => testFloatEncoding(slice, LITTLE_ENDIAN) } } + "encoding Double in big-endian" in { check { slice: ArraySlice[Double] => testDoubleEncoding(slice, BIG_ENDIAN) } } + "encoding Double in little-endian" in { check { slice: ArraySlice[Double] => testDoubleEncoding(slice, LITTLE_ENDIAN) } } } "have correct empty info" when { "is empty" in { - check { a: ByteStringBuilder ⇒ a.isEmpty } + check { a: ByteStringBuilder => a.isEmpty } } "is nonEmpty" in { - check { a: ByteStringBuilder ⇒ + check { a: ByteStringBuilder => a.putByte(1.toByte) a.nonEmpty } diff --git a/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala b/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala index 1ea3162fff..35a1ab73b5 100644 --- a/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/util/DurationSpec.scala @@ -55,7 +55,7 @@ class DurationSpec extends AkkaSpec { } /*"check its range" in { - for (unit ← Seq(DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS)) { + for (unit <- Seq(DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS)) { val x = unit.convert(Long.MaxValue, NANOSECONDS) val dur = Duration(x, unit) val mdur = Duration(-x, unit) diff --git a/akka-actor-tests/src/test/scala/akka/util/ImmutableIntMapSpec.scala b/akka-actor-tests/src/test/scala/akka/util/ImmutableIntMapSpec.scala index f5d4bceac6..ac33fb7bb1 100644 --- a/akka-actor-tests/src/test/scala/akka/util/ImmutableIntMapSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/util/ImmutableIntMapSpec.scala @@ -126,20 +126,20 @@ class ImmutableIntMapSpec extends WordSpec with Matchers { var reference = Map.empty[Long, Int] def verify(): Unit = { - val m = longMap.keysIterator.map(key ⇒ key → longMap.get(key)).toMap + val m = longMap.keysIterator.map(key => key -> longMap.get(key)).toMap m should be(reference) } - (1 to 1000).foreach { i ⇒ + (1 to 1000).foreach { i => withClue(s"seed=$seed, iteration=$i") { val key = rnd.nextInt(100) val value = rnd.nextPrintableChar() rnd.nextInt(3) match { - case 0 | 1 ⇒ + case 0 | 1 => longMap = longMap.updated(key, value) reference = reference.updated(key, value) - case 2 ⇒ + case 2 => longMap = longMap.remove(key) reference = reference - key } diff --git a/akka-actor-tests/src/test/scala/akka/util/IndexSpec.scala b/akka-actor-tests/src/test/scala/akka/util/IndexSpec.scala index 5f1e1478ed..147c5fa79d 100644 --- a/akka-actor-tests/src/test/scala/akka/util/IndexSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/util/IndexSpec.scala @@ -59,8 +59,8 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout { index.valueIterator("s1").toSet should ===(Set(2)) //Remove key index.remove("s2") match { - case Some(iter) ⇒ iter.toSet should ===(Set(1, 2)) - case None ⇒ fail() + case Some(iter) => iter.toSet should ===(Set(1, 2)) + case None => fail() } index.remove("s2") should ===(None) index.valueIterator("s2").toSet should ===(Set.empty[Int]) @@ -83,7 +83,7 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout { val index = indexWithValues var valueCount = 0 - index.foreach((key, value) ⇒ { + index.foreach((key, value) => { valueCount = valueCount + 1 index.findValue(key)(_ == value) should ===(Some(value)) }) @@ -103,7 +103,7 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout { val nrOfKeys = 10 val nrOfValues = 10 //Fill index - for (key ← 0 until nrOfKeys; value ← 0 until nrOfValues) + for (key <- 0 until nrOfKeys; value <- 0 until nrOfValues) index.put(key, value) //Tasks to be executed in parallel def putTask() = Future { @@ -124,10 +124,10 @@ class IndexSpec extends AkkaSpec with Matchers with DefaultTimeout { } def executeRandomTask() = Random.nextInt(4) match { - case 0 ⇒ putTask() - case 1 ⇒ removeTask1() - case 2 ⇒ removeTask2() - case 3 ⇒ readTask() + case 0 => putTask() + case 1 => removeTask1() + case 2 => removeTask2() + case 3 => readTask() } val tasks = List.fill(nrOfTasks)(executeRandomTask) diff --git a/akka-actor-tests/src/test/scala/akka/util/LineNumberSpecCodeForScala.scala b/akka-actor-tests/src/test/scala/akka/util/LineNumberSpecCodeForScala.scala index 9341bb96f9..4e0bde46ad 100644 --- a/akka-actor-tests/src/test/scala/akka/util/LineNumberSpecCodeForScala.scala +++ b/akka-actor-tests/src/test/scala/akka/util/LineNumberSpecCodeForScala.scala @@ -10,19 +10,19 @@ package akka.util object LineNumberSpecCodeForScala { - val oneline = (s: String) ⇒ println(s) + val oneline = (s: String) => println(s) - val twoline = (s: String) ⇒ { + val twoline = (s: String) => { println(s) Integer.parseInt(s) } val partial: PartialFunction[String, Unit] = { - case "a" ⇒ - case "b" ⇒ + case "a" => + case "b" => } - def method(s: String) = () ⇒ { + def method(s: String) = () => { println(s) Integer.parseInt(s) } diff --git a/akka-actor-tests/src/test/scala/akka/util/MessageBufferSpec.scala b/akka-actor-tests/src/test/scala/akka/util/MessageBufferSpec.scala index 9a58f7d558..3d2c8f2575 100644 --- a/akka-actor-tests/src/test/scala/akka/util/MessageBufferSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/util/MessageBufferSpec.scala @@ -51,11 +51,11 @@ class MessageBufferSpec extends WordSpec with Matchers { buffer.append("m2", "s2") buffer.append("m3", "s3") val sb1 = new StringBuilder() - buffer.foreach((m, s) ⇒ sb1.append(s"$m->$s:")) + buffer.foreach((m, s) => sb1.append(s"$m->$s:")) sb1.toString() should ===("m1->s1:m2->s2:m3->s3:") buffer.dropHead() val sb2 = new StringBuilder() - buffer.foreach((m, s) ⇒ sb2.append(s"$m->$s:")) + buffer.foreach((m, s) => sb2.append(s"$m->$s:")) sb2.toString() should ===("m2->s2:m3->s3:") } } @@ -89,8 +89,8 @@ class MessageBufferSpec extends WordSpec with Matchers { map.append("id2", "m22", "s22") map.totalSize should ===(4) val sb = new StringBuilder() - map.getOrEmpty("id1").foreach((m, s) ⇒ sb.append(s"id1->$m->$s:")) - map.getOrEmpty("id2").foreach((m, s) ⇒ sb.append(s"id2->$m->$s:")) + map.getOrEmpty("id1").foreach((m, s) => sb.append(s"id1->$m->$s:")) + map.getOrEmpty("id2").foreach((m, s) => sb.append(s"id2->$m->$s:")) sb.toString() should ===("id1->m11->s11:id1->m12->s12:id2->m21->s21:id2->m22->s22:") } } diff --git a/akka-actor-tests/src/test/scala/akka/util/PrettyDurationSpec.scala b/akka-actor-tests/src/test/scala/akka/util/PrettyDurationSpec.scala index 12a24ffcf4..32095aae56 100644 --- a/akka-actor-tests/src/test/scala/akka/util/PrettyDurationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/util/PrettyDurationSpec.scala @@ -13,22 +13,22 @@ class PrettyDurationSpec extends WordSpec with Matchers { import scala.concurrent.duration._ val cases: Seq[(Duration, String)] = - 9.nanos → "9.000 ns" :: - 95.nanos → "95.00 ns" :: - 999.nanos → "999.0 ns" :: - 1000.nanos → "1.000 μs" :: - 9500.nanos → "9.500 μs" :: - 9500.micros → "9.500 ms" :: - 9500.millis → "9.500 s" :: - 95.seconds → "1.583 min" :: - 95.minutes → "1.583 h" :: - 95.hours → "3.958 d" :: + 9.nanos -> "9.000 ns" :: + 95.nanos -> "95.00 ns" :: + 999.nanos -> "999.0 ns" :: + 1000.nanos -> "1.000 μs" :: + 9500.nanos -> "9.500 μs" :: + 9500.micros -> "9.500 ms" :: + 9500.millis -> "9.500 s" :: + 95.seconds -> "1.583 min" :: + 95.minutes -> "1.583 h" :: + 95.hours -> "3.958 d" :: Nil "PrettyDuration" should { cases foreach { - case (d, expectedValue) ⇒ + case (d, expectedValue) => s"print $d nanos as $expectedValue" in { d.pretty should ===(expectedValue) } diff --git a/akka-actor-tests/src/test/scala/akka/util/TokenBucketSpec.scala b/akka-actor-tests/src/test/scala/akka/util/TokenBucketSpec.scala index 9892375e66..c4e28b8a00 100644 --- a/akka-actor-tests/src/test/scala/akka/util/TokenBucketSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/util/TokenBucketSpec.scala @@ -74,7 +74,7 @@ class TokenBucketSpec extends AkkaSpec { val bucket = new TestBucket(1, 10) bucket.init() - for (time ← 0 to 100 by 10) { + for (time <- 0 to 100 by 10) { bucket.currentTime = time bucket.offer(1) should ===(0L) } @@ -195,11 +195,11 @@ class TokenBucketSpec extends AkkaSpec { val Debug = false for { - capacity ← List(0, 1, 5, 10) - period ← List(1, 3, 5) - arrivalPeriod ← List(1, 3, 5) - startTime ← List(Long.MinValue, -1L, 0L, Long.MaxValue) - maxCost ← List(1, 5, 10) + capacity <- List(0, 1, 5, 10) + period <- List(1, 3, 5) + arrivalPeriod <- List(1, 3, 5) + startTime <- List(Long.MinValue, -1L, 0L, Long.MaxValue) + maxCost <- List(1, 5, 10) } { val bucket = new TestBucket(capacity, period) @@ -212,7 +212,7 @@ class TokenBucketSpec extends AkkaSpec { var nextEmit = 0L var delaying = false - for (time ← 0 to 1000) { + for (time <- 0 to 1000) { if (untilNextTick == 0) { untilNextTick = period idealBucket = math.min(idealBucket + 1, capacity) diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/ActorContextSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/ActorContextSpec.scala index ae235ac90d..dfef579cde 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/ActorContextSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/ActorContextSpec.scala @@ -74,7 +74,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( import ActorSpecMessages._ - def decoration[T]: Behavior[T] ⇒ Behavior[T] + def decoration[T]: Behavior[T] => Behavior[T] implicit class BehaviorDecorator[T](behavior: Behavior[T])(implicit ev: ClassTag[T]) { def decorate: Behavior[T] = decoration[T](behavior) @@ -84,7 +84,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "be usable from Behavior.interpretMessage" in { // compilation only - lazy val b: Behavior[String] = Behaviors.receive { (context, message) ⇒ + lazy val b: Behavior[String] = Behaviors.receive { (context, message) => Behavior.interpretMessage(b, context, message) } } @@ -92,18 +92,18 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "canonicalize behaviors" in { val probe = TestProbe[Event]() - lazy val behavior: Behavior[Command] = Behaviors.receive[Command] { (_, message) ⇒ + lazy val behavior: Behavior[Command] = Behaviors.receive[Command] { (_, message) => message match { - case Ping ⇒ + case Ping => probe.ref ! Pong Behaviors.same - case Miss ⇒ + case Miss => probe.ref ! Missed Behaviors.unhandled - case Renew(ref) ⇒ + case Renew(ref) => ref ! Renewed behavior - case other ⇒ + case other => throw new RuntimeException(s"Unexpected message: $other") } }.decorate @@ -126,10 +126,10 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( val probe = TestProbe[Event]() val internal = (Behaviors.receivePartial[Command] { - case (_, Fail) ⇒ + case (_, Fail) => throw new TestException("Boom") } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behaviors.same }).decorate @@ -147,9 +147,9 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( val behavior: Behavior[Command] = ( Behaviors.receivePartial[Command] { - case (_, Stop) ⇒ Behaviors.stopped + case (_, Stop) => Behaviors.stopped } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behaviors.same }).decorate @@ -163,17 +163,17 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( val probe = TestProbe[Event]() val child: Behavior[Command] = (Behaviors.receivePartial[Command] { - case (_, Fail) ⇒ throw new TestException("Boom") - case (_, Ping) ⇒ + case (_, Fail) => throw new TestException("Boom") + case (_, Ping) => probe.ref ! Pong Behaviors.same } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! GotChildSignal(signal) Behavior.stopped }).decorate - val parent: Behavior[Command] = Behaviors.setup[Command](context ⇒ { + val parent: Behavior[Command] = Behaviors.setup[Command](context => { val childRef = context.spawnAnonymous( Behaviors.supervise(child).onFailure(SupervisorStrategy.restart) ) @@ -181,11 +181,11 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( probe.ref ! ChildMade(childRef) (Behaviors.receivePartial[Command] { - case (context, StopRef(ref)) ⇒ + case (context, StopRef(ref)) => context.stop(ref) Behavior.same } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behavior.stopped }).decorate @@ -207,16 +207,16 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( val probe = TestProbe[Event]() val child: Behavior[Command] = Behaviors.empty[Command].decorate - val parent: Behavior[Command] = Behaviors.setup[Command](context ⇒ { + val parent: Behavior[Command] = Behaviors.setup[Command](context => { val childRef = context.spawnAnonymous(child) context.watch(childRef) probe.ref ! ChildMade(childRef) Behaviors.receivePartial[Command] { - case (context, StopRef(ref)) ⇒ + case (context, StopRef(ref)) => context.stop(ref) Behaviors.same } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behavior.stopped } @@ -229,14 +229,14 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "reset behavior upon restart" in { val probe = TestProbe[Int]() - val internal = Behaviors.setup[Command](_ ⇒ { + val internal = Behaviors.setup[Command](_ => { var counter = 0 Behaviors.receivePartial[Command] { - case (_, Ping) ⇒ + case (_, Ping) => counter += 1 probe.ref ! counter Behavior.same - case (_, Fail) ⇒ + case (_, Fail) => throw new TestException("Boom") } }).decorate @@ -253,14 +253,14 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "not reset behavior upon resume" in { val probe = TestProbe[Int]() - val internal = Behaviors.setup[Command](_ ⇒ { + val internal = Behaviors.setup[Command](_ => { var counter = 0 Behaviors.receivePartial[Command] { - case (_, Ping) ⇒ + case (_, Ping) => counter += 1 probe.ref ! counter Behavior.same - case (_, Fail) ⇒ + case (_, Fail) => throw new TestException("Boom") } }).decorate @@ -278,25 +278,25 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "stop upon stop" in { val probe = TestProbe[Event]() val behavior = (Behaviors.receivePartial[Command] { - case (_, Ping) ⇒ + case (_, Ping) => probe.ref ! Pong Behaviors.same - case (_, Fail) ⇒ + case (_, Fail) => throw new TestException("boom") } receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => probe.ref ! ReceivedSignal(PostStop) Behavior.same }).decorate val actorToWatch = spawn(behavior) val watcher: ActorRef[Command] = spawn(( Behaviors.receivePartial[Any] { - case (context, Ping) ⇒ + case (context, Ping) => context.watch(actorToWatch) probe.ref ! Pong Behavior.same } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behavior.same } @@ -316,10 +316,10 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( val probe = TestProbe[Event]() val victim = spawn(Behaviors.empty[Command]) val actor = spawn(Behaviors.receivePartial[Command] { - case (_, Ping) ⇒ + case (_, Ping) => probe.ref ! Pong Behaviors.same - case (context, StopRef(ref)) ⇒ + case (context, StopRef(ref)) => assertThrows[IllegalArgumentException] { context.stop(ref) probe.ref ! Pong @@ -338,20 +338,20 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "watch a child actor before its termination" in { val probe = TestProbe[Event]() val child = Behaviors.receivePartial[Command] { - case (_, Stop) ⇒ + case (_, Stop) => Behaviors.stopped }.decorate spawn( - Behaviors.setup[Command](context ⇒ { + Behaviors.setup[Command](context => { val childRef = context.spawn(child, "A") context.watch(childRef) probe.ref ! ChildMade(childRef) Behaviors.receivePartial[Command] { - case (_, Ping) ⇒ + case (_, Ping) => probe.ref ! Pong Behaviors.same } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behaviors.same } @@ -365,20 +365,20 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "watch a child actor after its termination" in { val probe = TestProbe[Event]() val child = Behaviors.receivePartial[Command] { - case (_, Stop) ⇒ + case (_, Stop) => Behaviors.stopped }.decorate val actor = spawn( - Behaviors.setup[Command](context ⇒ { + Behaviors.setup[Command](context => { val childRef = context.spawn(child, "A") probe.ref ! ChildMade(childRef) Behaviors.receivePartial[Command] { - case (context, Watch(ref)) ⇒ + case (context, Watch(ref)) => context.watch(ref) probe.ref ! Pong Behaviors.same } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behaviors.same } @@ -396,24 +396,24 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "unwatch a child actor before its termination" in { val probe = TestProbe[Event]() val child = Behaviors.receivePartial[Command] { - case (_, Stop) ⇒ + case (_, Stop) => Behaviors.stopped }.decorate val actor = spawn( - Behaviors.setup[Command](context ⇒ { + Behaviors.setup[Command](context => { val childRef = context.spawn(child, "A") probe.ref ! ChildMade(childRef) Behaviors.receivePartial[Command] { - case (context, Watch(ref)) ⇒ + case (context, Watch(ref)) => context.watch(ref) probe.ref ! Pong Behaviors.same - case (context, UnWatch(ref)) ⇒ + case (context, UnWatch(ref)) => context.unwatch(ref) probe.ref ! Pong Behaviors.same } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behaviors.same } @@ -431,31 +431,31 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "terminate upon not handling Terminated" in { val probe = TestProbe[Event]() val child = (Behaviors.receivePartial[Command] { - case (_, Stop) ⇒ + case (_, Stop) => Behaviors.stopped } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! GotChildSignal(signal) Behavior.same }).decorate val actor = spawn( - Behaviors.setup[Command](context ⇒ { + Behaviors.setup[Command](context => { val childRef = context.spawn(child, "A") context.watch(childRef) probe.ref ! ChildMade(childRef) Behaviors.receivePartial[Command] { - case (_, Inert) ⇒ + case (_, Inert) => probe.ref ! InertEvent Behaviors.receive[Command] { - case (_, _) ⇒ Behaviors.unhandled + case (_, _) => Behaviors.unhandled } receiveSignal { - case (_, Terminated(_)) ⇒ Behaviors.unhandled - case (_, signal) ⇒ + case (_, Terminated(_)) => Behaviors.unhandled + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behaviors.same } } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => probe.ref ! ReceivedSignal(signal) Behaviors.same } @@ -476,8 +476,8 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( type Info = (ActorSystem[Nothing], ActorRef[String]) val probe = TestProbe[Info] val actor = spawn(Behaviors.receivePartial[String] { - case (context, "info") ⇒ - probe.ref ! (context.system → context.self) + case (context, "info") => + probe.ref ! (context.system -> context.self) Behaviors.same }.decorate) actor ! "info" @@ -488,14 +488,14 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( type Children = Seq[ActorRef[Nothing]] val probe = TestProbe[Children]() val actor = spawn(Behaviors.receivePartial[String] { - case (context, "create") ⇒ + case (context, "create") => context.spawn(Behaviors.empty, "B") probe.ref ! context.child("B").toSeq Behaviors.same - case (context, "all") ⇒ + case (context, "all") => probe.ref ! context.children.toSeq Behaviors.same - case (context, get) ⇒ + case (context, get) => probe.ref ! context.child(get).toSeq Behaviors.same }.decorate) @@ -512,10 +512,10 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "set small receive timeout" in { val probe = TestProbe[Event]() val actor = spawn(Behaviors.receivePartial[Command] { - case (_, ReceiveTimeout) ⇒ + case (_, ReceiveTimeout) => probe.ref ! GotReceiveTimeout Behaviors.same - case (context, SetTimeout(duration)) ⇒ + case (context, SetTimeout(duration)) => context.setReceiveTimeout(duration, ReceiveTimeout) probe.ref ! TimeoutSet Behaviors.same @@ -528,16 +528,16 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "set large receive timeout" in { val probe = TestProbe[String]() val actor = spawn(Behaviors.receivePartial[String] { - case (context, "schedule") ⇒ + case (context, "schedule") => context.scheduleOnce(1.second, probe.ref, "scheduled") Behaviors.same - case (_, "ping") ⇒ + case (_, "ping") => probe.ref ! "pong" Behaviors.same - case (_, "receive timeout") ⇒ + case (_, "receive timeout") => probe.ref ! "received timeout" Behaviors.same - case (context, duration) ⇒ + case (context, duration) => context.setReceiveTimeout(Duration(duration).asInstanceOf[FiniteDuration], "receive timeout") probe.ref ! "timeout set" Behaviors.same @@ -553,7 +553,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "schedule a message" in { val probe = TestProbe[Event]() val actor = spawn(Behaviors.receivePartial[Command] { - case (context, Ping) ⇒ + case (context, Ping) => context.scheduleOnce(1.nano, probe.ref, Pong) Behaviors.same }.decorate) @@ -566,10 +566,10 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( val messages = TestProbe[Envelope]() val probe = TestProbe[ActorRef[String]]() val actor = spawn(Behaviors.receivePartial[String] { - case (context, "message") ⇒ + case (context, "message") => messages.ref.tell((context.self, "received message")) Behaviors.same - case (context, name) ⇒ + case (context, name) => probe.ref ! context.spawnMessageAdapter(identity, name) Behaviors.same }.decorate) @@ -578,7 +578,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( val adapter = probe.receiveMessage() adapter.path.name should include(adapterName) adapter ! "message" - messages.expectMessage(actor → "received message") + messages.expectMessage(actor -> "received message") } "not allow null messages" in { @@ -591,11 +591,11 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( "not have problems stopping already stopped child" in { val probe = TestProbe[Event]() val actor = spawn( - Behaviors.setup[Command](context ⇒ { + Behaviors.setup[Command](context => { val child = context.spawnAnonymous(Behaviors.empty[Command]) probe.ref ! ChildMade(child) Behaviors.receivePartial[Command] { - case (context, StopRef(ref)) ⇒ + case (context, StopRef(ref)) => context.stop(ref) probe.ref ! Pong Behaviors.same @@ -614,22 +614,22 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit( class NormalActorContextSpec extends ActorContextSpec { - override def decoration[T] = x ⇒ x + override def decoration[T] = x => x } class WidenActorContextSpec extends ActorContextSpec { - override def decoration[T] = b ⇒ b.widen { case x ⇒ x } + override def decoration[T] = b => b.widen { case x => x } } class DeferredActorContextSpec extends ActorContextSpec { - override def decoration[T] = b ⇒ Behaviors.setup(_ ⇒ b) + override def decoration[T] = b => Behaviors.setup(_ => b) } class NestedDeferredActorContextSpec extends ActorContextSpec { - override def decoration[T] = b ⇒ Behaviors.setup(_ ⇒ Behaviors.setup(_ ⇒ b)) + override def decoration[T] = b => Behaviors.setup(_ => Behaviors.setup(_ => b)) } class InterceptActorContextSpec extends ActorContextSpec { @@ -642,5 +642,5 @@ class InterceptActorContextSpec extends ActorContextSpec { target(context, signal) } - override def decoration[T]: Behavior[T] ⇒ Behavior[T] = b ⇒ Behaviors.intercept[T, T](tap)(b) + override def decoration[T]: Behavior[T] => Behavior[T] = b => Behaviors.intercept[T, T](tap)(b) } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/AskSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/AskSpec.scala index 6b95aa35b5..98a62d7078 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/AskSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/AskSpec.scala @@ -42,10 +42,10 @@ class AskSpec extends ScalaTestWithActorTestKit(""" system.executionContext val behavior: Behavior[Msg] = receive[Msg] { - case (_, foo: Foo) ⇒ + case (_, foo: Foo) => foo.replyTo ! "foo" Behaviors.same - case (_, Stop(r)) ⇒ + case (_, Stop(r)) => r ! (()) Behaviors.stopped } @@ -93,10 +93,10 @@ class AskSpec extends ScalaTestWithActorTestKit(""" /** See issue #19947 (MatchError with adapted ActorRef) */ "fail the future if the actor doesn't exist" in { val noSuchActor: ActorRef[Msg] = system match { - case adaptedSys: ActorSystemAdapter[_] ⇒ + case adaptedSys: ActorSystemAdapter[_] => import akka.actor.typed.scaladsl.adapter._ adaptedSys.untypedSystem.provider.resolveActorRef("/foo/bar") - case _ ⇒ + case _ => fail("this test must only run in an adapted actor system") } @@ -120,7 +120,7 @@ class AskSpec extends ScalaTestWithActorTestKit(""" class LegacyActor extends akka.actor.Actor { def receive = { - case Ping(respondTo) ⇒ respondTo ! akka.actor.Status.Failure(ex) + case Ping(respondTo) => respondTo ! akka.actor.Status.Failure(ex) } } @@ -142,20 +142,20 @@ class AskSpec extends ScalaTestWithActorTestKit(""" val probe = TestProbe[AnyRef]("probe") val behv = Behaviors.receive[String] { - case (context, "start-ask") ⇒ + case (context, "start-ask") => context.ask[Question, Long](probe.ref)(Question(_)) { - case Success(42L) ⇒ + case Success(42L) => throw new RuntimeException("Unsupported number") - case _ ⇒ "test" + case _ => "test" } Behavior.same - case (_, "test") ⇒ + case (_, "test") => probe.ref ! "got-test" Behavior.same - case (_, "get-state") ⇒ + case (_, "get-state") => probe.ref ! "running" Behavior.same - case (_, _) ⇒ + case (_, _) => Behavior.unhandled } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/BehaviorSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/BehaviorSpec.scala index 4c2e5cd069..ab2f83b961 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/BehaviorSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/BehaviorSpec.scala @@ -4,12 +4,12 @@ package akka.actor.typed -import akka.actor.typed.scaladsl.{ Behaviors ⇒ SBehaviors } -import akka.actor.typed.scaladsl.{ AbstractBehavior ⇒ SAbstractBehavior } -import akka.actor.typed.javadsl.{ ActorContext ⇒ JActorContext, Behaviors ⇒ JBehaviors } -import akka.japi.function.{ Function ⇒ F1e, Function2 ⇒ F2, Procedure2 ⇒ P2 } +import akka.actor.typed.scaladsl.{ Behaviors => SBehaviors } +import akka.actor.typed.scaladsl.{ AbstractBehavior => SAbstractBehavior } +import akka.actor.typed.javadsl.{ ActorContext => JActorContext, Behaviors => JBehaviors } +import akka.japi.function.{ Function => F1e, Function2 => F2, Procedure2 => P2 } import akka.japi.pf.{ FI, PFBuilder } -import java.util.function.{ Function ⇒ F1 } +import java.util.function.{ Function => F1 } import akka.Done import akka.actor.testkit.typed.scaladsl.ScalaTestWithActorTestKit @@ -88,7 +88,7 @@ object BehaviorSpec { Init(behv, inbox, aux) } - def init(factory: ActorRef[Event] ⇒ (Behavior[Command], Aux)): Init = { + def init(factory: ActorRef[Event] => (Behavior[Command], Aux)): Init = { val inbox = TestInbox[Event]("evt") val (behv, aux) = factory(inbox.ref) Init(behv, inbox, aux) @@ -144,28 +144,28 @@ object BehaviorSpec { def mkFull(monitor: ActorRef[Event], state: State = StateA): Behavior[Command] = { SBehaviors.receive[Command] { - case (context, GetSelf) ⇒ + case (context, GetSelf) => monitor ! Self(context.self) SBehaviors.same - case (_, Miss) ⇒ + case (_, Miss) => monitor ! Missed SBehaviors.unhandled - case (_, Ignore) ⇒ + case (_, Ignore) => monitor ! Ignored SBehaviors.same - case (_, Ping) ⇒ + case (_, Ping) => monitor ! Pong mkFull(monitor, state) - case (_, Swap) ⇒ + case (_, Swap) => monitor ! Swapped mkFull(monitor, state.next) - case (_, GetState()) ⇒ + case (_, GetState()) => monitor ! state SBehaviors.same - case (_, Stop) ⇒ SBehaviors.stopped - case (_, _) ⇒ SBehaviors.unhandled + case (_, Stop) => SBehaviors.stopped + case (_, _) => SBehaviors.unhandled } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => monitor ! ReceivedSignal(signal) SBehaviors.same } @@ -173,31 +173,31 @@ object BehaviorSpec { /* * function converters for Java, to ease the pain on Scala 2.11 */ - def fs(f: (JActorContext[Command], Signal) ⇒ Behavior[Command]) = + def fs(f: (JActorContext[Command], Signal) => Behavior[Command]) = new F2[JActorContext[Command], Signal, Behavior[Command]] { override def apply(context: JActorContext[Command], sig: Signal) = f(context, sig) } - def fc(f: (JActorContext[Command], Command) ⇒ Behavior[Command]) = + def fc(f: (JActorContext[Command], Command) => Behavior[Command]) = new F2[JActorContext[Command], Command, Behavior[Command]] { override def apply(context: JActorContext[Command], command: Command) = f(context, command) } - def ps(f: (JActorContext[Command], Signal) ⇒ Unit) = + def ps(f: (JActorContext[Command], Signal) => Unit) = new P2[JActorContext[Command], Signal] { override def apply(context: JActorContext[Command], sig: Signal) = f(context, sig) } - def pc(f: (JActorContext[Command], Command) ⇒ Unit) = + def pc(f: (JActorContext[Command], Command) => Unit) = new P2[JActorContext[Command], Command] { override def apply(context: JActorContext[Command], command: Command) = f(context, command) } - def pf(f: PFBuilder[Command, Command] ⇒ PFBuilder[Command, Command]) = + def pf(f: PFBuilder[Command, Command] => PFBuilder[Command, Command]) = new F1[PFBuilder[Command, Command], PFBuilder[Command, Command]] { override def apply(in: PFBuilder[Command, Command]) = f(in) } - def fi(f: Command ⇒ Command) = + def fi(f: Command => Command) = new FI.Apply[Command, Command] { override def apply(in: Command) = f(in) } - def df(f: JActorContext[Command] ⇒ Behavior[Command]) = + def df(f: JActorContext[Command] => Behavior[Command]) = new F1e[JActorContext[Command], Behavior[Command]] { override def apply(in: JActorContext[Command]) = f(in) } @@ -343,35 +343,35 @@ object BehaviorSpec { import BehaviorSpec._ class FullBehaviorSpec extends ScalaTestWithActorTestKit with Messages with BecomeWithLifecycle with Stoppable { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = mkFull(monitor) → null + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = mkFull(monitor) -> null } class ReceiveBehaviorSpec extends Messages with BecomeWithLifecycle with Stoppable { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor, StateA) → null + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor, StateA) -> null private def behv(monitor: ActorRef[Event], state: State): Behavior[Command] = { SBehaviors.receive[Command] { - case (context, GetSelf) ⇒ + case (context, GetSelf) => monitor ! Self(context.self) SBehaviors.same - case (_, Miss) ⇒ + case (_, Miss) => monitor ! Missed SBehaviors.unhandled - case (_, Ignore) ⇒ + case (_, Ignore) => monitor ! Ignored SBehaviors.same - case (_, Ping) ⇒ + case (_, Ping) => monitor ! Pong behv(monitor, state) - case (_, Swap) ⇒ + case (_, Swap) => monitor ! Swapped behv(monitor, state.next) - case (_, GetState()) ⇒ + case (_, GetState()) => monitor ! state SBehaviors.same - case (_, Stop) ⇒ SBehaviors.stopped - case (_, _: AuxPing) ⇒ SBehaviors.unhandled + case (_, Stop) => SBehaviors.stopped + case (_, _: AuxPing) => SBehaviors.unhandled } receiveSignal { - case (_, signal) ⇒ + case (_, signal) => monitor ! ReceivedSignal(signal) SBehaviors.same } @@ -380,35 +380,35 @@ class ReceiveBehaviorSpec extends Messages with BecomeWithLifecycle with Stoppab class ImmutableWithSignalScalaBehaviorSpec extends Messages with BecomeWithLifecycle with Stoppable { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor) → null + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor) -> null def behv(monitor: ActorRef[Event], state: State = StateA): Behavior[Command] = SBehaviors.receive[Command] { - (context, message) ⇒ + (context, message) => message match { - case GetSelf ⇒ + case GetSelf => monitor ! Self(context.self) SBehaviors.same - case Miss ⇒ + case Miss => monitor ! Missed SBehaviors.unhandled - case Ignore ⇒ + case Ignore => monitor ! Ignored SBehaviors.same - case Ping ⇒ + case Ping => monitor ! Pong behv(monitor, state) - case Swap ⇒ + case Swap => monitor ! Swapped behv(monitor, state.next) - case GetState() ⇒ + case GetState() => monitor ! state SBehaviors.same - case Stop ⇒ SBehaviors.stopped - case _: AuxPing ⇒ SBehaviors.unhandled + case Stop => SBehaviors.stopped + case _: AuxPing => SBehaviors.unhandled } } receiveSignal { - case (_, sig) ⇒ + case (_, sig) => monitor ! ReceivedSignal(sig) SBehaviors.same } @@ -416,67 +416,67 @@ class ImmutableWithSignalScalaBehaviorSpec extends Messages with BecomeWithLifec class ImmutableScalaBehaviorSpec extends Messages with Become with Stoppable { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor, StateA) → null + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor, StateA) -> null def behv(monitor: ActorRef[Event], state: State): Behavior[Command] = - SBehaviors.receive[Command] { (context, message) ⇒ + SBehaviors.receive[Command] { (context, message) => message match { - case GetSelf ⇒ + case GetSelf => monitor ! Self(context.self) SBehaviors.same - case Miss ⇒ + case Miss => monitor ! Missed SBehaviors.unhandled - case Ignore ⇒ + case Ignore => monitor ! Ignored SBehaviors.same - case Ping ⇒ + case Ping => monitor ! Pong behv(monitor, state) - case Swap ⇒ + case Swap => monitor ! Swapped behv(monitor, state.next) - case GetState() ⇒ + case GetState() => monitor ! state SBehaviors.same - case Stop ⇒ SBehaviors.stopped - case _: AuxPing ⇒ SBehaviors.unhandled + case Stop => SBehaviors.stopped + case _: AuxPing => SBehaviors.unhandled } } } class MutableScalaBehaviorSpec extends Messages with Become with Stoppable { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor) → null + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor) -> null def behv(monitor: ActorRef[Event]): Behavior[Command] = - SBehaviors.setup[Command] { context ⇒ + SBehaviors.setup[Command] { context => new SAbstractBehavior[Command] { private var state: State = StateA override def onMessage(message: Command): Behavior[Command] = { message match { - case GetSelf ⇒ + case GetSelf => monitor ! Self(context.self) this - case Miss ⇒ + case Miss => monitor ! Missed SBehaviors.unhandled - case Ignore ⇒ + case Ignore => monitor ! Ignored SBehaviors.same // this or same works the same way - case Ping ⇒ + case Ping => monitor ! Pong this - case Swap ⇒ + case Swap => monitor ! Swapped state = state.next this - case GetState() ⇒ + case GetState() => monitor ! state this - case Stop ⇒ SBehaviors.stopped - case _: AuxPing ⇒ SBehaviors.unhandled + case Stop => SBehaviors.stopped + case _: AuxPing => SBehaviors.unhandled } } } @@ -487,7 +487,7 @@ class WidenedScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec with override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { val inbox = TestInbox[Command]("widenedListener") - super.behavior(monitor)._1.widen[Command] { case c ⇒ inbox.ref ! c; c } → inbox + super.behavior(monitor)._1.widen[Command] { case c => inbox.ref ! c; c } -> inbox } } @@ -496,7 +496,7 @@ class DeferredScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { val inbox = TestInbox[Done]("deferredListener") - (SBehaviors.setup(_ ⇒ { + (SBehaviors.setup(_ => { inbox.ref ! Done super.behavior(monitor)._1 }), inbox) @@ -528,68 +528,68 @@ class InterceptScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec wi class RestarterScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec with Reuse { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { - SBehaviors.supervise(super.behavior(monitor)._1).onFailure(SupervisorStrategy.restart) → null + SBehaviors.supervise(super.behavior(monitor)._1).onFailure(SupervisorStrategy.restart) -> null } } class ImmutableWithSignalJavaBehaviorSpec extends Messages with BecomeWithLifecycle with Stoppable { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor) → null + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor) -> null def behv(monitor: ActorRef[Event], state: State = StateA): Behavior[Command] = JBehaviors.receive( - fc((context, message) ⇒ message match { - case GetSelf ⇒ + fc((context, message) => message match { + case GetSelf => monitor ! Self(context.getSelf) SBehaviors.same - case Miss ⇒ + case Miss => monitor ! Missed SBehaviors.unhandled - case Ignore ⇒ + case Ignore => monitor ! Ignored SBehaviors.same - case Ping ⇒ + case Ping => monitor ! Pong behv(monitor, state) - case Swap ⇒ + case Swap => monitor ! Swapped behv(monitor, state.next) - case GetState() ⇒ + case GetState() => monitor ! state SBehaviors.same - case Stop ⇒ SBehaviors.stopped - case _: AuxPing ⇒ SBehaviors.unhandled + case Stop => SBehaviors.stopped + case _: AuxPing => SBehaviors.unhandled }), - fs((_, sig) ⇒ { + fs((_, sig) => { monitor ! ReceivedSignal(sig) SBehaviors.same })) } class ImmutableJavaBehaviorSpec extends Messages with Become with Stoppable { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor, StateA) → null + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor, StateA) -> null def behv(monitor: ActorRef[Event], state: State): Behavior[Command] = JBehaviors.receive { - fc((context, message) ⇒ + fc((context, message) => message match { - case GetSelf ⇒ + case GetSelf => monitor ! Self(context.getSelf) SBehaviors.same - case Miss ⇒ + case Miss => monitor ! Missed SBehaviors.unhandled - case Ignore ⇒ + case Ignore => monitor ! Ignored SBehaviors.same - case Ping ⇒ + case Ping => monitor ! Pong behv(monitor, state) - case Swap ⇒ + case Swap => monitor ! Swapped behv(monitor, state.next) - case GetState() ⇒ + case GetState() => monitor ! state SBehaviors.same - case Stop ⇒ SBehaviors.stopped - case _: AuxPing ⇒ SBehaviors.unhandled + case Stop => SBehaviors.stopped + case _: AuxPing => SBehaviors.unhandled }) } } @@ -597,10 +597,10 @@ class ImmutableJavaBehaviorSpec extends Messages with Become with Stoppable { class WidenedJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse with Siphon { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { val inbox = TestInbox[Command]("widenedListener") - JBehaviors.widened(super.behavior(monitor)._1, pf(_.`match`(classOf[Command], fi(x ⇒ { + JBehaviors.widened(super.behavior(monitor)._1, pf(_.`match`(classOf[Command], fi(x => { inbox.ref ! x x - })))) → inbox + })))) -> inbox } } @@ -609,7 +609,7 @@ class DeferredJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { val inbox = TestInbox[Done]("deferredListener") - (JBehaviors.setup(df(_ ⇒ { + (JBehaviors.setup(df(_ => { inbox.ref ! Done super.behavior(monitor)._1 })), inbox) @@ -642,6 +642,6 @@ class TapJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse class RestarterJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { JBehaviors.supervise(super.behavior(monitor)._1) - .onFailure(classOf[Exception], SupervisorStrategy.restart) → null + .onFailure(classOf[Exception], SupervisorStrategy.restart) -> null } } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/DeferredSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/DeferredSpec.scala index e43523ed88..d4d3b66f93 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/DeferredSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/DeferredSpec.scala @@ -22,8 +22,8 @@ object DeferredSpec { case object Started extends Event def target(monitor: ActorRef[Event]): Behavior[Command] = - Behaviors.receive((_, cmd) ⇒ cmd match { - case Ping ⇒ + Behaviors.receive((_, cmd) => cmd match { + case Ping => monitor ! Pong Behaviors.same }) @@ -44,7 +44,7 @@ class DeferredSpec extends ScalaTestWithActorTestKit( "Deferred behavior" must { "must create underlying" in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.setup[Command] { _ => probe.ref ! Started target(probe.ref) } @@ -56,14 +56,14 @@ class DeferredSpec extends ScalaTestWithActorTestKit( "must stop when exception from factory" in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.setup[Command] { context ⇒ - val child = context.spawnAnonymous(Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.setup[Command] { context => + val child = context.spawnAnonymous(Behaviors.setup[Command] { _ => probe.ref ! Started throw new RuntimeException("simulated exc from factory") with NoStackTrace }) context.watch(child) - Behaviors.receive[Command]((_, _) ⇒ Behaviors.same).receiveSignal { - case (_, Terminated(`child`)) ⇒ + Behaviors.receive[Command]((_, _) => Behaviors.same).receiveSignal { + case (_, Terminated(`child`)) => probe.ref ! Pong Behaviors.stopped } @@ -77,11 +77,11 @@ class DeferredSpec extends ScalaTestWithActorTestKit( "must stop when deferred result it Stopped" in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.setup[Command] { context ⇒ - val child = context.spawnAnonymous(Behaviors.setup[Command](_ ⇒ Behaviors.stopped)) + val behv = Behaviors.setup[Command] { context => + val child = context.spawnAnonymous(Behaviors.setup[Command](_ => Behaviors.stopped)) context.watch(child) - Behaviors.receive[Command]((_, _) ⇒ Behaviors.same).receiveSignal { - case (_, Terminated(`child`)) ⇒ + Behaviors.receive[Command]((_, _) => Behaviors.same).receiveSignal { + case (_, Terminated(`child`)) => probe.ref ! Pong Behaviors.stopped } @@ -92,8 +92,8 @@ class DeferredSpec extends ScalaTestWithActorTestKit( "must create underlying when nested" in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.setup[Command] { _ ⇒ - Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.setup[Command] { _ => + Behaviors.setup[Command] { _ => probe.ref ! Started target(probe.ref) } @@ -104,11 +104,11 @@ class DeferredSpec extends ScalaTestWithActorTestKit( "must un-defer underlying when wrapped by widen" in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.setup[Command] { _ => probe.ref ! Started target(probe.ref) }.widen[Command] { - case m ⇒ m + case m => m } probe.expectNoMessage() // not yet val ref = spawn(behv) @@ -122,7 +122,7 @@ class DeferredSpec extends ScalaTestWithActorTestKit( // monitor is implemented with tap, so this is testing both val probe = TestProbe[Event]("evt") val monitorProbe = TestProbe[Command]("monitor") - val behv = Behaviors.monitor(monitorProbe.ref, Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.monitor(monitorProbe.ref, Behaviors.setup[Command] { _ => probe.ref ! Started target(probe.ref) }) @@ -137,8 +137,8 @@ class DeferredSpec extends ScalaTestWithActorTestKit( "must not allow setup(same)" in { val probe = TestProbe[Any]() - val behv = Behaviors.setup[Command] { _ ⇒ - Behaviors.setup[Command] { _ ⇒ Behaviors.same } + val behv = Behaviors.setup[Command] { _ => + Behaviors.setup[Command] { _ => Behaviors.same } } EventFilter[ActorInitializationException](occurrences = 1).intercept { val ref = spawn(behv) @@ -154,7 +154,7 @@ class DeferredStubbedSpec extends WordSpec with Matchers { "must create underlying deferred behavior immediately" in { val inbox = TestInbox[Event]("evt") - val behv = Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.setup[Command] { _ => inbox.ref ! Started target(inbox.ref) } @@ -166,7 +166,7 @@ class DeferredStubbedSpec extends WordSpec with Matchers { "must stop when exception from factory" in { val inbox = TestInbox[Event]("evt") val exc = new RuntimeException("simulated exc from factory") with NoStackTrace - val behv = Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.setup[Command] { _ => inbox.ref ! Started throw exc } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/ExtensionsSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/ExtensionsSpec.scala index 99a9a73864..3c2e45869a 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/ExtensionsSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/ExtensionsSpec.scala @@ -19,7 +19,7 @@ object DummyExtension1 extends ExtensionId[DummyExtension1] { def createExtension(system: ActorSystem[_]) = new DummyExtension1 def get(system: ActorSystem[_]): DummyExtension1 = apply(system) } -class DummyExtension1Setup(factory: ActorSystem[_] ⇒ DummyExtension1) +class DummyExtension1Setup(factory: ActorSystem[_] => DummyExtension1) extends AbstractExtensionSetup[DummyExtension1](DummyExtension1, factory) class DummyExtension1ViaSetup extends DummyExtension1 @@ -65,7 +65,7 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { "The extensions subsystem" must { "return the same instance for the same id" in - withEmptyActorSystem("ExtensionsSpec01") { sys ⇒ + withEmptyActorSystem("ExtensionsSpec01") { sys => val instance1 = sys.registerExtension(DummyExtension1) val instance2 = sys.registerExtension(DummyExtension1) @@ -79,10 +79,10 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { } "return the same instance for the same id concurrently" in - withEmptyActorSystem("ExtensionsSpec02") { sys ⇒ + withEmptyActorSystem("ExtensionsSpec02") { sys => // not exactly water tight but better than nothing import sys.executionContext - val futures = (0 to 1000).map(n ⇒ + val futures = (0 to 1000).map(n => Future { sys.registerExtension(SlowExtension) } @@ -90,7 +90,7 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { val instances = Future.sequence(futures).futureValue - instances.reduce { (a, b) ⇒ + instances.reduce { (a, b) => a should be theSameInstanceAs b b } @@ -101,7 +101,7 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { """ akka.actor.typed.extensions = ["akka.actor.typed.DummyExtension1$", "akka.actor.typed.SlowExtension$"] """)) - ) { sys ⇒ + ) { sys => sys.hasExtension(DummyExtension1) should ===(true) sys.extension(DummyExtension1) shouldBe a[DummyExtension1] @@ -127,7 +127,7 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { } "support multiple instances of the same type of extension (with different ids)" in - withEmptyActorSystem("ExtensionsSpec06") { sys ⇒ + withEmptyActorSystem("ExtensionsSpec06") { sys => val id1 = new MultiExtensionId(1) val id2 = new MultiExtensionId(2) @@ -137,7 +137,7 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { } "allow for auto-loading of library-extensions" in - withEmptyActorSystem("ExtensionsSpec06") { sys ⇒ + withEmptyActorSystem("ExtensionsSpec06") { sys => val listedExtensions = sys.settings.config.getStringList("akka.actor.typed.library-extensions") listedExtensions.size should be > 0 // could be initialized by other tests, so at least once @@ -149,7 +149,7 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { withEmptyActorSystem( "ExtensionsSpec07", Some(ConfigFactory.parseString("""akka.actor.typed.library-extensions += "akka.actor.typed.FailingToLoadExtension$"""")) - ) { _ ⇒ () } + ) { _ => () } } "fail the system if a library-extension is missing" in @@ -157,11 +157,11 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { withEmptyActorSystem( "ExtensionsSpec08", Some(ConfigFactory.parseString("""akka.actor.typed.library-extensions += "akka.actor.typed.MissingExtension"""")) - ) { _ ⇒ () } + ) { _ => () } } "load an extension implemented in Java" in - withEmptyActorSystem("ExtensionsSpec09") { sys ⇒ + withEmptyActorSystem("ExtensionsSpec09") { sys => // no way to make apply work cleanly with extensions implemented in Java val instance1 = ExtensionsTest.MyExtension.get(sys) val instance2 = ExtensionsTest.MyExtension.get(sys) @@ -206,8 +206,8 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { """ akka.actor.typed.extensions = ["akka.actor.typed.DummyExtension1$", "akka.actor.typed.SlowExtension$"] """)), - Some(ActorSystemSetup(new DummyExtension1Setup(sys ⇒ new DummyExtension1ViaSetup))) - ) { sys ⇒ + Some(ActorSystemSetup(new DummyExtension1Setup(sys => new DummyExtension1ViaSetup))) + ) { sys => sys.hasExtension(DummyExtension1) should ===(true) sys.extension(DummyExtension1) shouldBe a[DummyExtension1ViaSetup] DummyExtension1(sys) shouldBe a[DummyExtension1ViaSetup] @@ -219,15 +219,15 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike { } def withEmptyActorSystem[T](name: String, config: Option[Config] = None, setup: Option[ActorSystemSetup] = None)( - f: ActorSystem[_] ⇒ T): T = { + f: ActorSystem[_] => T): T = { val bootstrap = config match { - case Some(c) ⇒ BootstrapSetup(c) - case None ⇒ BootstrapSetup(ExtensionsSpec.config) + case Some(c) => BootstrapSetup(c) + case None => BootstrapSetup(ExtensionsSpec.config) } val sys = setup match { - case None ⇒ ActorSystem[Any](Behavior.EmptyBehavior, name, bootstrap) - case Some(s) ⇒ ActorSystem[Any](Behavior.EmptyBehavior, name, s.and(bootstrap)) + case None => ActorSystem[Any](Behavior.EmptyBehavior, name, bootstrap) + case Some(s) => ActorSystem[Any](Behavior.EmptyBehavior, name, s.and(bootstrap)) } try f(sys) finally sys.terminate().futureValue diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/InterceptSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/InterceptSpec.scala index 0ff14a8220..cdcaf1b028 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/InterceptSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/InterceptSpec.scala @@ -54,7 +54,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( val ref: ActorRef[String] = spawn(Behaviors.intercept( interceptor)( - Behaviors.receiveMessage[String] { m ⇒ + Behaviors.receiveMessage[String] { m => probe.ref ! s"actual behavior $m" Behaviors.same } @@ -79,7 +79,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( val beh: Behavior[String] = intercept( intercept( - Behaviors.receiveMessage(m ⇒ + Behaviors.receiveMessage(m => Behaviors.same ) ) @@ -100,7 +100,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( def next(count: Int): Behavior[String] = Behaviors.intercept( interceptor)( - Behaviors.receiveMessage(m ⇒ + Behaviors.receiveMessage(m => next(count + 1) ) ) @@ -132,7 +132,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( val beh: Behavior[String] = intercept( intercept( - Behaviors.receiveMessage(m ⇒ + Behaviors.receiveMessage(m => Behaviors.same ) ) @@ -155,7 +155,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( Behaviors.intercept( // a new instance every "recursion" snitchingInterceptor(probe.ref))( - Behaviors.receiveMessage(m ⇒ + Behaviors.receiveMessage(m => next(count + 1) ) ) @@ -188,7 +188,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( } val innerBehaviorStarted = new AtomicBoolean(false) - val ref = spawn(Behaviors.intercept(interceptor)(Behaviors.setup { context ⇒ + val ref = spawn(Behaviors.intercept(interceptor)(Behaviors.setup { context => innerBehaviorStarted.set(true) Behaviors.unhandled[String] })) @@ -203,9 +203,9 @@ class InterceptSpec extends ScalaTestWithActorTestKit( val interceptor = snitchingInterceptor(probe.ref) val ref: ActorRef[String] = spawn(Behaviors.intercept(interceptor)( - Behaviors.setup { _ ⇒ + Behaviors.setup { _ => var count = 0 - Behaviors.receiveMessage[String] { m ⇒ + Behaviors.receiveMessage[String] { m => count += 1 probe.ref ! s"actual behavior $m-$count" Behaviors.same @@ -230,9 +230,9 @@ class InterceptSpec extends ScalaTestWithActorTestKit( def next(count1: Int): Behavior[String] = { Behaviors.intercept(interceptor)( - Behaviors.setup { _ ⇒ + Behaviors.setup { _ => var count2 = 0 - Behaviors.receiveMessage[String] { m ⇒ + Behaviors.receiveMessage[String] { m => count2 += 1 probe.ref ! s"actual behavior $m-$count1-$count2" next(count1 + 1) @@ -265,7 +265,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( EventFilter[ActorInitializationException](occurrences = 1).intercept { val ref = spawn(Behaviors.intercept(interceptor)( - Behaviors.setup[String] { _ ⇒ Behaviors.same[String] })) + Behaviors.setup[String] { _ => Behaviors.same[String] })) probe.expectTerminated(ref, probe.remainingOrDefault) } @@ -274,7 +274,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( "be useful for implementing PoisonPill" in { def inner(count: Int): Behavior[Msg] = Behaviors.receiveMessage { - case Msg(hello, replyTo) ⇒ + case Msg(hello, replyTo) => replyTo ! s"$hello-$count" inner(count + 1) } @@ -282,9 +282,9 @@ class InterceptSpec extends ScalaTestWithActorTestKit( val poisonInterceptor = new BehaviorInterceptor[Any, Msg] { override def aroundReceive(context: TypedActorContext[Any], message: Any, target: ReceiveTarget[Msg]): Behavior[Msg] = message match { - case MyPoisonPill ⇒ Behaviors.stopped - case m: Msg ⇒ target(context, m) - case _ ⇒ Behaviors.unhandled + case MyPoisonPill => Behaviors.stopped + case m: Msg => target(context, m) + case _ => Behaviors.unhandled } override def aroundSignal(context: TypedActorContext[Any], signal: Signal, target: SignalTarget[Msg]): Behavior[Msg] = @@ -328,7 +328,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit( } val probe = TestProbe[Message]() - val ref = spawn(Behaviors.intercept(partialInterceptor)(Behaviors.receiveMessage { msg ⇒ + val ref = spawn(Behaviors.intercept(partialInterceptor)(Behaviors.receiveMessage { msg => probe.ref ! msg Behaviors.same })) diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/LogMessagesSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/LogMessagesSpec.scala index 4d6840aaf9..f4f23e4cbb 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/LogMessagesSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/LogMessagesSpec.scala @@ -79,11 +79,11 @@ class LogMessagesSpec extends ScalaTestWithActorTestKit(""" val ref = spawn(behavior) EventFilter.custom({ - case logEvent if logEvent.level == Logging.DebugLevel ⇒ + case logEvent if logEvent.level == Logging.DebugLevel => logEvent.message should ===("received message Hello") logEvent.mdc should ===(Map("mdc" -> true)) true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! "Hello" } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/MonitorSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/MonitorSpec.scala index 53010320cf..055cf324f7 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/MonitorSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/MonitorSpec.scala @@ -16,7 +16,7 @@ class MonitorSpec extends ScalaTestWithActorTestKit with WordSpecLike { "monitor messages" in { val probe = TestProbe[String]() - val beh: Behavior[String] = Behaviors.monitor(probe.ref, Behaviors.receiveMessage(message ⇒ + val beh: Behavior[String] = Behaviors.monitor(probe.ref, Behaviors.receiveMessage(message => Behaviors.same )) val ref: ActorRef[String] = spawn(beh) @@ -35,7 +35,7 @@ class MonitorSpec extends ScalaTestWithActorTestKit with WordSpecLike { val beh: Behavior[String] = monitor( monitor( - Behaviors.receiveMessage(message ⇒ + Behaviors.receiveMessage(message => Behaviors.same ) ) @@ -55,7 +55,7 @@ class MonitorSpec extends ScalaTestWithActorTestKit with WordSpecLike { Behaviors.monitor(probe.ref, beh) def next: Behavior[String] = - monitor(Behaviors.receiveMessage(message ⇒ next)) + monitor(Behaviors.receiveMessage(message => next)) val ref: ActorRef[String] = spawn(next) ref ! "message 1" diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/OrElseSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/OrElseSpec.scala index f6b2f44008..74389ec3d5 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/OrElseSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/OrElseSpec.scala @@ -21,22 +21,22 @@ object OrElseStubbedSpec { def ping(counters: Map[String, Int]): Behavior[Ping] = { val ping1: Behavior[Ping] = Behaviors.receiveMessagePartial { - case Ping1(replyTo: ActorRef[Pong]) ⇒ + case Ping1(replyTo: ActorRef[Pong]) => val newCounters = counters.updated("ping1", counters.getOrElse("ping1", 0) + 1) replyTo ! Pong(newCounters("ping1")) ping(newCounters) } val ping2: Behavior[Ping] = Behaviors.receiveMessage { - case Ping2(replyTo: ActorRef[Pong]) ⇒ + case Ping2(replyTo: ActorRef[Pong]) => val newCounters = counters.updated("ping2", counters.getOrElse("ping2", 0) + 1) replyTo ! Pong(newCounters("ping2")) ping(newCounters) - case _ ⇒ Behaviors.unhandled + case _ => Behaviors.unhandled } val ping3: Behavior[Ping] = Behaviors.receiveMessagePartial { - case Ping3(replyTo: ActorRef[Pong]) ⇒ + case Ping3(replyTo: ActorRef[Pong]) => val newCounters = counters.updated("ping3", counters.getOrElse("ping3", 0) + 1) replyTo ! Pong(newCounters("ping3")) ping(newCounters) @@ -84,8 +84,8 @@ class OrElseSpec extends ScalaTestWithActorTestKit with WordSpecLike { "Behavior.orElse" must { "work for deferred behavior on the left" in { - val orElseDeferred = Behaviors.setup[Ping] { _ ⇒ - Behaviors.receiveMessage { _ ⇒ + val orElseDeferred = Behaviors.setup[Ping] { _ => + Behaviors.receiveMessage { _ => Behaviors.unhandled } }.orElse(ping(Map.empty)) @@ -98,9 +98,9 @@ class OrElseSpec extends ScalaTestWithActorTestKit with WordSpecLike { } "work for deferred behavior on the right" in { - val orElseDeferred = ping(Map.empty).orElse(Behaviors.setup { _ ⇒ + val orElseDeferred = ping(Map.empty).orElse(Behaviors.setup { _ => Behaviors.receiveMessage { - case PingInfinite(replyTo) ⇒ + case PingInfinite(replyTo) => replyTo ! Pong(-1) Behaviors.same } @@ -123,20 +123,20 @@ class OrElseSpec extends ScalaTestWithActorTestKit with WordSpecLike { def dealer(set: Set[Any]): Behavior[Parent] = { val add = Behaviors.receiveMessage[Parent] { - case Add(o) ⇒ dealer(set + o) - case _ ⇒ Behaviors.unhandled + case Add(o) => dealer(set + o) + case _ => Behaviors.unhandled } val remove = Behaviors.receiveMessage[Parent] { - case Remove(o) ⇒ dealer(set - o) - case _ ⇒ Behaviors.unhandled + case Remove(o) => dealer(set - o) + case _ => Behaviors.unhandled } val getStack = Behaviors.receiveMessagePartial[Parent] { - case Stack(sender) ⇒ + case Stack(sender) => sender ! Thread.currentThread().getStackTrace Behaviors.same } val getSet = Behaviors.receiveMessagePartial[Parent] { - case Get(sender) ⇒ + case Get(sender) => sender ! set Behaviors.same } @@ -145,10 +145,10 @@ class OrElseSpec extends ScalaTestWithActorTestKit with WordSpecLike { val y = spawn(dealer(Set.empty)) - (0 to 10000) foreach { i ⇒ + (0 to 10000) foreach { i => y ! Add(i) } - (0 to 9999) foreach { i ⇒ + (0 to 9999) foreach { i => y ! Remove(i) } val probe = TestProbe[Set[Any]] diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/SpawnProtocolSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/SpawnProtocolSpec.scala index 0ad0ecc21b..6968ede558 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/SpawnProtocolSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/SpawnProtocolSpec.scala @@ -18,7 +18,7 @@ object SpawnProtocolSpec { val target: Behavior[Message] = Behaviors.receiveMessage { - case Ping(replyTo) ⇒ + case Ping(replyTo) => replyTo ! Pong Behaviors.same } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/SupervisionSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/SupervisionSpec.scala index b4081943d8..3f975a12d2 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/SupervisionSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/SupervisionSpec.scala @@ -43,30 +43,30 @@ object SupervisionSpec { class Exc3(message: String = "exc-3") extends RuntimeException(message) with NoStackTrace def targetBehavior(monitor: ActorRef[Event], state: State = State(0, Map.empty), slowStop: Option[CountDownLatch] = None): Behavior[Command] = - receive[Command] { (context, cmd) ⇒ + receive[Command] { (context, cmd) => cmd match { - case Ping(n) ⇒ + case Ping(n) => monitor ! Pong(n) Behaviors.same - case IncrementState ⇒ + case IncrementState => targetBehavior(monitor, state.copy(n = state.n + 1), slowStop) - case GetState ⇒ - val reply = state.copy(children = context.children.map(c ⇒ c.path.name → c.unsafeUpcast[Command]).toMap) + case GetState => + val reply = state.copy(children = context.children.map(c => c.path.name -> c.unsafeUpcast[Command]).toMap) monitor ! reply Behaviors.same - case CreateChild(childBehv, childName) ⇒ + case CreateChild(childBehv, childName) => context.spawn(childBehv, childName) Behaviors.same - case Watch(ref) ⇒ + case Watch(ref) => context.watch(ref) Behaviors.same - case Throw(e) ⇒ + case Throw(e) => throw e } } receiveSignal { - case (_, sig) ⇒ + case (_, sig) => if (sig == PostStop) - slowStop.foreach(latch ⇒ latch.await(10, TimeUnit.SECONDS)) + slowStop.foreach(latch => latch.await(10, TimeUnit.SECONDS)) monitor ! ReceivedSignal(sig) Behaviors.same } @@ -235,7 +235,7 @@ class StubbedSupervisionSpec extends WordSpec with Matchers { "create underlying deferred behavior immediately" in { val inbox = TestInbox[Event]("evt") - val behv = supervise(setup[Command] { _ ⇒ + val behv = supervise(setup[Command] { _ => inbox.ref ! Started targetBehavior(inbox.ref) }).onFailure[Exc1](SupervisorStrategy.restart) @@ -280,7 +280,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( class FailingDeferredTestSetup(failCount: Int, strategy: SupervisorStrategy) { val probe = TestProbe[AnyRef]("evt") val failCounter = new AtomicInteger(0) - def behv = supervise(setup[Command] { _ ⇒ + def behv = supervise(setup[Command] { _ => val count = failCounter.getAndIncrement() if (count < failCount) { probe.ref ! StartFailed @@ -294,7 +294,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( class FailingUnhandledTestSetup(strategy: SupervisorStrategy) { val probe = TestProbe[AnyRef]("evt") - def behv = supervise(setup[Command] { _ ⇒ + def behv = supervise(setup[Command] { _ => probe.ref ! StartFailed throw new TestException("construction failed") }).onFailure[IllegalArgumentException](strategy) @@ -323,7 +323,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( "stop when strategy is stop - exception in setup" in { val probe = TestProbe[Event]("evt") - val failedSetup = Behaviors.setup[Command](_ ⇒ { + val failedSetup = Behaviors.setup[Command](_ => { throw new Exc3() targetBehavior(probe.ref) }) @@ -634,7 +634,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( val slowStop2 = new CountDownLatch(1) val throwFromSetup = new AtomicBoolean(true) val behv = Behaviors.supervise { - Behaviors.setup[Command] { ctx ⇒ + Behaviors.setup[Command] { ctx => ctx.spawn(targetBehavior(child1Probe.ref, slowStop = Some(slowStop1)), "child1") if (throwFromSetup.get()) { // note that this second child waiting on slowStop2 will prevent a restart loop that could exhaust the @@ -677,7 +677,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( val slowStop2 = new CountDownLatch(1) val throwFromSetup = new AtomicBoolean(false) val behv = Behaviors.supervise { - Behaviors.setup[Command] { ctx ⇒ + Behaviors.setup[Command] { ctx => ctx.spawn(targetBehavior(child1Probe.ref, slowStop = Some(slowStop1)), "child1") if (throwFromSetup.get()) { // note that this second child waiting on slowStop2 will prevent a restart loop that could exhaust the @@ -771,7 +771,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( val minBackoff = 1.seconds val strategy = SupervisorStrategy .restartWithBackoff(minBackoff, minBackoff, 0.0).withStashCapacity(2) - val behv = Behaviors.supervise(Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.supervise(Behaviors.setup[Command] { _ => startedProbe.ref ! Started targetBehavior(probe.ref) }).onFailure[Exception](strategy) @@ -802,7 +802,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( .restartWithBackoff(minBackoff, 10.seconds, 0.0) .withResetBackoffAfter(10.seconds) .withStashCapacity(0) - val behv = Behaviors.supervise(Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.supervise(Behaviors.setup[Command] { _ => startedProbe.ref ! Started targetBehavior(probe.ref) }).onFailure[Exception](strategy) @@ -847,13 +847,13 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( .withResetBackoffAfter(10.seconds) val alreadyStarted = new AtomicBoolean(false) - val behv = Behaviors.supervise(Behaviors.setup[Command] { _ ⇒ + val behv = Behaviors.supervise(Behaviors.setup[Command] { _ => if (alreadyStarted.get()) throw TestException("failure to restart") alreadyStarted.set(true) startedProbe.ref ! Started Behaviors.receiveMessagePartial { - case Throw(boom) ⇒ throw boom + case Throw(boom) => throw boom } }).onFailure[Exception](strategy) val ref = spawn(behv) @@ -904,7 +904,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( "create underlying deferred behavior immediately" in { val probe = TestProbe[Event]("evt") - val behv = supervise(setup[Command] { _ ⇒ + val behv = supervise(setup[Command] { _ => probe.ref ! Started targetBehavior(probe.ref) }).onFailure[Exception](SupervisorStrategy.restart) @@ -1008,7 +1008,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( "fail when exception from AbstractBehavior constructor" in new FailingConstructorTestSetup(failCount = 1) { val probe = TestProbe[Event]("evt") - val behv = supervise(setup[Command](_ ⇒ new FailingConstructor(probe.ref))) + val behv = supervise(setup[Command](_ => new FailingConstructor(probe.ref))) .onFailure[Exception](SupervisorStrategy.restart) EventFilter[ActorInitializationException](occurrences = 1).intercept { @@ -1020,8 +1020,8 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( "work with nested supervisions and defers" in { val strategy = SupervisorStrategy.restart.withLimit(3, 1.second) val probe = TestProbe[AnyRef]("p") - val beh = supervise[String](setup(_ ⇒ - supervise[String](setup { _ ⇒ + val beh = supervise[String](setup(_ => + supervise[String](setup { _ => probe.ref ! Started Behaviors.empty[String] }).onFailure[RuntimeException](strategy) @@ -1034,19 +1034,19 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( "replace supervision when new returned behavior catches same exception" in { val probe = TestProbe[AnyRef]("probeMcProbeFace") val behv = supervise[String](Behaviors.receiveMessage { - case "boom" ⇒ throw TestException("boom indeed") - case "switch" ⇒ + case "boom" => throw TestException("boom indeed") + case "switch" => supervise[String]( supervise[String]( supervise[String]( supervise[String]( supervise[String]( Behaviors.receiveMessage { - case "boom" ⇒ throw TestException("boom indeed") - case "ping" ⇒ + case "boom" => throw TestException("boom indeed") + case "ping" => probe.ref ! "pong" Behaviors.same - case "give me stacktrace" ⇒ + case "give me stacktrace" => probe.ref ! new RuntimeException().getStackTrace.toVector Behaviors.stopped }).onFailure[RuntimeException](SupervisorStrategy.resume) @@ -1087,19 +1087,19 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( } val behv = supervise[String](Behaviors.receiveMessage { - case "boom" ⇒ throw TestException("boom indeed") - case "switch" ⇒ + case "boom" => throw TestException("boom indeed") + case "switch" => supervise[String]( - setup(_ ⇒ + setup(_ => supervise[String]( Behaviors.intercept(whateverInterceptor)( supervise[String]( Behaviors.receiveMessage { - case "boom" ⇒ throw TestException("boom indeed") - case "ping" ⇒ + case "boom" => throw TestException("boom indeed") + case "ping" => probe.ref ! "pong" Behaviors.same - case "give me stacktrace" ⇒ + case "give me stacktrace" => probe.ref ! new RuntimeException().getStackTrace.toVector Behaviors.stopped }).onFailure[RuntimeException](SupervisorStrategy.resume) @@ -1128,16 +1128,16 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( val probe = TestProbe[AnyRef]("probeMcProbeFace") val restartCount = new AtomicInteger(0) val behv = supervise[String]( - Behaviors.setup { _ ⇒ + Behaviors.setup { _ => // a bit superficial, but just to be complete if (restartCount.incrementAndGet() == 1) { probe.ref ! "started 1" Behaviors.receiveMessage { - case "boom" ⇒ + case "boom" => probe.ref ! "crashing 1" throw TestException("boom indeed") - case "ping" ⇒ + case "ping" => probe.ref ! "pong 1" Behaviors.same } @@ -1145,10 +1145,10 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( probe.ref ! "started 2" Behaviors.supervise[String]( Behaviors.receiveMessage { - case "boom" ⇒ + case "boom" => probe.ref ! "crashing 2" throw TestException("boom indeed") - case "ping" ⇒ + case "ping" => probe.ref ! "pong 2" Behaviors.same } @@ -1181,10 +1181,10 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( "be able to recover from a DeathPactException" in { val probe = TestProbe[AnyRef]() - val actor = spawn(Behaviors.supervise(Behaviors.setup[String] { context ⇒ - val child = context.spawnAnonymous(Behaviors.receive[String] { (context, message) ⇒ + val actor = spawn(Behaviors.supervise(Behaviors.setup[String] { context => + val child = context.spawnAnonymous(Behaviors.receive[String] { (context, message) => message match { - case "boom" ⇒ + case "boom" => probe.ref ! context.self Behaviors.stopped } @@ -1192,10 +1192,10 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( context.watch(child) Behaviors.receiveMessage { - case "boom" ⇒ + case "boom" => child ! "boom" Behaviors.same - case "ping" ⇒ + case "ping" => probe.ref ! "pong" Behaviors.same } @@ -1220,7 +1220,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( SupervisorStrategy.restart.withLimit(1, 100.millis) ) - allStrategies.foreach { strategy ⇒ + allStrategies.foreach { strategy => s"Supervision with the strategy $strategy" should { @@ -1235,7 +1235,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( "that is stopped after setup should be stopped" in { val actor = spawn( Behaviors.supervise[Command]( - Behaviors.setup(_ ⇒ + Behaviors.setup(_ => Behaviors.stopped) ).onFailure(strategy) ) @@ -1248,13 +1248,13 @@ class SupervisionSpec extends ScalaTestWithActorTestKit( val stopInSetup = new AtomicBoolean(false) val actor = spawn( Behaviors.supervise[String]( - Behaviors.setup { _ ⇒ + Behaviors.setup { _ => if (stopInSetup.get()) { Behaviors.stopped } else { stopInSetup.set(true) Behaviors.receiveMessage { - case "boom" ⇒ throw TestException("boom") + case "boom" => throw TestException("boom") } } }).onFailure[TestException](strategy) diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/TerminatedSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/TerminatedSpec.scala index 5298a5287c..7e8f472664 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/TerminatedSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/TerminatedSpec.scala @@ -17,11 +17,11 @@ class TerminatedSpec extends WordSpec with Matchers { val childFailed = new ChildFailed(probe.ref, ex) (childFailed match { - case Terminated(r) ⇒ r + case Terminated(r) => r }) shouldEqual probe.ref (childFailed match { - case ChildFailed(ref, e) ⇒ (ref, e) + case ChildFailed(ref, e) => (ref, e) }) shouldEqual (probe.ref, ex) } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/TimerSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/TimerSpec.scala index 213f1f2eb6..2450281e5b 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/TimerSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/TimerSpec.scala @@ -51,33 +51,33 @@ class TimerSpec extends ScalaTestWithActorTestKit( target(monitor, timer, nextCount) } - Behaviors.receive[Command] { (context, cmd) ⇒ + Behaviors.receive[Command] { (context, cmd) => cmd match { - case Tick(n) ⇒ + case Tick(n) => monitor ! Tock(n) Behaviors.same - case Bump ⇒ + case Bump => bump() - case SlowThenBump(latch) ⇒ + case SlowThenBump(latch) => latch.await(10, TimeUnit.SECONDS) bump() - case End ⇒ + case End => Behaviors.stopped - case Cancel ⇒ + case Cancel => timer.cancel("T") monitor ! Cancelled Behaviors.same - case Throw(e) ⇒ + case Throw(e) => throw e - case SlowThenThrow(latch, e) ⇒ + case SlowThenThrow(latch, e) => latch.await(10, TimeUnit.SECONDS) throw e } } receiveSignal { - case (context, PreRestart) ⇒ + case (context, PreRestart) => monitor ! GotPreRestart(timer.isTimerActive("T")) Behaviors.same - case (context, PostStop) ⇒ + case (context, PostStop) => monitor ! GotPostStop(timer.isTimerActive("T")) Behaviors.same } @@ -86,7 +86,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( "A timer" must { "schedule non-repeated ticks" taggedAs TimingTest in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.withTimers[Command] { timer ⇒ + val behv = Behaviors.withTimers[Command] { timer => timer.startSingleTimer("T", Tick(1), 10.millis) target(probe.ref, timer, 1) } @@ -101,7 +101,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( "schedule repeated ticks" taggedAs TimingTest in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.withTimers[Command] { timer ⇒ + val behv = Behaviors.withTimers[Command] { timer => timer.startPeriodicTimer("T", Tick(1), interval) target(probe.ref, timer, 1) } @@ -119,7 +119,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( "replace timer" taggedAs TimingTest in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.withTimers[Command] { timer ⇒ + val behv = Behaviors.withTimers[Command] { timer => timer.startPeriodicTimer("T", Tick(1), interval) target(probe.ref, timer, 1) } @@ -139,7 +139,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( "cancel timer" taggedAs TimingTest in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.withTimers[Command] { timer ⇒ + val behv = Behaviors.withTimers[Command] { timer => timer.startPeriodicTimer("T", Tick(1), interval) target(probe.ref, timer, 1) } @@ -149,10 +149,10 @@ class TimerSpec extends ScalaTestWithActorTestKit( ref ! Cancel probe.fishForMessage(3.seconds) { // we don't know that we will see exactly one tock - case _: Tock ⇒ FishingOutcomes.continue + case _: Tock => FishingOutcomes.continue // but we know that after we saw Cancelled we won't see any more - case Cancelled ⇒ FishingOutcomes.complete - case message ⇒ FishingOutcomes.fail(s"unexpected message: $message") + case Cancelled => FishingOutcomes.complete + case message => FishingOutcomes.fail(s"unexpected message: $message") } probe.expectNoMessage(interval + 100.millis.dilated) @@ -163,7 +163,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( "discard timers from old incarnation after restart, alt 1" taggedAs TimingTest in { val probe = TestProbe[Event]("evt") val startCounter = new AtomicInteger(0) - val behv = Behaviors.supervise(Behaviors.withTimers[Command] { timer ⇒ + val behv = Behaviors.supervise(Behaviors.withTimers[Command] { timer => timer.startPeriodicTimer("T", Tick(startCounter.incrementAndGet()), interval) target(probe.ref, timer, 1) }).onFailure[Exception](SupervisorStrategy.restart) @@ -188,7 +188,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( "discard timers from old incarnation after restart, alt 2" taggedAs TimingTest in { val probe = TestProbe[Event]("evt") - val behv = Behaviors.supervise(Behaviors.withTimers[Command] { timer ⇒ + val behv = Behaviors.supervise(Behaviors.withTimers[Command] { timer => timer.startPeriodicTimer("T", Tick(1), interval) target(probe.ref, timer, 1) }).onFailure[Exception](SupervisorStrategy.restart) @@ -216,7 +216,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( "cancel timers when stopped from exception" taggedAs TimingTest in { val probe = TestProbe[Event]() - val behv = Behaviors.withTimers[Command] { timer ⇒ + val behv = Behaviors.withTimers[Command] { timer => timer.startPeriodicTimer("T", Tick(1), interval) target(probe.ref, timer, 1) } @@ -229,7 +229,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( "cancel timers when stopped voluntarily" taggedAs TimingTest in { val probe = TestProbe[Event]() - val behv = Behaviors.withTimers[Command] { timer ⇒ + val behv = Behaviors.withTimers[Command] { timer => timer.startPeriodicTimer("T", Tick(1), interval) target(probe.ref, timer, 1) } @@ -240,11 +240,11 @@ class TimerSpec extends ScalaTestWithActorTestKit( "allow for nested timers" in { val probe = TestProbe[String]() - val ref = spawn(Behaviors.withTimers[String] { outerTimer ⇒ + val ref = spawn(Behaviors.withTimers[String] { outerTimer => outerTimer.startPeriodicTimer("outer-key", "outer-message", 50.millis) - Behaviors.withTimers { innerTimer ⇒ + Behaviors.withTimers { innerTimer => innerTimer.startPeriodicTimer("inner-key", "inner-message", 50.millis) - Behaviors.receiveMessage { message ⇒ + Behaviors.receiveMessage { message => if (message == "stop") Behaviors.stopped else { probe.ref ! message @@ -256,7 +256,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( var seen = Set.empty[String] probe.fishForMessage(500.millis) { - case message ⇒ + case message => seen += message if (seen.size == 2) FishingOutcomes.complete else FishingOutcomes.continue @@ -267,9 +267,9 @@ class TimerSpec extends ScalaTestWithActorTestKit( "keep timers when behavior changes" in { val probe = TestProbe[String]() - def newBehavior(n: Int): Behavior[String] = Behaviors.withTimers[String] { timers ⇒ + def newBehavior(n: Int): Behavior[String] = Behaviors.withTimers[String] { timers => timers.startPeriodicTimer(s"key${n}", s"message${n}", 50.milli) - Behaviors.receiveMessage { message ⇒ + Behaviors.receiveMessage { message => if (message == "stop") Behaviors.stopped else { probe.ref ! message @@ -281,7 +281,7 @@ class TimerSpec extends ScalaTestWithActorTestKit( val ref = spawn(newBehavior(1)) var seen = Set.empty[String] probe.fishForMessage(500.millis) { - case message ⇒ + case message => seen += message if (seen.size == 2) FishingOutcomes.complete else FishingOutcomes.continue @@ -291,9 +291,9 @@ class TimerSpec extends ScalaTestWithActorTestKit( } "not grow stack when nesting withTimers" in { - def next(n: Int, probe: ActorRef[Array[StackTraceElement]]): Behavior[String] = Behaviors.withTimers { timers ⇒ + def next(n: Int, probe: ActorRef[Array[StackTraceElement]]): Behavior[String] = Behaviors.withTimers { timers => timers.startSingleTimer("key", "tick", 1.millis) - Behaviors.receiveMessage { message ⇒ + Behaviors.receiveMessage { message => if (n == 20) { val e = new RuntimeException().fillInStackTrace() val trace = e.getStackTrace diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/WatchSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/WatchSpec.scala index 828a4e2600..8fe972b171 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/WatchSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/WatchSpec.scala @@ -25,12 +25,12 @@ object WatchSpec { val terminatorBehavior = Behaviors.receive[Stop.type] { - case (_, Stop) ⇒ Behaviors.stopped + case (_, Stop) => Behaviors.stopped } val mutableTerminatorBehavior = new AbstractBehavior[Stop.type] { override def onMessage(message: Stop.type) = message match { - case Stop ⇒ Behaviors.stopped + case Stop => Behaviors.stopped } } @@ -56,12 +56,12 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe val watcher = spawn( Behaviors.supervise( Behaviors.receive[StartWatching] { - case (context, StartWatching(watchee)) ⇒ + case (context, StartWatching(watchee)) => context.watch(watchee) watchProbe.ref ! Done Behaviors.same }.receiveSignal { - case (_, t: Terminated) ⇒ + case (_, t: Terminated) => receivedTerminationSignal.success(t) Behaviors.stopped } @@ -85,20 +85,20 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe "notify a parent of child termination because of failure" in { val probe = TestProbe[Any]() val ex = new TestException("boom") - val parent = spawn(Behaviors.setup[Any] { context ⇒ - val child = context.spawn(Behaviors.receive[Any]((context, message) ⇒ + val parent = spawn(Behaviors.setup[Any] { context => + val child = context.spawn(Behaviors.receive[Any]((context, message) => throw ex ), "child") context.watch(child) - Behaviors.receive[Any] { (context, message) ⇒ + Behaviors.receive[Any] { (context, message) => child ! message Behaviors.same }.receiveSignal { - case (_, t: ChildFailed) ⇒ + case (_, t: ChildFailed) => probe.ref ! ChildHasFailed(t) Behaviors.same - case (_, t: Terminated) ⇒ + case (_, t: Terminated) => probe.ref ! HasTerminated(t) Behaviors.same } @@ -113,20 +113,20 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe "notify a parent of child termination because of failure with a supervisor" in { val probe = TestProbe[Any]() val ex = new TestException("boom") - val behavior = Behaviors.setup[Any] { context ⇒ - val child = context.spawn(Behaviors.supervise(Behaviors.receive[Any]((context, message) ⇒ { + val behavior = Behaviors.setup[Any] { context => + val child = context.spawn(Behaviors.supervise(Behaviors.receive[Any]((context, message) => { throw ex })).onFailure[Throwable](SupervisorStrategy.stop), "child") context.watch(child) - Behaviors.receive[Any] { (context, message) ⇒ + Behaviors.receive[Any] { (context, message) => child ! message Behaviors.same }.receiveSignal { - case (_, t: ChildFailed) ⇒ + case (_, t: ChildFailed) => probe.ref ! ChildHasFailed(t) Behaviors.same - case (_, t: Terminated) ⇒ + case (_, t: Terminated) => probe.ref ! HasTerminated(t) Behaviors.same } @@ -143,14 +143,14 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe case class Failed(t: Terminated) // we need to wrap it as it is handled specially val probe = TestProbe[Any]() val ex = new TestException("boom") - val grossoBosso = spawn(Behaviors.setup[Any] { context ⇒ - val middleManagement = context.spawn(Behaviors.setup[Any] { context ⇒ - val sixPackJoe = context.spawn(Behaviors.receive[Any]((context, message) ⇒ + val grossoBosso = spawn(Behaviors.setup[Any] { context => + val middleManagement = context.spawn(Behaviors.setup[Any] { context => + val sixPackJoe = context.spawn(Behaviors.receive[Any]((context, message) => throw ex ), "joe") context.watch(sixPackJoe) - Behaviors.receive[Any] { (context, message) ⇒ + Behaviors.receive[Any] { (context, message) => sixPackJoe ! message Behaviors.same } // no handling of terminated, even though we watched!!! @@ -158,11 +158,11 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe context.watch(middleManagement) - Behaviors.receive[Any] { (context, message) ⇒ + Behaviors.receive[Any] { (context, message) => middleManagement ! message Behaviors.same }.receiveSignal { - case (_, t: Terminated) ⇒ + case (_, t: Terminated) => probe.ref ! Failed(t) Behaviors.stopped } @@ -195,11 +195,11 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe val watcher = spawn( Behaviors.supervise( Behaviors.receive[Message] { - case (context, StartWatchingWith(watchee, message)) ⇒ + case (context, StartWatchingWith(watchee, message)) => context.watchWith(watchee, message) watchProbe.ref ! Done Behaviors.same - case (_, message) ⇒ + case (_, message) => receivedTerminationSignal.success(message) Behaviors.stopped }).onFailure[Throwable](SupervisorStrategy.stop) @@ -231,15 +231,15 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe val watcher = spawn( Behaviors.supervise( Behaviors.receive[Message] { - case (context, StartWatching(watchee)) ⇒ + case (context, StartWatching(watchee)) => context.watch(watchee) Behaviors.same - case (context, StartWatchingWith(watchee, message)) ⇒ + case (context, StartWatchingWith(watchee, message)) => context.unwatch(watchee) context.watchWith(watchee, message) watchProbe.ref ! Done Behaviors.same - case (_, message) ⇒ + case (_, message) => receivedTerminationSignal.success(message) Behaviors.stopped }).onFailure[Throwable](SupervisorStrategy.stop) @@ -261,12 +261,12 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe val watcher = spawn( Behaviors.supervise( Behaviors.receive[Message] { - case (context, StartWatchingWith(watchee, message)) ⇒ + case (context, StartWatchingWith(watchee, message)) => context.unwatch(watchee) context.watchWith(watchee, message) watchProbe.ref ! Done Behaviors.same - case (_, message) ⇒ + case (_, message) => receivedTerminationSignal.success(message) Behaviors.stopped }).onFailure[Throwable](SupervisorStrategy.stop) @@ -287,16 +287,16 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe val watcher = spawn( Behaviors.supervise( Behaviors.receive[Message] { - case (context, StartWatchingWith(watchee, message)) ⇒ + case (context, StartWatchingWith(watchee, message)) => context.watchWith(watchee, message) Behaviors.same - case (context, StartWatching(watchee)) ⇒ + case (context, StartWatching(watchee)) => context.watch(watchee) Behaviors.same - case (_, _) ⇒ + case (_, _) => Behaviors.stopped }.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => Behaviors.stopped } ).onFailure[Throwable](SupervisorStrategy.stop) diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/WidenSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/WidenSpec.scala index c5b7fa6f6a..f0de3378cc 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/WidenSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/WidenSpec.scala @@ -24,11 +24,11 @@ class WidenSpec extends ScalaTestWithActorTestKit( implicit val untypedSystem = system.toUntyped def intToString(probe: ActorRef[String]): Behavior[Int] = { - Behaviors.receiveMessage[String] { message ⇒ + Behaviors.receiveMessage[String] { message => probe ! message Behaviors.same }.widen[Int] { - case n if n != 13 ⇒ n.toString + case n if n != 13 => n.toString } } @@ -62,7 +62,7 @@ class WidenSpec extends ScalaTestWithActorTestKit( // sadly the only "same" we can know is if it is the same PF val transform: PartialFunction[String, String] = { - case s ⇒ + case s => transformCount.incrementAndGet() s } @@ -72,7 +72,7 @@ class WidenSpec extends ScalaTestWithActorTestKit( val beh = widen( widen( - Behaviors.receiveMessage[String] { message ⇒ + Behaviors.receiveMessage[String] { message => probe.ref ! message Behaviors.same } @@ -92,7 +92,7 @@ class WidenSpec extends ScalaTestWithActorTestKit( // sadly the only "same" we can know is if it is the same PF val transform: PartialFunction[String, String] = { - case s ⇒ + case s => transformCount.incrementAndGet() s } @@ -101,7 +101,7 @@ class WidenSpec extends ScalaTestWithActorTestKit( def next: Behavior[String] = widen( - Behaviors.receiveMessage[String] { message ⇒ + Behaviors.receiveMessage[String] { message => probe.ref ! message next } @@ -124,14 +124,14 @@ class WidenSpec extends ScalaTestWithActorTestKit( def widen(behavior: Behavior[String]): Behavior[String] = behavior.widen[String] { - case s ⇒ s.toLowerCase + case s => s.toLowerCase } EventFilter[ActorInitializationException](occurrences = 1).intercept { val ref = spawn( widen( widen( - Behaviors.receiveMessage[String] { message ⇒ + Behaviors.receiveMessage[String] { message => Behaviors.same } ) diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/ActorRefSerializationSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/ActorRefSerializationSpec.scala index 24a7d8d596..99fe47256b 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/ActorRefSerializationSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/ActorRefSerializationSpec.scala @@ -34,11 +34,11 @@ class ActorRefSerializationSpec extends ScalaTestWithActorTestKit(ActorRefSerial "be serialized and deserialized by MiscMessageSerializer" in { val obj = spawn(Behaviors.empty[Unit]) serialization.findSerializerFor(obj) match { - case serializer: MiscMessageSerializer ⇒ + case serializer: MiscMessageSerializer => val blob = serializer.toBinary(obj) val ref = serializer.fromBinary(blob, serializer.manifest(obj)) ref should ===(obj) - case s ⇒ + case s => throw new IllegalStateException(s"Wrong serializer ${s.getClass} for ${obj.getClass}") } } @@ -48,11 +48,11 @@ class ActorRefSerializationSpec extends ScalaTestWithActorTestKit(ActorRefSerial val obj = ActorRefSerializationSpec.MessageWrappingActorRef("some message", ref) serialization.findSerializerFor(obj) match { - case serializer: JavaSerializer ⇒ + case serializer: JavaSerializer => val blob = serializer.toBinary(obj) val restored = serializer.fromBinary(blob, None) restored should ===(obj) - case s ⇒ + case s => throw new IllegalStateException(s"Wrong serializer ${s.getClass} for ${obj.getClass}") } } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/ActorSystemSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/ActorSystemSpec.scala index 128ae72f8d..8901c796cc 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/ActorSystemSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/ActorSystemSpec.scala @@ -25,13 +25,13 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll case class Probe(message: String, replyTo: ActorRef[String]) - def withSystem[T](name: String, behavior: Behavior[T], doTerminate: Boolean = true)(block: ActorSystem[T] ⇒ Unit): Terminated = { + def withSystem[T](name: String, behavior: Behavior[T], doTerminate: Boolean = true)(block: ActorSystem[T] => Unit): Terminated = { val sys = system(behavior, s"$suite-$name") try { block(sys) if (doTerminate) sys.terminate().futureValue else sys.whenTerminated.futureValue } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => sys.terminate() throw ex } @@ -41,7 +41,7 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll "start the guardian actor and terminate when it terminates" in { val t = withSystem( "a", - Behaviors.receive[Probe] { case (_, p) ⇒ p.replyTo ! p.message; Behaviors.stopped }, doTerminate = false) { sys ⇒ + Behaviors.receive[Probe] { case (_, p) => p.replyTo ! p.message; Behaviors.stopped }, doTerminate = false) { sys => val inbox = TestInbox[String]("a") sys ! Probe("hello", inbox.ref) eventually { @@ -58,9 +58,9 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll "shutdown if guardian shuts down immediately" in { val stoppable = Behaviors.receive[Done] { - case (context, Done) ⇒ Behaviors.stopped + case (context, Done) => Behaviors.stopped } - withSystem("shutdown", stoppable, doTerminate = false) { sys: ActorSystem[Done] ⇒ + withSystem("shutdown", stoppable, doTerminate = false) { sys: ActorSystem[Done] => sys ! Done sys.whenTerminated.futureValue } @@ -70,9 +70,9 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll val inbox = TestInbox[String]("terminate") val sys = system( Behaviors.receive[Probe] { - case (_, _) ⇒ Behaviors.unhandled + case (_, _) => Behaviors.unhandled } receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => inbox.ref ! "done" Behaviors.same }, @@ -86,13 +86,13 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll } "have a name" in { - withSystem("name", Behaviors.empty[String]) { sys ⇒ + withSystem("name", Behaviors.empty[String]) { sys => sys.name should ===(suite + "-name") } } "report its uptime" in { - withSystem("uptime", Behaviors.empty[String]) { sys ⇒ + withSystem("uptime", Behaviors.empty[String]) { sys => sys.uptime should be < 1L Thread.sleep(1000) sys.uptime should be >= 1L @@ -100,7 +100,7 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll } "have a working thread factory" in { - withSystem("thread", Behaviors.empty[String]) { sys ⇒ + withSystem("thread", Behaviors.empty[String]) { sys => val p = Promise[Int] sys.threadFactory.newThread(new Runnable { def run(): Unit = p.success(42) @@ -110,14 +110,14 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll } "be able to run Futures" in { - withSystem("futures", Behaviors.empty[String]) { sys ⇒ + withSystem("futures", Behaviors.empty[String]) { sys => val f = Future(42)(sys.executionContext) f.futureValue should ===(42) } } "not allow null messages" in { - withSystem("null-messages", Behaviors.empty[String]) { sys ⇒ + withSystem("null-messages", Behaviors.empty[String]) { sys => intercept[InvalidMessageException] { sys ! null } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/receptionist/LocalReceptionistSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/receptionist/LocalReceptionistSpec.scala index 2f44b2b654..79f8f98e79 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/receptionist/LocalReceptionistSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/receptionist/LocalReceptionistSpec.scala @@ -27,10 +27,10 @@ object LocalReceptionistSpec { val behaviorB = Behaviors.empty[ServiceB] case object Stop extends ServiceA with ServiceB - val stoppableBehavior = Behaviors.receive[Any] { (_, message) ⇒ + val stoppableBehavior = Behaviors.receive[Any] { (_, message) => message match { - case Stop ⇒ Behavior.stopped - case _ ⇒ Behavior.same + case Stop => Behavior.stopped + case _ => Behavior.same } } @@ -128,7 +128,7 @@ class LocalReceptionistBehaviorSpec extends WordSpec with Matchers { import LocalReceptionistSpec._ def assertEmpty(inboxes: TestInbox[_]*): Unit = { - inboxes foreach (i ⇒ withClue(s"inbox $i had messages")(i.hasMessages should be(false))) + inboxes foreach (i => withClue(s"inbox $i had messages")(i.hasMessages should be(false))) } "A local receptionist behavior" must { diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/receptionist/ServiceKeySerializationSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/receptionist/ServiceKeySerializationSpec.scala index 0c0d1d4579..cc0f6a29e3 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/receptionist/ServiceKeySerializationSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/receptionist/ServiceKeySerializationSpec.scala @@ -19,11 +19,11 @@ class ServiceKeySerializationSpec extends ScalaTestWithActorTestKit(ActorRefSeri "be serialized and deserialized by ServiceKeySerializer" in { val obj = ServiceKey[Int]("testKey") serialization.findSerializerFor(obj) match { - case serializer: ServiceKeySerializer ⇒ + case serializer: ServiceKeySerializer => val blob = serializer.toBinary(obj) val ref = serializer.fromBinary(blob, serializer.manifest(obj)) ref should be(obj) - case s ⇒ + case s => throw new IllegalStateException(s"Wrong serializer ${s.getClass} for ${obj.getClass}") } } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/routing/RoutingLogicSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/routing/RoutingLogicSpec.scala index b763d8b626..fd4867cc32 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/routing/RoutingLogicSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/internal/routing/RoutingLogicSpec.scala @@ -126,7 +126,7 @@ class RoutingLogicSpec extends ScalaTestWithActorTestKit with WordSpecLike with val logic = new RoutingLogics.RandomLogic[Any]() logic.routeesUpdated(routees) - (0 to 10).foreach { _ ⇒ + (0 to 10).foreach { _ => // not much to verify here, but let's exercise it at least val routee = logic.selectRoutee() routees should contain(routee) diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/receptionist/ReceptionistApiSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/receptionist/ReceptionistApiSpec.scala index f05ebc4634..b71fb5b5ff 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/receptionist/ReceptionistApiSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/receptionist/ReceptionistApiSpec.scala @@ -33,26 +33,26 @@ object ReceptionistApiSpec { val registered: Future[Receptionist.Registered] = system.receptionist.ask(Receptionist.Register(key, service, _)) registered.foreach { - case key.Registered(ref) ⇒ + case key.Registered(ref) => // ref is the right type here ref ! "woho" - case _ ⇒ () + case _ => () } // one-off ask outside of actor, should be uncommon but not rare val found: Future[Receptionist.Listing] = system.receptionist.ask(Receptionist.Find(key, _)) found.foreach { - case key.Listing(instances) ⇒ + case key.Listing(instances) => instances.foreach(_ ! "woho") - case _ ⇒ () + case _ => () } - Behaviors.setup[Any] { context ⇒ + Behaviors.setup[Any] { context => // oneoff ask inside of actor, this should be a rare use case context.ask(system.receptionist)(Receptionist.Find(key)) { - case Success(key.Listing(services)) ⇒ services // Set[ActorRef[String]] !! - case _ ⇒ "unexpected" + case Success(key.Listing(services)) => services // Set[ActorRef[String]] !! + case _ => "unexpected" } // this is a more "normal" use case which is clean @@ -60,7 +60,7 @@ object ReceptionistApiSpec { // another more "normal" is subscribe using an adapter // FIXME inference doesn't work with partial function - val adapter = context.spawnMessageAdapter { listing: Receptionist.Listing ⇒ + val adapter = context.spawnMessageAdapter { listing: Receptionist.Listing => listing.serviceInstances(key) // Set[ActorRef[String]] !! } context.system.receptionist ! Receptionist.Subscribe(key, adapter) @@ -69,12 +69,12 @@ object ReceptionistApiSpec { // to cover as much of the API as possible context.system.receptionist ! Receptionist.Register(key, context.self.narrow, context.self.narrow) - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => message match { - case key.Listing(services) ⇒ + case key.Listing(services) => services.foreach(_ ! "woho") Behaviors.same - case key.Registered(service) ⇒ // ack on Register above + case key.Registered(service) => // ack on Register above service ! "woho" Behaviors.same } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorContextAskSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorContextAskSpec.scala index 63549f03d4..cfcfea09a0 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorContextAskSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorContextAskSpec.scala @@ -42,23 +42,23 @@ class ActorContextAskSpec extends ScalaTestWithActorTestKit(ActorContextAskSpec. case class Ping(sender: ActorRef[Pong]) case class Pong(selfName: String, threadName: String) - val pingPong = spawn(Behaviors.receive[Ping] { (context, message) ⇒ + val pingPong = spawn(Behaviors.receive[Ping] { (context, message) => message.sender ! Pong(context.self.path.name, Thread.currentThread().getName) Behaviors.same }, "ping-pong", Props.empty.withDispatcherFromConfig("ping-pong-dispatcher")) val probe = TestProbe[Pong]() - val snitch = Behaviors.setup[Pong] { context ⇒ + val snitch = Behaviors.setup[Pong] { context => // Timeout comes from TypedAkkaSpec context.ask(pingPong)(Ping) { - case Success(_) ⇒ Pong(context.self.path.name + "1", Thread.currentThread().getName) - case Failure(ex) ⇒ throw ex + case Success(_) => Pong(context.self.path.name + "1", Thread.currentThread().getName) + case Failure(ex) => throw ex } - Behaviors.receiveMessage { pong ⇒ + Behaviors.receiveMessage { pong => probe.ref ! pong Behaviors.same } @@ -79,27 +79,27 @@ class ActorContextAskSpec extends ScalaTestWithActorTestKit(ActorContextAskSpec. case class Ping(respondTo: ActorRef[Pong.type]) extends Protocol case object Pong extends Protocol - val pingPong = spawn(Behaviors.receive[Protocol]((_, message) ⇒ + val pingPong = spawn(Behaviors.receive[Protocol]((_, message) => message match { - case Ping(respondTo) ⇒ + case Ping(respondTo) => respondTo ! Pong Behaviors.same } )) - val snitch = Behaviors.setup[AnyRef] { context ⇒ + val snitch = Behaviors.setup[AnyRef] { context => context.ask(pingPong)(Ping) { - case Success(message) ⇒ throw new NotImplementedError(message.toString) - case Failure(x) ⇒ x + case Success(message) => throw new NotImplementedError(message.toString) + case Failure(x) => x } Behaviors.receive[AnyRef] { - case (_, message) ⇒ + case (_, message) => probe.ref ! message Behaviors.same }.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => probe.ref ! "stopped" Behaviors.same } @@ -115,14 +115,14 @@ class ActorContextAskSpec extends ScalaTestWithActorTestKit(ActorContextAskSpec. "deal with timeouts in ask" in { val probe = TestProbe[AnyRef]() - val snitch = Behaviors.setup[AnyRef] { context ⇒ + val snitch = Behaviors.setup[AnyRef] { context => - context.ask[String, String](system.deadLetters)(ref ⇒ "boo") { - case Success(m) ⇒ m - case Failure(x) ⇒ x + context.ask[String, String](system.deadLetters)(ref => "boo") { + case Success(m) => m + case Failure(x) => x }(10.millis, implicitly[ClassTag[String]]) - Behaviors.receiveMessage { message ⇒ + Behaviors.receiveMessage { message => probe.ref ! message Behaviors.same } @@ -141,14 +141,14 @@ class ActorContextAskSpec extends ScalaTestWithActorTestKit(ActorContextAskSpec. "must timeout if recipient doesn't reply in time" in { val target = spawn(Behaviors.ignore[String]) val probe = TestProbe[AnyRef]() - val snitch = Behaviors.setup[AnyRef] { context ⇒ + val snitch = Behaviors.setup[AnyRef] { context => - context.ask[String, String](target)(_ ⇒ "bar") { - case Success(m) ⇒ m - case Failure(x) ⇒ x + context.ask[String, String](target)(_ => "bar") { + case Success(m) => m + case Failure(x) => x }(10.millis, implicitly[ClassTag[String]]) - Behaviors.receiveMessage { message ⇒ + Behaviors.receiveMessage { message => probe.ref ! message Behaviors.same } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorContextPipeToSelfSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorContextPipeToSelfSpec.scala index 576c810336..79bfeb87d4 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorContextPipeToSelfSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorContextPipeToSelfSpec.scala @@ -37,12 +37,12 @@ final class ActorContextPipeToSelfSpec extends ScalaTestWithActorTestKit(ActorCo final case class Msg(response: String, selfName: String, threadName: String) val probe = TestProbe[Msg]() - val behavior = Behaviors.setup[Msg] { context ⇒ + val behavior = Behaviors.setup[Msg] { context => context.pipeToSelf(future) { - case Success(s) ⇒ Msg(s"ok: $s", context.self.path.name, Thread.currentThread().getName) - case Failure(e) ⇒ Msg(s"ko: $e", context.self.path.name, Thread.currentThread().getName) + case Success(s) => Msg(s"ok: $s", context.self.path.name, Thread.currentThread().getName) + case Failure(e) => Msg(s"ko: $e", context.self.path.name, Thread.currentThread().getName) } - Behaviors.receiveMessage { msg ⇒ + Behaviors.receiveMessage { msg => probe.ref ! msg Behaviors.stopped } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorLoggingSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorLoggingSpec.scala index cbe0958190..b90b1a429e 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorLoggingSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ActorLoggingSpec.scala @@ -21,7 +21,7 @@ class SomeClass object WhereTheBehaviorIsDefined { - def behavior: Behavior[String] = Behaviors.setup { context ⇒ + def behavior: Behavior[String] = Behaviors.setup { context => context.log.info("Starting up") Behaviors.stopped } @@ -29,7 +29,7 @@ object WhereTheBehaviorIsDefined { } object BehaviorWhereTheLoggerIsUsed { - def behavior: Behavior[String] = Behaviors.setup(ctx ⇒ new BehaviorWhereTheLoggerIsUsed(ctx)) + def behavior: Behavior[String] = Behaviors.setup(ctx => new BehaviorWhereTheLoggerIsUsed(ctx)) } class BehaviorWhereTheLoggerIsUsed(context: ActorContext[String]) extends AbstractBehavior[String] { context.log.info("Starting up") @@ -54,10 +54,10 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "be conveniently available from the context" in { val actor = EventFilter.info("Started", source = "akka://ActorLoggingSpec/user/the-actor", occurrences = 1).intercept { - spawn(Behaviors.setup[String] { context ⇒ + spawn(Behaviors.setup[String] { context => context.log.info("Started") - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => context.log.info("got message {}", message) Behaviors.same } @@ -71,22 +71,22 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "contain the class name where the first log was called" in { val eventFilter = EventFilter.custom({ - case l: LogEvent if l.logClass == classOf[ActorLoggingSpec] ⇒ true - case l: LogEvent if isScala211 ⇒ + case l: LogEvent if l.logClass == classOf[ActorLoggingSpec] => true + case l: LogEvent if isScala211 => // TODO remove in Akka 2.6 when we drop Scala 2.11 // the class with 2.11 is like // ActorLoggingSpec$$anonfun$1$$anonfun$apply$mcV$sp$26$$anonfun$apply$6$$anonfun$apply$7 l.logClass.getName.startsWith(classOf[ActorLoggingSpec].getName) - case l: LogEvent ⇒ + case l: LogEvent => println(l.logClass) false }, occurrences = 1) eventFilter.intercept { - spawn(Behaviors.setup[String] { context ⇒ + spawn(Behaviors.setup[String] { context => context.log.info("Started") - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => context.log.info("got message {}", message) Behaviors.same } @@ -96,13 +96,13 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "contain the object class name where the first log was called" in { val eventFilter = EventFilter.custom({ - case l: LogEvent if l.logClass == WhereTheBehaviorIsDefined.getClass ⇒ true - case l: LogEvent if isScala211 ⇒ + case l: LogEvent if l.logClass == WhereTheBehaviorIsDefined.getClass => true + case l: LogEvent if isScala211 => // TODO remove in Akka 2.6 when we drop Scala 2.11 // the class with 2.11 is like // WhereTheBehaviorIsDefined$$anonfun$behavior$1 l.logClass.getName.startsWith(WhereTheBehaviorIsDefined.getClass.getName) - case l: LogEvent ⇒ + case l: LogEvent => println(l.logClass) false }, occurrences = 1) @@ -114,8 +114,8 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "contain the abstract behavior class name where the first log was called" in { val eventFilter = EventFilter.custom({ - case l: LogEvent if l.logClass == classOf[BehaviorWhereTheLoggerIsUsed] ⇒ true - case l: LogEvent ⇒ + case l: LogEvent if l.logClass == classOf[BehaviorWhereTheLoggerIsUsed] => true + case l: LogEvent => println(l.logClass) false }, occurrences = 1) @@ -127,14 +127,14 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "allow for adapting log source and class" in { val eventFilter = EventFilter.custom({ - case l: LogEvent ⇒ + case l: LogEvent => l.logClass == classOf[SomeClass] && l.logSource == "who-knows-where-it-came-from" && l.mdc == Map("mdc" -> true) // mdc should be kept }, occurrences = 1) eventFilter.intercept { - spawn(Behaviors.setup[String] { context ⇒ + spawn(Behaviors.setup[String] { context => val log = context.log.withMdc(Map("mdc" -> true)) .withLoggerClass(classOf[SomeClass]) .withLogSource("who-knows-where-it-came-from") @@ -147,15 +147,15 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "pass markers to the log" in { EventFilter.custom({ - case event: LogEventWithMarker if event.marker == marker ⇒ true + case event: LogEventWithMarker if event.marker == marker => true }, occurrences = 9).intercept( - spawn(Behaviors.setup[Any] { context ⇒ + spawn(Behaviors.setup[Any] { context => context.log.debug(marker, "whatever") context.log.info(marker, "whatever") context.log.warning(marker, "whatever") context.log.error(marker, "whatever") context.log.error(marker, cause, "whatever") - Logging.AllLogLevels.foreach(level ⇒ { + Logging.AllLogLevels.foreach(level => { context.log.log(level, marker, "whatever") }) Behaviors.stopped @@ -165,9 +165,9 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "pass cause with warning" in { EventFilter.custom({ - case event: LogEventWithCause if event.cause == cause ⇒ true + case event: LogEventWithCause if event.cause == cause => true }, occurrences = 2).intercept( - spawn(Behaviors.setup[Any] { context ⇒ + spawn(Behaviors.setup[Any] { context => context.log.warning(cause, "whatever") context.log.warning(marker, cause, "whatever") Behaviors.stopped @@ -180,9 +180,9 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" // Not the best test but at least it exercises every log overload ;) EventFilter.custom({ - case _ ⇒ true // any is fine, we're just after the right count of statements reaching the listener + case _ => true // any is fine, we're just after the right count of statements reaching the listener }, occurrences = 120).intercept { - spawn(Behaviors.setup[String] { context ⇒ + spawn(Behaviors.setup[String] { context => context.log.debug("message") context.log.debug("{}", "arg1") context.log.debug("{} {}", "arg1", "arg2") @@ -261,7 +261,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" context.log.error(marker, cause, "{} {} {} {}", "arg1", "arg2", "arg3", "arg4") context.log.error(marker, cause, "{} {} {} {} {}", Array("arg1", "arg2", "arg3", "arg4", "arg5")) - Logging.AllLogLevels.foreach(level ⇒ { + Logging.AllLogLevels.foreach(level => { context.log.log(level, "message") context.log.log(level, "{}", "arg1") context.log.log(level, "{} {}", "arg1", "arg2") @@ -295,7 +295,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" val behaviors = Behaviors.withMdc[Protocol]( Map("static" -> 1), // FIXME why u no infer the type here Scala?? - (message: Protocol) ⇒ + (message: Protocol) => if (message.transactionId == 1) Map( "txId" -> message.transactionId, @@ -303,9 +303,9 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" ) else Map("txId" -> message.transactionId) ) { - Behaviors.setup { context ⇒ + Behaviors.setup { context => context.log.info("Starting") - Behaviors.receiveMessage { _ ⇒ + Behaviors.receiveMessage { _ => context.log.info("Got message!") Behaviors.same } @@ -314,33 +314,33 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" // mdc on defer is empty (thread and timestamp MDC is added by logger backend) val ref = EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("Starting") logEvent.mdc shouldBe empty true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { spawn(behaviors) } // mdc on message EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("Got message!") logEvent.mdc should ===(Map("static" -> 1, "txId" -> 1L, "first" -> true)) true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! Message(1, "first") } // mdc does not leak between messages EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("Got message!") logEvent.mdc should ===(Map("static" -> 1, "txId" -> 2L)) true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! Message(2, "second") } @@ -351,7 +351,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" val behavior = Behaviors.withMdc[String](Map("outermost" -> true)) { Behaviors.withMdc(Map("innermost" -> true)) { - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => context.log.info(message) Behaviors.same } @@ -360,11 +360,11 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" val ref = spawn(behavior) EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("message") logEvent.mdc should ===(Map("outermost" -> true)) true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! "message" } @@ -372,11 +372,11 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "keep being applied when behavior changes to other behavior" in { def behavior: Behavior[String] = - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => message match { - case "new-behavior" ⇒ + case "new-behavior" => behavior - case other ⇒ + case other => context.log.info(other) Behaviors.same } @@ -384,11 +384,11 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" val ref = spawn(Behaviors.withMdc(Map("hasMdc" -> true))(behavior)) EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("message") logEvent.mdc should ===(Map("hasMdc" -> true)) true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! "message" } @@ -396,11 +396,11 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" ref ! "new-behavior" EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("message") logEvent.mdc should ===(Map("hasMdc" -> true)) // original mdc should stay true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! "message" } @@ -412,11 +412,11 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" val id = new AtomicInteger(0) def behavior: Behavior[String] = Behaviors.withMdc(Map("mdc-version" -> id.incrementAndGet())) { - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => message match { - case "new-mdc" ⇒ + case "new-mdc" => behavior - case other ⇒ + case other => context.log.info(other) Behaviors.same } @@ -425,21 +425,21 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" val ref = spawn(behavior) EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("message") logEvent.mdc should ===(Map("mdc-version" -> 1)) true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! "message" } ref ! "new-mdc" EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("message") logEvent.mdc should ===(Map("mdc-version" -> 2)) // mdc should have been replaced true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! "message" } @@ -448,8 +448,8 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" "provide a withMdc decorator" in { val behavior = Behaviors.withMdc[Protocol](Map("mdc" -> "outer"))( - Behaviors.setup { context ⇒ - Behaviors.receiveMessage { _ ⇒ + Behaviors.setup { context => + Behaviors.receiveMessage { _ => context.log.withMdc(Map("mdc" -> "inner")).info("Got message log.withMDC!") // after log.withMdc so we know it didn't change the outer mdc context.log.info("Got message behavior.withMdc!") @@ -461,18 +461,18 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" // mdc on message val ref = spawn(behavior) EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("Got message behavior.withMdc!") logEvent.mdc should ===(Map("mdc" -> "outer")) true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { EventFilter.custom({ - case logEvent if logEvent.level == Logging.InfoLevel ⇒ + case logEvent if logEvent.level == Logging.InfoLevel => logEvent.message should ===("Got message log.withMDC!") logEvent.mdc should ===(Map("mdc" -> "inner")) true - case other ⇒ system.log.error(s"Unexpected log event: {}", other); false + case other => system.log.error(s"Unexpected log event: {}", other); false }, occurrences = 1).intercept { ref ! Message(1, "first") } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/GracefulStopSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/GracefulStopSpec.scala index ff9c17ab98..592f16f4ae 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/GracefulStopSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/GracefulStopSpec.scala @@ -19,22 +19,22 @@ final class GracefulStopSpec extends ScalaTestWithActorTestKit with WordSpecLike val probe = TestProbe[String]("probe") val behavior = - Behaviors.setup[akka.NotUsed] { context ⇒ + Behaviors.setup[akka.NotUsed] { context => context.spawn[NotUsed](Behaviors.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => probe.ref ! "child-done" Behaviors.stopped }, "child1") context.spawn[NotUsed](Behaviors.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => probe.ref ! "child-done" Behaviors.stopped }, "child2") Behaviors.stopped { Behaviors.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => // cleanup function body probe.ref ! "parent-done" Behaviors.same @@ -52,11 +52,11 @@ final class GracefulStopSpec extends ScalaTestWithActorTestKit with WordSpecLike val probe = TestProbe[Done]("probe") val behavior = - Behaviors.setup[akka.NotUsed] { _ ⇒ + Behaviors.setup[akka.NotUsed] { _ => // do not spawn any children Behaviors.stopped { Behaviors.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => // cleanup function body probe.ref ! Done Behaviors.same diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/MessageAdapterSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/MessageAdapterSpec.scala index b5f9f7a783..145d58f091 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/MessageAdapterSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/MessageAdapterSpec.scala @@ -45,25 +45,25 @@ class MessageAdapterSpec extends ScalaTestWithActorTestKit(MessageAdapterSpec.co case class AnotherPong(selfName: String, threadName: String) - val pingPong = spawn(Behaviors.receive[Ping] { (context, message) ⇒ + val pingPong = spawn(Behaviors.receive[Ping] { (context, message) => message.sender ! Pong(context.self.path.name, Thread.currentThread().getName) Behaviors.same }, "ping-pong", Props.empty.withDispatcherFromConfig("ping-pong-dispatcher")) val probe = TestProbe[AnotherPong]() - val snitch = Behaviors.setup[AnotherPong] { context ⇒ + val snitch = Behaviors.setup[AnotherPong] { context => - val replyTo = context.messageAdapter[Response](_ ⇒ + val replyTo = context.messageAdapter[Response](_ => AnotherPong(context.self.path.name, Thread.currentThread().getName)) pingPong ! Ping(replyTo) // also verify the internal spawnMessageAdapter - val replyTo2: ActorRef[Response] = context.spawnMessageAdapter(_ ⇒ + val replyTo2: ActorRef[Response] = context.spawnMessageAdapter(_ => AnotherPong(context.self.path.name, Thread.currentThread().getName)) pingPong ! Ping(replyTo2) - Behaviors.receiveMessage { anotherPong ⇒ + Behaviors.receiveMessage { anotherPong => probe.ref ! anotherPong Behaviors.same } @@ -92,25 +92,25 @@ class MessageAdapterSpec extends ScalaTestWithActorTestKit(MessageAdapterSpec.co case class Wrapped(qualifier: String, response: Response) val pingPong = spawn(Behaviors.receiveMessage[Ping] { - case Ping1(sender) ⇒ + case Ping1(sender) => sender ! Pong1("hello-1") Behaviors.same - case Ping2(sender) ⇒ + case Ping2(sender) => sender ! Pong2("hello-2") Behaviors.same }) val probe = TestProbe[Wrapped]() - val snitch = Behaviors.setup[Wrapped] { context ⇒ + val snitch = Behaviors.setup[Wrapped] { context => - context.messageAdapter[Response](pong ⇒ Wrapped(qualifier = "wrong", pong)) // this is replaced - val replyTo1: ActorRef[Response] = context.messageAdapter(pong ⇒ Wrapped(qualifier = "1", pong)) - val replyTo2 = context.messageAdapter[Pong2](pong ⇒ Wrapped(qualifier = "2", pong)) + context.messageAdapter[Response](pong => Wrapped(qualifier = "wrong", pong)) // this is replaced + val replyTo1: ActorRef[Response] = context.messageAdapter(pong => Wrapped(qualifier = "1", pong)) + val replyTo2 = context.messageAdapter[Pong2](pong => Wrapped(qualifier = "2", pong)) pingPong ! Ping1(replyTo1) pingPong ! Ping2(replyTo2) - Behaviors.receiveMessage { wrapped ⇒ + Behaviors.receiveMessage { wrapped => probe.ref ! wrapped Behaviors.same } @@ -133,10 +133,10 @@ class MessageAdapterSpec extends ScalaTestWithActorTestKit(MessageAdapterSpec.co case class Wrapped(qualifier: String, response: Response) val pingPong = spawn(Behaviors.receiveMessage[Ping] { - case Ping1(sender) ⇒ + case Ping1(sender) => sender ! Pong1("hello-1") Behaviors.same - case Ping2(sender) ⇒ + case Ping2(sender) => // doing something terribly wrong sender ! Pong2("hello-2") Behaviors.same @@ -144,16 +144,16 @@ class MessageAdapterSpec extends ScalaTestWithActorTestKit(MessageAdapterSpec.co val probe = TestProbe[Wrapped]() - val snitch = Behaviors.setup[Wrapped] { context ⇒ + val snitch = Behaviors.setup[Wrapped] { context => - val replyTo1 = context.messageAdapter[Pong1](pong ⇒ Wrapped(qualifier = "1", pong)) + val replyTo1 = context.messageAdapter[Pong1](pong => Wrapped(qualifier = "1", pong)) pingPong ! Ping1(replyTo1) // doing something terribly wrong // Pong2 message adapter not registered pingPong ! Ping2(replyTo1.asInstanceOf[ActorRef[Pong2]]) pingPong ! Ping1(replyTo1) - Behaviors.receiveMessage { wrapped ⇒ + Behaviors.receiveMessage { wrapped => probe.ref ! wrapped Behaviors.same } @@ -173,30 +173,30 @@ class MessageAdapterSpec extends ScalaTestWithActorTestKit(MessageAdapterSpec.co case class Pong(greeting: String) case class Wrapped(count: Int, response: Pong) - val pingPong = spawn(Behaviors.receiveMessage[Ping] { ping ⇒ + val pingPong = spawn(Behaviors.receiveMessage[Ping] { ping => ping.sender ! Pong("hello") Behaviors.same }) val probe = TestProbe[Any]() - val snitch = Behaviors.setup[Wrapped] { context ⇒ + val snitch = Behaviors.setup[Wrapped] { context => var count = 0 - val replyTo = context.messageAdapter[Pong] { pong ⇒ + val replyTo = context.messageAdapter[Pong] { pong => count += 1 if (count == 3) throw new TestException("boom") else Wrapped(count, pong) } - (1 to 4).foreach { _ ⇒ + (1 to 4).foreach { _ => pingPong ! Ping(replyTo) } - Behaviors.receiveMessage[Wrapped] { wrapped ⇒ + Behaviors.receiveMessage[Wrapped] { wrapped => probe.ref ! wrapped Behaviors.same }.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => probe.ref ! "stopped" Behaviors.same } @@ -220,30 +220,30 @@ class MessageAdapterSpec extends ScalaTestWithActorTestKit(MessageAdapterSpec.co case class Pong(greeting: String) case class Wrapped(response: Pong) - val pingPong = spawn(Behaviors.receiveMessage[Ping] { ping ⇒ + val pingPong = spawn(Behaviors.receiveMessage[Ping] { ping => ping.sender ! Pong("hello") Behaviors.same }) val probe = TestProbe[Any]() - val snitch = Behaviors.setup[Wrapped] { context ⇒ + val snitch = Behaviors.setup[Wrapped] { context => - val replyTo = context.messageAdapter[Pong] { pong ⇒ + val replyTo = context.messageAdapter[Pong] { pong => Wrapped(pong) } - (1 to 5).foreach { _ ⇒ + (1 to 5).foreach { _ => pingPong ! Ping(replyTo) } - def behv(count: Int): Behavior[Wrapped] = Behaviors.receiveMessage[Wrapped] { wrapped ⇒ + def behv(count: Int): Behavior[Wrapped] = Behaviors.receiveMessage[Wrapped] { wrapped => probe.ref ! count if (count == 3) { throw new TestException("boom") } behv(count + 1) }.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => probe.ref ! "stopped" Behaviors.same } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/OnSignalSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/OnSignalSpec.scala index 2ea72b6d91..9dcb791a45 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/OnSignalSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/OnSignalSpec.scala @@ -16,11 +16,11 @@ final class OnSignalSpec extends ScalaTestWithActorTestKit with WordSpecLike { "must correctly install the signal handler" in { val probe = TestProbe[Done]("probe") val behavior = - Behaviors.setup[Nothing] { context ⇒ + Behaviors.setup[Nothing] { context => val stoppedChild = context.spawn(Behaviors.stopped, "stopped-child") context.watch(stoppedChild) Behaviors.receiveSignal[Nothing] { - case (_, Terminated(`stoppedChild`)) ⇒ + case (_, Terminated(`stoppedChild`)) => probe.ref ! Done Behaviors.stopped } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ReceivePartialSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ReceivePartialSpec.scala index 3cd48dec14..e2e3a9946c 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ReceivePartialSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/ReceivePartialSpec.scala @@ -18,7 +18,7 @@ class ReceivePartialSpec extends ScalaTestWithActorTestKit with WordSpecLike { val probe = TestProbe[Command]("probe") val behavior = Behaviors.receiveMessagePartial[Command] { - case Command2 ⇒ + case Command2 => probe.ref ! Command2 Behaviors.same } @@ -35,7 +35,7 @@ class ReceivePartialSpec extends ScalaTestWithActorTestKit with WordSpecLike { val probe = TestProbe[Command]("probe") val behavior = Behaviors.receivePartial[Command] { - case (_, Command2) ⇒ + case (_, Command2) => probe.ref ! Command2 Behaviors.same } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/RoutersSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/RoutersSpec.scala index 4ee8530268..ed7396452d 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/RoutersSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/RoutersSpec.scala @@ -25,13 +25,9 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" implicit val untypedSystem = system.toUntyped def compileOnlyApiCoverage(): Unit = { - Routers.group(ServiceKey[String]("key")) - .withRandomRouting() - .withRoundRobinRouting() + Routers.group(ServiceKey[String]("key")).withRandomRouting().withRoundRobinRouting() - Routers.pool(10)(Behavior.empty[Any]) - .withRandomRouting() - .withRoundRobinRouting() + Routers.pool(10)(Behavior.empty[Any]).withRandomRouting().withRoundRobinRouting() } "The router pool" must { @@ -40,30 +36,32 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" val childCounter = new AtomicInteger(0) case class Ack(msg: String, recipient: Int) val probe = createTestProbe[AnyRef]() - val pool = spawn(Routers.pool[String](4)(Behaviors.setup { _ ⇒ + val pool = spawn(Routers.pool[String](4)(Behaviors.setup { _ => val id = childCounter.getAndIncrement() probe.ref ! s"started $id" - Behaviors.receiveMessage { msg ⇒ + Behaviors.receiveMessage { msg => probe.ref ! Ack(msg, id) Behaviors.same } })) // ordering of these msgs is not guaranteed - val expectedStarted = (0 to 3).map { n ⇒ s"started $n" }.toSet + val expectedStarted = (0 to 3).map { n => + s"started $n" + }.toSet probe.receiveMessages(4).toSet should ===(expectedStarted) // send one message at a time and see we rotate over all children, note that we don't necessarily // know what order the logic is rotating over the children, so we just check we reach all of them - val sent = (0 to 8).map { n ⇒ + val sent = (0 to 8).map { n => val msg = s"message-$n" pool ! msg msg } - val acks = (0 to 8).map(_ ⇒ probe.expectMessageType[Ack]) + val acks = (0 to 8).map(_ => probe.expectMessageType[Ack]) val (recipients, messages) = acks.foldLeft[(Set[Int], Set[String])]((Set.empty, Set.empty)) { - case ((recipients, messages), ack) ⇒ + case ((recipients, messages), ack) => (recipients + ack.recipient, messages + ack.msg) } recipients should ===(Set(0, 1, 2, 3)) @@ -72,11 +70,11 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" "keep routing to the rest of the children if some children stops" in { val probe = createTestProbe[String]() - val pool = spawn(Routers.pool[String](4)(Behaviors.setup { _ ⇒ + val pool = spawn(Routers.pool[String](4)(Behaviors.setup { _ => Behaviors.receiveMessage { - case "stop" ⇒ + case "stop" => Behaviors.stopped - case msg ⇒ + case msg => probe.ref ! msg Behaviors.same } @@ -91,25 +89,25 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" // deliver messages to it, which will end up in dead letters. // this test protects against that by waiting for the log entry to show up - val responses = (0 to 4).map { n ⇒ + val responses = (0 to 4).map { n => val msg = s"message-$n" pool ! msg probe.expectMessageType[String] } - responses should contain allOf ("message-0", "message-1", "message-2", "message-3", "message-4") + (responses should contain).allOf("message-0", "message-1", "message-2", "message-3", "message-4") } "stops if all children stops" in { val probe = createTestProbe() - val pool = spawn(Routers.pool[String](4)(Behaviors.setup { _ ⇒ - Behaviors.receiveMessage { _ ⇒ + val pool = spawn(Routers.pool[String](4)(Behaviors.setup { _ => + Behaviors.receiveMessage { _ => Behaviors.stopped } })) EventFilter.info(start = "Last pool child stopped, stopping pool", occurrences = 1).intercept { - (0 to 3).foreach { _ ⇒ + (0 to 3).foreach { _ => pool ! "stop" } probe.expectTerminated(pool) @@ -125,12 +123,12 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" "route messages across routees registered to the receptionist" in { val serviceKey = ServiceKey[String]("group-routing-1") val probe = createTestProbe[String]() - val routeeBehavior: Behavior[String] = Behaviors.receiveMessage { msg ⇒ + val routeeBehavior: Behavior[String] = Behaviors.receiveMessage { msg => probe.ref ! msg Behaviors.same } - (0 to 3).foreach { n ⇒ + (0 to 3).foreach { n => val ref = spawn(routeeBehavior, s"group-1-routee-$n") system.receptionist ! Receptionist.register(serviceKey, ref) } @@ -140,7 +138,7 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" // give the group a little time to get a listing from the receptionist Thread.sleep(receptionistDelayMs) - (0 to 3).foreach { n ⇒ + (0 to 3).foreach { n => val msg = s"message-$n" group ! msg probe.expectMessage(msg) @@ -155,13 +153,13 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" val probe = TestProbe[DeadLetter]() system.toUntyped.eventStream.subscribe(probe.ref.toUntyped, classOf[DeadLetter]) - (0 to 3).foreach { n ⇒ + (0 to 3).foreach { n => val msg = s"message-$n" /* FIXME cant watch log events until #26432 is fixed EventFilter.info(start = "Message [java.lang.String] ... was not delivered.", occurrences = 1).intercept { */ group ! msg probe.expectMessageType[DeadLetter] - /* } */ + /* } */ } testKit.stop(group) @@ -171,9 +169,9 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" val serviceKey = ServiceKey[String]("group-routing-3") val probe = createTestProbe[String]() val routeeBehavior: Behavior[String] = Behaviors.receiveMessage { - case "stop" ⇒ + case "stop" => Behaviors.stopped - case msg ⇒ + case msg => probe.ref ! msg Behaviors.same } @@ -192,7 +190,7 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" // give the group a little time to get a listing from the receptionist Thread.sleep(receptionistDelayMs) - (0 to 3).foreach { n ⇒ + (0 to 3).foreach { n => val msg = s"message-$n" group ! msg probe.expectMessage(msg) @@ -203,7 +201,7 @@ class RoutersSpec extends ScalaTestWithActorTestKit(""" // give the group a little time to get an updated listing from the receptionist Thread.sleep(receptionistDelayMs) - (0 to 3).foreach { n ⇒ + (0 to 3).foreach { n => val msg = s"message-$n" group ! msg probe.expectMessage(msg) diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StashBufferSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StashBufferSpec.scala index 2b0ef1a896..516d0fea8f 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StashBufferSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StashBufferSpec.scala @@ -85,7 +85,7 @@ class StashBufferSpec extends WordSpec with Matchers { val valueInbox = TestInbox[String]() def behavior(state: String): Behavior[String] = - Behaviors.receive[String] { (_, message) ⇒ + Behaviors.receive[String] { (_, message) => if (message == "get") { valueInbox.ref ! state Behaviors.same @@ -108,12 +108,12 @@ class StashBufferSpec extends WordSpec with Matchers { val valueInbox = TestInbox[String]() def behavior(state: String): Behavior[String] = - Behaviors.receive[String] { (_, message) ⇒ + Behaviors.receive[String] { (_, message) => if (message == "get") { valueInbox.ref ! state Behaviors.same } else { - Behaviors.setup[String](_ ⇒ behavior(state + message)) + Behaviors.setup[String](_ => behavior(state + message)) } } @@ -131,7 +131,7 @@ class StashBufferSpec extends WordSpec with Matchers { val valueInbox = TestInbox[String]() def behavior(state: String): Behavior[String] = - Behaviors.receive[String] { (_, message) ⇒ + Behaviors.receive[String] { (_, message) => if (message == "get") { valueInbox.ref ! state Behaviors.same diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StashSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StashSpec.scala index d80c681499..5826b56f70 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StashSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StashSpec.scala @@ -28,46 +28,46 @@ object AbstractStashSpec { final case class GetStashSize(replyTo: ActorRef[Int]) extends Command val immutableStash: Behavior[Command] = - Behaviors.setup[Command] { _ ⇒ + Behaviors.setup[Command] { _ => val buffer = StashBuffer[Command](capacity = 10) def active(processed: Vector[String]): Behavior[Command] = - Behaviors.receive { (_, cmd) ⇒ + Behaviors.receive { (_, cmd) => cmd match { - case message: Msg ⇒ + case message: Msg => active(processed :+ message.s) - case GetProcessed(replyTo) ⇒ + case GetProcessed(replyTo) => replyTo ! processed Behaviors.same - case Stash ⇒ + case Stash => stashing(processed) - case GetStashSize(replyTo) ⇒ + case GetStashSize(replyTo) => replyTo ! 0 Behaviors.same - case UnstashAll ⇒ + case UnstashAll => Behaviors.unhandled - case Unstash ⇒ + case Unstash => Behaviors.unhandled - case u: Unstashed ⇒ + case u: Unstashed => throw new IllegalStateException(s"Unexpected $u in active") } } def stashing(processed: Vector[String]): Behavior[Command] = - Behaviors.receive { (context, cmd) ⇒ + Behaviors.receive { (context, cmd) => cmd match { - case message: Msg ⇒ + case message: Msg => buffer.stash(message) Behaviors.same - case g: GetProcessed ⇒ + case g: GetProcessed => buffer.stash(g) Behaviors.same - case GetStashSize(replyTo) ⇒ + case GetStashSize(replyTo) => replyTo ! buffer.size Behaviors.same - case UnstashAll ⇒ + case UnstashAll => buffer.unstashAll(context, active(processed)) - case Unstash ⇒ + case Unstash => context.log.debug(s"Unstash ${buffer.size}") if (buffer.isEmpty) active(processed) @@ -77,34 +77,34 @@ object AbstractStashSpec { context.log.debug(s"Unstash $numberOfMessages of ${buffer.size}, starting with ${buffer.head}") buffer.unstash(context, unstashing(processed), numberOfMessages, Unstashed) } - case Stash ⇒ + case Stash => Behaviors.unhandled - case u: Unstashed ⇒ + case u: Unstashed => throw new IllegalStateException(s"Unexpected $u in stashing") } } def unstashing(processed: Vector[String]): Behavior[Command] = - Behaviors.receive { (context, cmd) ⇒ + Behaviors.receive { (context, cmd) => cmd match { - case Unstashed(message: Msg) ⇒ + case Unstashed(message: Msg) => context.log.debug(s"unstashed $message") unstashing(processed :+ message.s) - case Unstashed(GetProcessed(replyTo)) ⇒ + case Unstashed(GetProcessed(replyTo)) => context.log.debug(s"unstashed GetProcessed") replyTo ! processed Behaviors.same - case message: Msg ⇒ + case message: Msg => context.log.debug(s"got $message in unstashing") buffer.stash(message) Behaviors.same - case g: GetProcessed ⇒ + case g: GetProcessed => context.log.debug(s"got GetProcessed in unstashing") buffer.stash(g) Behaviors.same - case Stash ⇒ + case Stash => stashing(processed) - case Unstash ⇒ + case Unstash => if (buffer.isEmpty) { context.log.debug(s"unstashing done") active(processed) @@ -114,12 +114,12 @@ object AbstractStashSpec { context.log.debug(s"Unstash $numberOfMessages of ${buffer.size}, starting with ${buffer.head}") buffer.unstash(context, unstashing(processed), numberOfMessages, Unstashed) } - case GetStashSize(replyTo) ⇒ + case GetStashSize(replyTo) => replyTo ! buffer.size Behaviors.same - case UnstashAll ⇒ + case UnstashAll => Behaviors.unhandled - case u: Unstashed ⇒ + case u: Unstashed => throw new IllegalStateException(s"Unexpected $u in unstashing") } } @@ -135,28 +135,28 @@ object AbstractStashSpec { override def onMessage(cmd: Command): Behavior[Command] = { cmd match { - case message: Msg ⇒ + case message: Msg => if (stashing) buffer.stash(message) else processed :+= message.s this - case g @ GetProcessed(replyTo) ⇒ + case g @ GetProcessed(replyTo) => if (stashing) buffer.stash(g) else replyTo ! processed this - case GetStashSize(replyTo) ⇒ + case GetStashSize(replyTo) => replyTo ! buffer.size this - case Stash ⇒ + case Stash => stashing = true this - case UnstashAll ⇒ + case UnstashAll => stashing = false buffer.unstashAll(context, this) - case Unstash ⇒ + case Unstash => if (buffer.isEmpty) { stashing = false this @@ -166,15 +166,15 @@ object AbstractStashSpec { context.log.debug(s"Unstash $numberOfMessages of ${buffer.size}, starting with ${buffer.head}") buffer.unstash(context, this, numberOfMessages, Unstashed) } - case Unstashed(message: Msg) ⇒ + case Unstashed(message: Msg) => context.log.debug(s"unstashed $message") processed :+= message.s this - case Unstashed(GetProcessed(replyTo)) ⇒ + case Unstashed(GetProcessed(replyTo)) => context.log.debug(s"unstashed GetProcessed") replyTo ! processed Behaviors.same - case _: Unstashed ⇒ + case _: Unstashed => Behaviors.unhandled } } @@ -192,7 +192,7 @@ class ImmutableStashSpec extends AbstractStashSpec { class MutableStashSpec extends AbstractStashSpec { import AbstractStashSpec._ def testQualifier: String = "mutable behavior" - def behaviorUnderTest: Behavior[Command] = Behaviors.setup(context ⇒ new MutableStash(context)) + def behaviorUnderTest: Behavior[Command] = Behaviors.setup(context => new MutableStash(context)) } abstract class AbstractStashSpec extends ScalaTestWithActorTestKit with WordSpecLike { @@ -262,7 +262,7 @@ class UnstashingSpec extends ScalaTestWithActorTestKit(""" private def slowStoppingChild(latch: CountDownLatch): Behavior[String] = Behaviors.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => latch.await(10, TimeUnit.SECONDS) Behaviors.same } @@ -270,48 +270,48 @@ class UnstashingSpec extends ScalaTestWithActorTestKit(""" private def stashingBehavior( probe: ActorRef[String], withSlowStoppingChild: Option[CountDownLatch] = None) = { - Behaviors.setup[String] { ctx ⇒ + Behaviors.setup[String] { ctx => - withSlowStoppingChild.foreach(latch ⇒ ctx.spawnAnonymous(slowStoppingChild(latch))) + withSlowStoppingChild.foreach(latch => ctx.spawnAnonymous(slowStoppingChild(latch))) val stash = StashBuffer[String](10) def unstashing(n: Int): Behavior[String] = Behaviors.receiveMessage[String] { - case "stash" ⇒ + case "stash" => probe.ref ! s"unstashing-$n" unstashing(n + 1) - case "stash-fail" ⇒ + case "stash-fail" => probe.ref ! s"stash-fail-$n" throw TestException("unstash-fail") - case "get-current" ⇒ + case "get-current" => probe.ref ! s"current-$n" Behaviors.same - case "get-stash-size" ⇒ + case "get-stash-size" => probe.ref ! s"stash-size-${stash.size}" Behaviors.same - case "unstash" ⇒ + case "unstash" => // when testing resume stash.unstashAll(ctx, unstashing(n)) }.receiveSignal { - case (_, PreRestart) ⇒ + case (_, PreRestart) => probe.ref ! s"pre-restart-$n" Behaviors.same - case (_, PostStop) ⇒ + case (_, PostStop) => probe.ref ! s"post-stop-$n" Behaviors.same } Behaviors.receiveMessage[String] { - case msg if msg.startsWith("stash") ⇒ + case msg if msg.startsWith("stash") => stash.stash(msg) Behavior.same - case "unstash" ⇒ + case "unstash" => stash.unstashAll(ctx, unstashing(0)) - case "get-current" ⇒ + case "get-current" => probe.ref ! s"current-00" Behaviors.same - case "get-stash-size" ⇒ + case "get-stash-size" => probe.ref ! s"stash-size-${stash.size}" Behaviors.same } @@ -327,12 +327,12 @@ class UnstashingSpec extends ScalaTestWithActorTestKit(""" val probe = TestProbe[String]() // unstashing is inside setup val ref = spawn(Behaviors.receive[String] { - case (ctx, "unstash") ⇒ + case (ctx, "unstash") => val stash = StashBuffer[String](10) stash.stash("one") stash.unstashAll(ctx, Behavior.same) - case (_, msg) ⇒ + case (_, msg) => probe.ref ! msg Behaviors.same }) @@ -345,11 +345,11 @@ class UnstashingSpec extends ScalaTestWithActorTestKit(""" val probe = TestProbe[String]() // unstashing is inside setup val ref = spawn(Behaviors.receivePartial[String] { - case (ctx, "unstash") ⇒ + case (ctx, "unstash") => val stash = StashBuffer[String](10) stash.stash("one") stash.stash("two") - stash.unstashAll(ctx, Behaviors.receiveMessage { msg ⇒ + stash.unstashAll(ctx, Behaviors.receiveMessage { msg => probe.ref ! msg Behaviors.same }) @@ -369,12 +369,12 @@ class UnstashingSpec extends ScalaTestWithActorTestKit(""" val probe = TestProbe[String]() // unstashing is inside setup val ref = spawn(Behaviors.supervise(Behaviors.receivePartial[String] { - case (ctx, "unstash") ⇒ + case (ctx, "unstash") => val stash = StashBuffer[String](10) stash.stash("one") stash.unstashAll(ctx, Behavior.same) - case (_, msg) ⇒ + case (_, msg) => probe.ref ! msg Behaviors.same }).onFailure[TestException](SupervisorStrategy.stop)) @@ -389,11 +389,11 @@ class UnstashingSpec extends ScalaTestWithActorTestKit(""" val probe = TestProbe[String]() // unstashing is inside setup val ref = spawn(Behaviors.supervise(Behaviors.receivePartial[String] { - case (ctx, "unstash") ⇒ + case (ctx, "unstash") => val stash = StashBuffer[String](10) stash.stash("one") stash.stash("two") - stash.unstashAll(ctx, Behaviors.receiveMessage { msg ⇒ + stash.unstashAll(ctx, Behaviors.receiveMessage { msg => probe.ref ! msg Behaviors.same }) @@ -559,7 +559,7 @@ class UnstashingSpec extends ScalaTestWithActorTestKit(""" "be possible in combination with setup" in { val probe = TestProbe[String]() - val ref = spawn(Behaviors.setup[String] { _ ⇒ + val ref = spawn(Behaviors.setup[String] { _ => val stash = StashBuffer[String](10) stash.stash("one") @@ -568,11 +568,11 @@ class UnstashingSpec extends ScalaTestWithActorTestKit(""" // unstashing is inside setup new AbstractBehavior[String] { override def onMessage(msg: String): Behavior[String] = msg match { - case "unstash" ⇒ - Behaviors.setup[String] { ctx ⇒ + case "unstash" => + Behaviors.setup[String] { ctx => stash.unstashAll(ctx, this) } - case _ ⇒ + case _ => probe.ref ! msg Behavior.same } diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StopSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StopSpec.scala index 0eb05aca20..cb467bdf45 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StopSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/StopSpec.scala @@ -23,9 +23,9 @@ class StopSpec extends ScalaTestWithActorTestKit with WordSpecLike { "execute the post stop" in { val sawSignal = Promise[Done]() - spawn(Behaviors.setup[AnyRef] { _ ⇒ + spawn(Behaviors.setup[AnyRef] { _ => Behaviors.stopped[AnyRef](Behaviors.receiveSignal[AnyRef] { - case (context, PostStop) ⇒ + case (context, PostStop) => sawSignal.success(Done) Behaviors.empty }) @@ -36,7 +36,7 @@ class StopSpec extends ScalaTestWithActorTestKit with WordSpecLike { // #25082 "execute the post stop when wrapped" in { val sawSignal = Promise[Done]() - val ref = spawn(Behaviors.setup[AnyRef] { _ ⇒ + val ref = spawn(Behaviors.setup[AnyRef] { _ => Behaviors.intercept( new BehaviorInterceptor[AnyRef, AnyRef] { override def aroundReceive(context: typed.TypedActorContext[AnyRef], message: AnyRef, target: ReceiveTarget[AnyRef]): Behavior[AnyRef] = { @@ -48,7 +48,7 @@ class StopSpec extends ScalaTestWithActorTestKit with WordSpecLike { } } )(Behaviors.stopped[AnyRef](Behaviors.receiveSignal[AnyRef] { - case (context, PostStop) ⇒ + case (context, PostStop) => sawSignal.success(Done) Behaviors.empty })) @@ -61,7 +61,7 @@ class StopSpec extends ScalaTestWithActorTestKit with WordSpecLike { "execute the post stop early" in { val sawSignal = Promise[Done]() spawn(Behaviors.stopped[AnyRef](Behaviors.receiveSignal[AnyRef] { - case (context, PostStop) ⇒ + case (context, PostStop) => sawSignal.success(Done) Behaviors.empty })) @@ -76,7 +76,7 @@ class StopSpec extends ScalaTestWithActorTestKit with WordSpecLike { val ex = intercept[IllegalArgumentException] { Behaviors.stopped( // illegal: - Behaviors.setup[String] { _ ⇒ + Behaviors.setup[String] { _ => throw TestException("boom!") } ) diff --git a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/adapter/AdapterSpec.scala b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/adapter/AdapterSpec.scala index e7cdd3be51..d48b2c7e15 100644 --- a/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/adapter/AdapterSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/akka/actor/typed/scaladsl/adapter/AdapterSpec.scala @@ -17,15 +17,15 @@ import akka.actor.typed.Terminated import akka.testkit._ import akka.Done import akka.NotUsed -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } object AdapterSpec { val untyped1: untyped.Props = untyped.Props(new Untyped1) class Untyped1 extends untyped.Actor { def receive = { - case "ping" ⇒ sender() ! "pong" - case t: ThrowIt ⇒ throw t + case "ping" => sender() ! "pong" + case t: ThrowIt => throw t } } @@ -33,48 +33,48 @@ object AdapterSpec { class UntypedForwarder(ref: untyped.ActorRef) extends untyped.Actor { def receive = { - case a: String ⇒ ref ! a + case a: String => ref ! a } } def typed1(ref: untyped.ActorRef, probe: ActorRef[String]): Behavior[String] = Behaviors.receive[String] { - (context, message) ⇒ + (context, message) => message match { - case "send" ⇒ + case "send" => val replyTo = context.self.toUntyped ref.tell("ping", replyTo) Behaviors.same - case "pong" ⇒ + case "pong" => probe ! "ok" Behaviors.same - case "actorOf" ⇒ + case "actorOf" => val child = context.actorOf(untyped1) child.tell("ping", context.self.toUntyped) Behaviors.same - case "watch" ⇒ + case "watch" => context.watch(ref) Behaviors.same - case "supervise-stop" ⇒ + case "supervise-stop" => val child = context.actorOf(untyped1) context.watch(child) child ! ThrowIt3 child.tell("ping", context.self.toUntyped) Behaviors.same - case "stop-child" ⇒ + case "stop-child" => val child = context.actorOf(untyped1) context.watch(child) context.stop(child) Behaviors.same } } receiveSignal { - case (context, Terminated(ref)) ⇒ + case (context, Terminated(ref)) => probe ! "terminated" Behaviors.same } - def unhappyTyped(msg: String): Behavior[String] = Behaviors.setup[String] { ctx ⇒ - val child = ctx.spawnAnonymous(Behaviors.receiveMessage[String] { _ ⇒ + def unhappyTyped(msg: String): Behavior[String] = Behaviors.setup[String] { ctx => + val child = ctx.spawnAnonymous(Behaviors.receiveMessage[String] { _ => throw TestException(msg) }) child ! "throw please" @@ -96,13 +96,13 @@ object AdapterSpec { override val supervisorStrategy = untyped.OneForOneStrategy() { ({ - case ThrowIt1 ⇒ + case ThrowIt1 => probe ! "thrown-stop" untyped.SupervisorStrategy.Stop - case ThrowIt2 ⇒ + case ThrowIt2 => probe ! "thrown-resume" untyped.SupervisorStrategy.Resume - case ThrowIt3 ⇒ + case ThrowIt3 => probe ! "thrown-restart" // TODO Restart will not really restart the behavior untyped.SupervisorStrategy.Restart @@ -110,26 +110,26 @@ object AdapterSpec { } def receive = { - case "send" ⇒ ref ! Ping(self) // implicit conversion - case "pong" ⇒ probe ! "ok" - case "spawn" ⇒ + case "send" => ref ! Ping(self) // implicit conversion + case "pong" => probe ! "ok" + case "spawn" => val child = context.spawnAnonymous(typed2) child ! Ping(self) - case "actorOf-props" ⇒ + case "actorOf-props" => // this is how Cluster Sharding can be used val child = context.actorOf(typed2Props) child ! Ping(self) - case "watch" ⇒ + case "watch" => context.watch(ref) - case untyped.Terminated(_) ⇒ + case untyped.Terminated(_) => probe ! "terminated" - case "supervise-stop" ⇒ + case "supervise-stop" => testSupervice(ThrowIt1) - case "supervise-resume" ⇒ + case "supervise-resume" => testSupervice(ThrowIt2) - case "supervise-restart" ⇒ + case "supervise-restart" => testSupervice(ThrowIt3) - case "stop-child" ⇒ + case "stop-child" => val child = context.spawnAnonymous(typed2) context.watch(child) context.stop(child) @@ -144,14 +144,14 @@ object AdapterSpec { } def typed2: Behavior[Typed2Msg] = - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => message match { - case Ping(replyTo) ⇒ + case Ping(replyTo) => replyTo ! "pong" Behaviors.same - case StopIt ⇒ + case StopIt => Behaviors.stopped - case t: ThrowIt ⇒ + case t: ThrowIt => throw t } } @@ -175,22 +175,22 @@ class AdapterSpec extends AkkaSpec( } "not crash if guardian is stopped" in { - for { _ ← 0 to 10 } { + for { _ <- 0 to 10 } { var system: akka.actor.typed.ActorSystem[NotUsed] = null try { - system = ActorSystem.create(Behaviors.setup[NotUsed](_ ⇒ Behavior.stopped[NotUsed]), "AdapterSpec-stopping-guardian") + system = ActorSystem.create(Behaviors.setup[NotUsed](_ => Behavior.stopped[NotUsed]), "AdapterSpec-stopping-guardian") } finally if (system != null) shutdown(system.toUntyped) } } "not crash if guardian is stopped very quickly" in { - for { _ ← 0 to 10 } { + for { _ <- 0 to 10 } { var system: akka.actor.typed.ActorSystem[Done] = null try { - system = ActorSystem.create(Behaviors.receive[Done] { (context, message) ⇒ + system = ActorSystem.create(Behaviors.receive[Done] { (context, message) => context.self ! Done message match { - case Done ⇒ Behaviors.stopped + case Done => Behaviors.stopped } }, "AdapterSpec-stopping-guardian-2") diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/DispatchersDocSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/DispatchersDocSpec.scala index fcfcb8413e..b149e8589c 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/DispatchersDocSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/DispatchersDocSpec.scala @@ -33,14 +33,14 @@ object DispatchersDocSpec { case class WhichDispatcher(replyTo: ActorRef[Dispatcher]) - val giveMeYourDispatcher = Behaviors.receive[WhichDispatcher] { (context, message) ⇒ + val giveMeYourDispatcher = Behaviors.receive[WhichDispatcher] { (context, message) => message.replyTo ! context.executionContext.asInstanceOf[Dispatcher] Behaviors.same } val yourBehavior: Behavior[String] = Behaviors.same - val example = Behaviors.receive[Any] { (context, message) ⇒ + val example = Behaviors.receive[Any] { (context, message) => //#spawn-dispatcher import akka.actor.typed.DispatcherSelector diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/FSMDocSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/FSMDocSpec.scala index 2533c0b609..675f917933 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/FSMDocSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/FSMDocSpec.scala @@ -31,26 +31,26 @@ object FSMDocSpec { //#simple-state // states of the FSM represented as behaviors - def idle(data: Data): Behavior[Event] = Behaviors.receiveMessage[Event] { message: Event ⇒ + def idle(data: Data): Behavior[Event] = Behaviors.receiveMessage[Event] { message: Event => (message, data) match { - case (SetTarget(ref), Uninitialized) ⇒ + case (SetTarget(ref), Uninitialized) => idle(Todo(ref, Vector.empty)) - case (Queue(obj), t @ Todo(_, v)) ⇒ + case (Queue(obj), t @ Todo(_, v)) => active(t.copy(queue = v :+ obj)) - case _ ⇒ + case _ => Behaviors.unhandled } } def active(data: Todo): Behavior[Event] = - Behaviors.withTimers[Event] { timers ⇒ + Behaviors.withTimers[Event] { timers => // instead of FSM state timeout timers.startSingleTimer(Timeout, Timeout, 1.second) Behaviors.receiveMessagePartial { - case Flush | Timeout ⇒ + case Flush | Timeout => data.target ! Batch(data.queue) idle(data.copy(queue = Vector.empty)) - case Queue(obj) ⇒ + case Queue(obj) => active(data.copy(queue = data.queue :+ obj)) } } diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/FaultToleranceDocSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/FaultToleranceDocSpec.scala index b5fd6b7090..0ec8450810 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/FaultToleranceDocSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/FaultToleranceDocSpec.scala @@ -25,13 +25,13 @@ class FaultToleranceDocSpec extends ScalaTestWithActorTestKit( sealed trait Message case class Fail(text: String) extends Message - val worker = Behaviors.receive[Message] { (context, message) ⇒ + val worker = Behaviors.receive[Message] { (context, message) => message match { - case Fail(text) ⇒ throw new RuntimeException(text) + case Fail(text) => throw new RuntimeException(text) } } - val middleManagementBehavior = Behaviors.setup[Message] { context ⇒ + val middleManagementBehavior = Behaviors.setup[Message] { context => context.log.info("Middle management starting up") val child = context.spawn(worker, "child") context.watch(child) @@ -39,13 +39,13 @@ class FaultToleranceDocSpec extends ScalaTestWithActorTestKit( // here we don't handle Terminated at all which means that // when the child fails or stops gracefully this actor will // fail with a DeathWatchException - Behaviors.receive[Message] { (context, message) ⇒ + Behaviors.receive[Message] { (context, message) => child ! message Behaviors.same } } - val bossBehavior = Behaviors.supervise(Behaviors.setup[Message] { context ⇒ + val bossBehavior = Behaviors.supervise(Behaviors.setup[Message] { context => context.log.info("Boss starting up") val middleManagement = context.spawn(middleManagementBehavior, "middle-management") context.watch(middleManagement) @@ -53,7 +53,7 @@ class FaultToleranceDocSpec extends ScalaTestWithActorTestKit( // here we don't handle Terminated at all which means that // when middle management fails with a DeathWatchException // this actor will also fail - Behaviors.receiveMessage[Message] { message ⇒ + Behaviors.receiveMessage[Message] { message => middleManagement ! message Behaviors.same } diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/GracefulStopDocSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/GracefulStopDocSpec.scala index 407205f438..b9147b63be 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/GracefulStopDocSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/GracefulStopDocSpec.scala @@ -28,26 +28,26 @@ object GracefulStopDocSpec { // Predefined cleanup operation def cleanup(log: Logger): Unit = log.info("Cleaning up!") - val mcpa = Behaviors.receive[JobControlLanguage] { (context, message) ⇒ + val mcpa = Behaviors.receive[JobControlLanguage] { (context, message) => message match { - case SpawnJob(jobName) ⇒ + case SpawnJob(jobName) => context.log.info("Spawning job {}!", jobName) context.spawn(Job.job(jobName), name = jobName) Behaviors.same - case GracefulShutdown ⇒ + case GracefulShutdown => context.log.info("Initiating graceful shutdown...") // perform graceful stop, executing cleanup before final system termination // behavior executing cleanup is passed as a parameter to Actor.stopped Behaviors.stopped { Behaviors.receiveSignal { - case (context, PostStop) ⇒ + case (context, PostStop) => cleanup(context.system.log) Behaviors.same } } } }.receiveSignal { - case (context, PostStop) ⇒ + case (context, PostStop) => context.log.info("MCPA stopped") Behaviors.same } @@ -60,7 +60,7 @@ object GracefulStopDocSpec { import GracefulStopDocSpec.MasterControlProgramActor.JobControlLanguage def job(name: String) = Behaviors.receiveSignal[JobControlLanguage] { - case (context, PostStop) ⇒ + case (context, PostStop) => context.log.info("Worker {} stopped", name) Behaviors.same } diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/InteractionPatternsSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/InteractionPatternsSpec.scala index d175ef6732..9c02340fd4 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/InteractionPatternsSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/InteractionPatternsSpec.scala @@ -27,7 +27,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik case class PrintMe(message: String) val printerBehavior: Behavior[PrintMe] = Behaviors.receive { - case (context, PrintMe(message)) ⇒ + case (context, PrintMe(message)) => context.log.info(message) Behaviors.same } @@ -56,7 +56,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik // #request-response-respond val otherBehavior = Behaviors.receiveMessage[Request] { - case Request(query, respondTo) ⇒ + case Request(query, respondTo) => // ... process query ... respondTo ! Response("Here's your cookies!") Behaviors.same @@ -101,27 +101,27 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik private final case class WrappedBackendResponse(response: Backend.Response) extends Command def translator(backend: ActorRef[Backend.Request]): Behavior[Command] = - Behaviors.setup[Command] { context ⇒ + Behaviors.setup[Command] { context => val backendResponseMapper: ActorRef[Backend.Response] = - context.messageAdapter(rsp ⇒ WrappedBackendResponse(rsp)) + context.messageAdapter(rsp => WrappedBackendResponse(rsp)) def active( inProgress: Map[Int, ActorRef[URI]], count: Int): Behavior[Command] = { Behaviors.receiveMessage[Command] { - case Translate(site, replyTo) ⇒ + case Translate(site, replyTo) => val taskId = count + 1 backend ! Backend.StartTranslationJob(taskId, site, backendResponseMapper) active(inProgress.updated(taskId, replyTo), taskId) - case wrapped: WrappedBackendResponse ⇒ wrapped.response match { - case Backend.JobStarted(taskId) ⇒ + case wrapped: WrappedBackendResponse => wrapped.response match { + case Backend.JobStarted(taskId) => context.log.info("Started {}", taskId) Behaviors.same - case Backend.JobProgress(taskId, progress) ⇒ + case Backend.JobProgress(taskId, progress) => context.log.info("Progress {}: {}", taskId, progress) Behaviors.same - case Backend.JobCompleted(taskId, result) ⇒ + case Backend.JobCompleted(taskId, result) => context.log.info("Completed {}: {}", taskId, result) inProgress(taskId) ! result active(inProgress - taskId, count) @@ -135,7 +135,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik // #adapted-response val backend = spawn(Behaviors.receiveMessage[Backend.Request] { - case Backend.StartTranslationJob(taskId, site, replyTo) ⇒ + case Backend.StartTranslationJob(taskId, site, replyTo) => replyTo ! Backend.JobStarted(taskId) replyTo ! Backend.JobProgress(taskId, 0.25) replyTo ! Backend.JobProgress(taskId, 0.50) @@ -163,12 +163,12 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik case object Timeout extends Msg def behavior(target: ActorRef[Batch], after: FiniteDuration, maxSize: Int): Behavior[Msg] = { - Behaviors.withTimers(timers ⇒ idle(timers, target, after, maxSize)) + Behaviors.withTimers(timers => idle(timers, target, after, maxSize)) } def idle(timers: TimerScheduler[Msg], target: ActorRef[Batch], after: FiniteDuration, maxSize: Int): Behavior[Msg] = { - Behaviors.receiveMessage[Msg] { message ⇒ + Behaviors.receiveMessage[Msg] { message => timers.startSingleTimer(TimerKey, Timeout, after) active(Vector(message), timers, target, after, maxSize) } @@ -177,10 +177,10 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik def active(buffer: Vector[Msg], timers: TimerScheduler[Msg], target: ActorRef[Batch], after: FiniteDuration, maxSize: Int): Behavior[Msg] = { Behaviors.receiveMessage[Msg] { - case Timeout ⇒ + case Timeout => target ! Batch(buffer) idle(timers, target, after, maxSize) - case m ⇒ + case m => val newBuffer = buffer :+ m if (newBuffer.size == maxSize) { timers.cancel(TimerKey) @@ -207,7 +207,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik case class HalResponse(message: String) val halBehavior = Behaviors.receiveMessage[HalCommand] { - case OpenThePodBayDoorsPlease(respondTo) ⇒ + case OpenThePodBayDoorsPlease(respondTo) => respondTo ! HalResponse("I'm sorry, Dave. I'm afraid I can't do that.") Behaviors.same } @@ -216,7 +216,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik // this is a part of the protocol that is internal to the actor itself case class AdaptedResponse(message: String) extends DaveMessage - def daveBehavior(hal: ActorRef[HalCommand]) = Behaviors.setup[DaveMessage] { context ⇒ + def daveBehavior(hal: ActorRef[HalCommand]) = Behaviors.setup[DaveMessage] { context => // asking someone requires a timeout, if the timeout hits without response // the ask is failed with a TimeoutException @@ -227,8 +227,8 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik // that is what we are passing as the second parameter here it could also be written // as `ref => OpenThePodBayDoorsPlease(ref)` context.ask(hal)(OpenThePodBayDoorsPlease) { - case Success(HalResponse(message)) ⇒ AdaptedResponse(message) - case Failure(ex) ⇒ AdaptedResponse("Request failed") + case Success(HalResponse(message)) => AdaptedResponse(message) + case Failure(ex) => AdaptedResponse("Request failed") } // we can also tie in request context into an interaction, it is safe to look at @@ -237,14 +237,14 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik // use immutable state we have closed over like here. val requestId = 1 context.ask(hal)(OpenThePodBayDoorsPlease) { - case Success(HalResponse(message)) ⇒ AdaptedResponse(s"$requestId: $message") - case Failure(ex) ⇒ AdaptedResponse(s"$requestId: Request failed") + case Success(HalResponse(message)) => AdaptedResponse(s"$requestId: $message") + case Failure(ex) => AdaptedResponse(s"$requestId: Request failed") } Behaviors.receiveMessage { // the adapted message ends up being processed like any other // message sent to the actor - case AdaptedResponse(message) ⇒ + case AdaptedResponse(message) => context.log.info("Got response from hal: {}", message) Behaviors.same } @@ -268,12 +268,12 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik // #per-session-child val keyCabinetBehavior: Behavior[GetKeys] = Behaviors.receiveMessage { - case GetKeys(_, respondTo) ⇒ + case GetKeys(_, respondTo) => respondTo ! Keys() Behaviors.same } val drawerBehavior: Behavior[GetWallet] = Behaviors.receiveMessage { - case GetWallet(_, respondTo) ⇒ + case GetWallet(_, respondTo) => respondTo ! Wallet() Behaviors.same } @@ -287,12 +287,12 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik case class GetKeys(whoseKeys: String, respondTo: ActorRef[Keys]) case class GetWallet(whoseWallet: String, respondTo: ActorRef[Wallet]) - def homeBehavior = Behaviors.receive[HomeCommand] { (context, message) ⇒ + def homeBehavior = Behaviors.receive[HomeCommand] { (context, message) => val keyCabinet: ActorRef[GetKeys] = context.spawn(keyCabinetBehavior, "key-cabinet") val drawer: ActorRef[GetWallet] = context.spawn(drawerBehavior, "drawer") message match { - case LeaveHome(who, respondTo) ⇒ + case LeaveHome(who, respondTo) => context.spawn(prepareToLeaveHome(who, respondTo, keyCabinet, drawer), s"leaving-$who") Behavior.same } @@ -307,7 +307,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik // we don't _really_ care about the actor protocol here as nobody will send us // messages except for responses to our queries, so we just accept any kind of message // but narrow that to more limited types then we interact - Behaviors.setup[AnyRef] { context ⇒ + Behaviors.setup[AnyRef] { context => var wallet: Option[Wallet] = None var keys: Option[Keys] = None @@ -317,23 +317,23 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik def nextBehavior: Behavior[AnyRef] = (keys, wallet) match { - case (Some(w), Some(k)) ⇒ + case (Some(w), Some(k)) => // we got both, "session" is completed! respondTo ! ReadyToLeaveHome(whoIsLeaving, w, k) Behavior.stopped - case _ ⇒ + case _ => Behavior.same } Behaviors.receiveMessage { - case w: Wallet ⇒ + case w: Wallet => wallet = Some(w) nextBehavior - case k: Keys ⇒ + case k: Keys => keys = Some(k) nextBehavior - case _ ⇒ + case _ => Behaviors.unhandled } }.narrow[NotUsed] // we don't let anyone else know we accept anything @@ -354,7 +354,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik // #standalone-ask // keep this out of the sample as it uses the testkit spawn - val cookieActorRef = spawn(Behaviors.receiveMessage[GiveMeCookies] { message ⇒ + val cookieActorRef = spawn(Behaviors.receiveMessage[GiveMeCookies] { message => message.replyTo ! Cookies(5) Behaviors.same }) @@ -368,14 +368,14 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik implicit val timeout: Timeout = 3.seconds implicit val scheduler = system.scheduler - val result: Future[Cookies] = cookieActorRef.ask(ref ⇒ GiveMeCookies(ref)) + val result: Future[Cookies] = cookieActorRef.ask(ref => GiveMeCookies(ref)) // the response callback will be executed on this execution context implicit val ec = system.executionContext result.onComplete { - case Success(cookies) ⇒ println("Yay, cookies!") - case Failure(ex) ⇒ println("Boo! didn't get cookies in time.") + case Success(cookies) => println("Yay, cookies!") + case Failure(ex) => println("Boo! didn't get cookies in time.") } // #standalone-ask diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/IntroSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/IntroSpec.scala index 88485843e4..ef135a6e19 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/IntroSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/IntroSpec.scala @@ -27,7 +27,7 @@ object IntroSpec { final case class Greet(whom: String, replyTo: ActorRef[Greeted]) final case class Greeted(whom: String, from: ActorRef[Greet]) - val greeter: Behavior[Greet] = Behaviors.receive { (context, message) ⇒ + val greeter: Behavior[Greet] = Behaviors.receive { (context, message) => //#fiddle_code context.log.info("Hello {}!", message.whom) //#fiddle_code @@ -44,7 +44,7 @@ object IntroSpec { object HelloWorldBot { def bot(greetingCounter: Int, max: Int): Behavior[HelloWorld.Greeted] = - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => val n = greetingCounter + 1 //#fiddle_code context.log.info("Greeting {} for {}", n, message.whom) @@ -68,10 +68,10 @@ object IntroSpec { final case class Start(name: String) val main: Behavior[Start] = - Behaviors.setup { context ⇒ + Behaviors.setup { context => val greeter = context.spawn(HelloWorld.greeter, "greeter") - Behaviors.receiveMessage { message ⇒ + Behaviors.receiveMessage { message => val replyTo = context.spawn(HelloWorldBot.bot(greetingCounter = 0, max = 3), message.name) greeter ! HelloWorld.Greet(message.name, replyTo) Behaviors.same @@ -87,13 +87,13 @@ object IntroSpec { //#hello-world-main-with-dispatchers val main: Behavior[Start] = - Behaviors.setup { context ⇒ + Behaviors.setup { context => val dispatcherPath = "akka.actor.default-blocking-io-dispatcher" val props = DispatcherSelector.fromConfig(dispatcherPath) val greeter = context.spawn(HelloWorld.greeter, "greeter", props) - Behaviors.receiveMessage { message ⇒ + Behaviors.receiveMessage { message => val replyTo = context.spawn(HelloWorldBot.bot(greetingCounter = 0, max = 3), message.name) greeter ! HelloWorld.Greet(message.name, replyTo) @@ -131,16 +131,16 @@ object IntroSpec { chatRoom(List.empty) private def chatRoom(sessions: List[ActorRef[SessionCommand]]): Behavior[RoomCommand] = - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => message match { - case GetSession(screenName, client) ⇒ + case GetSession(screenName, client) => // create a child actor for further interaction with the client val ses = context.spawn( session(context.self, screenName, client), name = URLEncoder.encode(screenName, StandardCharsets.UTF_8.name)) client ! SessionGranted(ses) chatRoom(ses :: sessions) - case PublishSessionMessage(screenName, message) ⇒ + case PublishSessionMessage(screenName, message) => val notification = NotifyClient(MessagePosted(screenName, message)) sessions foreach (_ ! notification) Behaviors.same @@ -151,13 +151,13 @@ object IntroSpec { room: ActorRef[PublishSessionMessage], screenName: String, client: ActorRef[SessionEvent]): Behavior[SessionCommand] = - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => message match { - case PostMessage(message) ⇒ + case PostMessage(message) => // from client, publish to others via the room room ! PublishSessionMessage(screenName, message) Behaviors.same - case NotifyClient(message) ⇒ + case NotifyClient(message) => // published from the room client ! message Behaviors.same @@ -199,14 +199,14 @@ class IntroSpec extends ScalaTestWithActorTestKit with WordSpecLike { Behaviors.receiveMessage { //#chatroom-gabbler // We document that the compiler warns about the missing handler for `SessionDenied` - case SessionDenied(reason) ⇒ + case SessionDenied(reason) => println(s"cannot start chat room session: $reason") Behaviors.stopped //#chatroom-gabbler - case SessionGranted(handle) ⇒ + case SessionGranted(handle) => handle ! PostMessage("Hello World!") Behaviors.same - case MessagePosted(screenName, message) ⇒ + case MessagePosted(screenName, message) => println(s"message has been posted by '$screenName': $message") Behaviors.stopped } @@ -214,14 +214,14 @@ class IntroSpec extends ScalaTestWithActorTestKit with WordSpecLike { //#chatroom-main val main: Behavior[NotUsed] = - Behaviors.setup { context ⇒ + Behaviors.setup { context => val chatRoom = context.spawn(ChatRoom.behavior, "chatroom") val gabblerRef = context.spawn(gabbler, "gabbler") context.watch(gabblerRef) chatRoom ! GetSession("ol’ Gabbler", gabblerRef) Behaviors.receiveSignal { - case (_, Terminated(ref)) ⇒ + case (_, Terminated(ref)) => Behaviors.stopped } } diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/OOIntroSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/OOIntroSpec.scala index f1555b42fa..2e8db0507b 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/OOIntroSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/OOIntroSpec.scala @@ -42,14 +42,14 @@ object OOIntroSpec { //#chatroom-behavior def behavior(): Behavior[RoomCommand] = - Behaviors.setup[RoomCommand](context ⇒ new ChatRoomBehavior(context)) + Behaviors.setup[RoomCommand](context => new ChatRoomBehavior(context)) class ChatRoomBehavior(context: ActorContext[RoomCommand]) extends AbstractBehavior[RoomCommand] { private var sessions: List[ActorRef[SessionCommand]] = List.empty override def onMessage(message: RoomCommand): Behavior[RoomCommand] = { message match { - case GetSession(screenName, client) ⇒ + case GetSession(screenName, client) => // create a child actor for further interaction with the client val ses = context.spawn( session(context.self, screenName, client), @@ -57,7 +57,7 @@ object OOIntroSpec { client ! SessionGranted(ses) sessions = ses :: sessions this - case PublishSessionMessage(screenName, message) ⇒ + case PublishSessionMessage(screenName, message) => val notification = NotifyClient(MessagePosted(screenName, message)) sessions foreach (_ ! notification) this @@ -70,11 +70,11 @@ object OOIntroSpec { screenName: String, client: ActorRef[SessionEvent]): Behavior[SessionCommand] = Behaviors.receiveMessage { - case PostMessage(message) ⇒ + case PostMessage(message) => // from client, publish to others via the room room ! PublishSessionMessage(screenName, message) Behaviors.same - case NotifyClient(message) ⇒ + case NotifyClient(message) => // published from the room client ! message Behaviors.same @@ -96,13 +96,13 @@ class OOIntroSpec extends ScalaTestWithActorTestKit with WordSpecLike { val gabbler = Behaviors.receiveMessage[SessionEvent] { - case SessionDenied(reason) ⇒ + case SessionDenied(reason) => println(s"cannot start chat room session: $reason") Behaviors.stopped - case SessionGranted(handle) ⇒ + case SessionGranted(handle) => handle ! PostMessage("Hello World!") Behaviors.same - case MessagePosted(screenName, message) ⇒ + case MessagePosted(screenName, message) => println(s"message has been posted by '$screenName': $message") Behaviors.stopped } @@ -110,17 +110,17 @@ class OOIntroSpec extends ScalaTestWithActorTestKit with WordSpecLike { //#chatroom-main val main: Behavior[String] = - Behaviors.setup { context ⇒ + Behaviors.setup { context => val chatRoom = context.spawn(ChatRoom.behavior(), "chatroom") val gabblerRef = context.spawn(gabbler, "gabbler") context.watch(gabblerRef) Behaviors.receiveMessagePartial[String] { - case "go" ⇒ + case "go" => chatRoom ! GetSession("ol’ Gabbler", gabblerRef) Behaviors.same } receiveSignal { - case (_, Terminated(_)) ⇒ + case (_, Terminated(_)) => println("Stopping guardian") Behaviors.stopped } diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/RouterSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/RouterSpec.scala index b583de1266..7c167e29fa 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/RouterSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/RouterSpec.scala @@ -23,11 +23,11 @@ object RouterSpec { sealed trait Command case class DoLog(text: String) extends Command - val behavior: Behavior[Command] = Behaviors.setup { ctx ⇒ + val behavior: Behavior[Command] = Behaviors.setup { ctx => ctx.log.info("Starting worker") Behaviors.receiveMessage { - case DoLog(text) ⇒ + case DoLog(text) => ctx.log.info("Got message {}", text) Behaviors.same } @@ -45,7 +45,7 @@ class RouterSpec extends ScalaTestWithActorTestKit with WordSpecLike { "The routing sample" must { "show pool routing" in { - spawn(Behaviors.setup[Unit] { ctx ⇒ + spawn(Behaviors.setup[Unit] { ctx => // #pool // make sure the workers are restarted if they fail val supervisedWorker = Behaviors.supervise(Worker.behavior) @@ -53,7 +53,7 @@ class RouterSpec extends ScalaTestWithActorTestKit with WordSpecLike { val pool = Routers.pool(poolSize = 4)(supervisedWorker) val router = ctx.spawn(pool, "worker-pool") - (0 to 10).foreach { n ⇒ + (0 to 10).foreach { n => router ! Worker.DoLog(s"msg $n") } // #pool @@ -68,7 +68,7 @@ class RouterSpec extends ScalaTestWithActorTestKit with WordSpecLike { "show group routing" in { - spawn(Behaviors.setup[Unit] { ctx ⇒ + spawn(Behaviors.setup[Unit] { ctx => // #group // this would likely happen elsewhere - if we create it locally we // can just as well use a pool @@ -82,7 +82,7 @@ class RouterSpec extends ScalaTestWithActorTestKit with WordSpecLike { // guarantee the router has seen any workers yet if we hit it directly like this and // these messages may end up in dead letters - in a real application you would not use // a group router like this - it is to keep the sample simple - (0 to 10).foreach { n ⇒ + (0 to 10).foreach { n => router ! Worker.DoLog(s"msg $n") } // #group diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/SpawnProtocolDocSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/SpawnProtocolDocSpec.scala index e52ec4cc03..efd6502862 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/SpawnProtocolDocSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/SpawnProtocolDocSpec.scala @@ -33,7 +33,7 @@ object SpawnProtocolDocSpec { //#main object HelloWorldMain { val main: Behavior[SpawnProtocol] = - Behaviors.setup { context ⇒ + Behaviors.setup { context => // Start initial tasks // context.spawn(...) @@ -63,7 +63,7 @@ class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with WordSpecLike { val greeter: Future[ActorRef[HelloWorld.Greet]] = system.ask(SpawnProtocol.Spawn(behavior = HelloWorld.greeter, name = "greeter", props = Props.empty)) - val greetedBehavior = Behaviors.receive[HelloWorld.Greeted] { (context, message) ⇒ + val greetedBehavior = Behaviors.receive[HelloWorld.Greeted] { (context, message) => context.log.info("Greeting for {} from {}", message.whom, message.from) Behaviors.stopped } @@ -71,7 +71,7 @@ class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with WordSpecLike { val greetedReplyTo: Future[ActorRef[HelloWorld.Greeted]] = system.ask(SpawnProtocol.Spawn(greetedBehavior, name = "", props = Props.empty)) - for (greeterRef ← greeter; replyToRef ← greetedReplyTo) { + for (greeterRef <- greeter; replyToRef <- greetedReplyTo) { greeterRef ! HelloWorld.Greet("Akka", replyToRef) } diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/StashDocSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/StashDocSpec.scala index 3d4288fc76..b875571cfb 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/StashDocSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/StashDocSpec.scala @@ -33,19 +33,19 @@ object StashDocSpec { private final case class DBError(cause: Throwable) extends Command def behavior(id: String, db: DB): Behavior[Command] = - Behaviors.setup[Command] { context ⇒ + Behaviors.setup[Command] { context => val buffer = StashBuffer[Command](capacity = 100) def init(): Behavior[Command] = - Behaviors.receive[Command] { (context, message) ⇒ + Behaviors.receive[Command] { (context, message) => message match { - case InitialState(value) ⇒ + case InitialState(value) => // now we are ready to handle stashed messages if any buffer.unstashAll(context, active(value)) - case DBError(cause) ⇒ + case DBError(cause) => throw cause - case other ⇒ + case other => // stash all other messages for later processing buffer.stash(other) Behaviors.same @@ -53,37 +53,37 @@ object StashDocSpec { } def active(state: String): Behavior[Command] = - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => message match { - case Get(replyTo) ⇒ + case Get(replyTo) => replyTo ! state Behaviors.same - case Save(value, replyTo) ⇒ + case Save(value, replyTo) => context.pipeToSelf(db.save(id, value)) { - case Success(_) ⇒ SaveSuccess - case Failure(cause) ⇒ DBError(cause) + case Success(_) => SaveSuccess + case Failure(cause) => DBError(cause) } saving(value, replyTo) } } def saving(state: String, replyTo: ActorRef[Done]): Behavior[Command] = - Behaviors.receive[Command] { (context, message) ⇒ + Behaviors.receive[Command] { (context, message) => message match { - case SaveSuccess ⇒ + case SaveSuccess => replyTo ! Done buffer.unstashAll(context, active(state)) - case DBError(cause) ⇒ + case DBError(cause) => throw cause - case other ⇒ + case other => buffer.stash(other) Behaviors.same } } context.pipeToSelf(db.load(id)) { - case Success(value) ⇒ InitialState(value) - case Failure(cause) ⇒ DBError(cause) + case Success(value) => InitialState(value) + case Failure(cause) => DBError(cause) } init() diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/coexistence/TypedWatchingUntypedSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/coexistence/TypedWatchingUntypedSpec.scala index 9040d540ba..635f06c1c2 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/coexistence/TypedWatchingUntypedSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/coexistence/TypedWatchingUntypedSpec.scala @@ -13,7 +13,7 @@ import akka.actor.typed.scaladsl.adapter._ //#adapter-import import akka.testkit.TestProbe //#import-alias -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } //#import-alias import org.scalatest.WordSpec import scala.concurrent.duration._ @@ -27,7 +27,7 @@ object TypedWatchingUntypedSpec { case object Pong extends Command val behavior: Behavior[Command] = - Behaviors.setup { context ⇒ + Behaviors.setup { context => // context.actorOf is an implicit extension method val untyped = context.actorOf(Untyped.props(), "second") @@ -38,13 +38,13 @@ object TypedWatchingUntypedSpec { untyped.tell(Typed.Ping(context.self), context.self.toUntyped) Behaviors.receivePartial[Command] { - case (context, Pong) ⇒ + case (context, Pong) => // it's not possible to get the sender, that must be sent in message // context.stop is an implicit extension method context.stop(untyped) Behaviors.same } receiveSignal { - case (_, akka.actor.typed.Terminated(_)) ⇒ + case (_, akka.actor.typed.Terminated(_)) => Behaviors.stopped } } @@ -57,7 +57,7 @@ object TypedWatchingUntypedSpec { } class Untyped extends untyped.Actor { override def receive = { - case Typed.Ping(replyTo) ⇒ + case Typed.Ping(replyTo) => replyTo ! Typed.Pong } } diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/coexistence/UntypedWatchingTypedSpec.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/coexistence/UntypedWatchingTypedSpec.scala index 85b40aab9a..ea1e05eaa7 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/coexistence/UntypedWatchingTypedSpec.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/coexistence/UntypedWatchingTypedSpec.scala @@ -14,7 +14,7 @@ import akka.actor.typed.scaladsl.adapter._ //#adapter-import import akka.testkit.TestProbe //#import-alias -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } //#import-alias import org.scalatest.WordSpec @@ -40,11 +40,11 @@ object UntypedWatchingTypedSpec { second ! Typed.Ping(self) override def receive = { - case Typed.Pong ⇒ + case Typed.Pong => log.info(s"$self got Pong from ${sender()}") // context.stop is an implicit extension method context.stop(second) - case untyped.Terminated(ref) ⇒ + case untyped.Terminated(ref) => log.info(s"$self observed termination of $ref") context.stop(self) } @@ -58,9 +58,9 @@ object UntypedWatchingTypedSpec { case object Pong val behavior: Behavior[Command] = - Behaviors.receive { (context, message) ⇒ + Behaviors.receive { (context, message) => message match { - case Ping(replyTo) ⇒ + case Ping(replyTo) => context.log.info(s"${context.self} got Ping from $replyTo") // replyTo is an untyped actor that has been converted for coexistence replyTo ! Pong diff --git a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/supervision/SupervisionCompileOnly.scala b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/supervision/SupervisionCompileOnly.scala index 7dc1b03775..98593fe316 100644 --- a/akka-actor-typed-tests/src/test/scala/docs/akka/typed/supervision/SupervisionCompileOnly.scala +++ b/akka-actor-typed-tests/src/test/scala/docs/akka/typed/supervision/SupervisionCompileOnly.scala @@ -44,9 +44,9 @@ object SupervisionCompileOnly { case class GetCount(replyTo: ActorRef[Int]) extends Command def counter(count: Int): Behavior[Command] = Behaviors.receiveMessage[Command] { - case Increment(nr: Int) ⇒ + case Increment(nr: Int) => counter(count + nr) - case GetCount(replyTo) ⇒ + case GetCount(replyTo) => replyTo ! count Behaviors.same } @@ -58,15 +58,15 @@ object SupervisionCompileOnly { //#restart-stop-children def child(size: Long): Behavior[String] = - Behaviors.receiveMessage(msg ⇒ child(size + msg.length)) + Behaviors.receiveMessage(msg => child(size + msg.length)) def parent: Behavior[String] = { Behaviors.supervise[String] { - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => val child1 = ctx.spawn(child(0), "child1") val child2 = ctx.spawn(child(0), "child2") - Behaviors.receiveMessage[String] { msg ⇒ + Behaviors.receiveMessage[String] { msg => // there might be bugs here... val parts = msg.split(" ") child1 ! parts(0) @@ -80,13 +80,13 @@ object SupervisionCompileOnly { //#restart-keep-children def parent2: Behavior[String] = { - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => val child1 = ctx.spawn(child(0), "child1") val child2 = ctx.spawn(child(0), "child2") // supervision strategy inside the setup to not recreate children on restart Behaviors.supervise { - Behaviors.receiveMessage[String] { msg ⇒ + Behaviors.receiveMessage[String] { msg => // there might be bugs here... val parts = msg.split(" ") child1 ! parts(0) diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/ActorRef.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/ActorRef.scala index 280c9bcab3..f91c525e23 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/ActorRef.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/ActorRef.scala @@ -5,7 +5,7 @@ package akka.actor.typed import akka.annotation.DoNotInherit -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } import scala.annotation.unchecked.uncheckedVariance import akka.actor.typed.internal.InternalRecipientRef @@ -22,7 +22,7 @@ import akka.actor.typed.internal.InternalRecipientRef * Not for user extension */ @DoNotInherit -trait ActorRef[-T] extends RecipientRef[T] with java.lang.Comparable[ActorRef[_]] with java.io.Serializable { this: InternalRecipientRef[T] ⇒ +trait ActorRef[-T] extends RecipientRef[T] with java.lang.Comparable[ActorRef[_]] with java.io.Serializable { this: InternalRecipientRef[T] => /** * Send a message to the Actor referenced by this ActorRef using *at-most-once* * messaging semantics. @@ -96,11 +96,11 @@ private[akka] final case class SerializedActorRef[T] private (address: String) { @throws(classOf[java.io.ObjectStreamException]) def readResolve(): AnyRef = currentSystem.value match { - case null ⇒ + case null => throw new IllegalStateException( "Trying to deserialize a serialized typed ActorRef without an ActorSystem in scope." + " Use 'akka.serialization.Serialization.currentSystem.withValue(system) { ... }'") - case someSystem ⇒ + case someSystem => val resolver = ActorRefResolver(someSystem.toTyped) resolver.resolveActorRef(address) } @@ -111,7 +111,7 @@ private[akka] final case class SerializedActorRef[T] private (address: String) { * - not serializable * - not watchable */ -trait RecipientRef[-T] { this: InternalRecipientRef[T] ⇒ +trait RecipientRef[-T] { this: InternalRecipientRef[T] => /** * Send a message to the destination referenced by this `RecipientRef` using *at-most-once* * messaging semantics. diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/ActorRefResolver.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/ActorRefResolver.scala index 9920f08f9e..8c8ee66156 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/ActorRefResolver.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/ActorRefResolver.scala @@ -57,7 +57,7 @@ abstract class ActorRefResolver extends Extension { } object ActorRefResolverSetup { - def apply[T <: Extension](createExtension: ActorSystem[_] ⇒ ActorRefResolver): ActorRefResolverSetup = + def apply[T <: Extension](createExtension: ActorSystem[_] => ActorRefResolver): ActorRefResolverSetup = new ActorRefResolverSetup(new java.util.function.Function[ActorSystem[_], ActorRefResolver] { override def apply(sys: ActorSystem[_]): ActorRefResolver = createExtension(sys) }) // TODO can be simplified when compiled only with Scala >= 2.12 diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/ActorSystem.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/ActorSystem.scala index e23271c9d0..ab1788b827 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/ActorSystem.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/ActorSystem.scala @@ -4,7 +4,7 @@ package akka.actor.typed -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } import java.util.concurrent.CompletionStage import java.util.concurrent.ThreadFactory @@ -36,7 +36,7 @@ import com.typesafe.config.ConfigFactory */ @DoNotInherit @ApiMayChange -abstract class ActorSystem[-T] extends ActorRef[T] with Extensions { this: InternalRecipientRef[T] ⇒ +abstract class ActorSystem[-T] extends ActorRef[T] with Extensions { this: InternalRecipientRef[T] => /** * The name of this actor system, used to distinguish multiple ones within * the same JVM & class loader. @@ -231,7 +231,7 @@ object ActorSystem { val executionContext = bootstrapSettings.flatMap(_.defaultExecutionContext) val system = new untyped.ActorSystemImpl(name, appConfig, cl, executionContext, - Some(PropsAdapter(() ⇒ guardianBehavior, guardianProps, isGuardian = true)), setup) + Some(PropsAdapter(() => guardianBehavior, guardianProps, isGuardian = true)), setup) system.start() system.guardian ! GuardianActorAdapter.Start diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/Behavior.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/Behavior.scala index 69c6ec64fc..085dd5c7bd 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/Behavior.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/Behavior.scala @@ -12,7 +12,7 @@ import akka.actor.typed.internal.BehaviorImpl.OrElseBehavior import akka.actor.typed.internal.WrappingBehavior import akka.util.{ LineNumbers, OptionVal } import akka.annotation.{ ApiMayChange, DoNotInherit, InternalApi } -import akka.actor.typed.scaladsl.{ ActorContext ⇒ SAC } +import akka.actor.typed.scaladsl.{ ActorContext => SAC } /** * The behavior of an actor defines how it reacts to the messages that it @@ -36,7 +36,7 @@ import akka.actor.typed.scaladsl.{ ActorContext ⇒ SAC } */ @ApiMayChange @DoNotInherit -abstract class Behavior[T] { behavior ⇒ +abstract class Behavior[T] { behavior => /** * Narrow the type of this Behavior, which is always a safe operation. This * method is necessary to implement the contravariant nature of Behavior @@ -63,7 +63,7 @@ abstract class Behavior[T] { behavior ⇒ * * @param that the fallback `Behavior` */ - final def orElse(that: Behavior[T]): Behavior[T] = Behavior.DeferredBehavior[T] { ctx ⇒ + final def orElse(that: Behavior[T]): Behavior[T] = Behavior.DeferredBehavior[T] { ctx => new OrElseBehavior[T](Behavior.start(this, ctx), Behavior.start(that, ctx)) } } @@ -220,7 +220,7 @@ object Behavior { * INTERNAL API */ @InternalApi private[akka] val unhandledSignal: PartialFunction[(TypedActorContext[Nothing], Signal), Behavior[Nothing]] = { - case (_, _) ⇒ UnhandledBehavior + case (_, _) => UnhandledBehavior } /** @@ -234,7 +234,7 @@ object Behavior { /** INTERNAL API */ @InternalApi private[akka] object DeferredBehavior { - def apply[T](factory: SAC[T] ⇒ Behavior[T]): Behavior[T] = + def apply[T](factory: SAC[T] => Behavior[T]): Behavior[T] = new DeferredBehavior[T] { def apply(ctx: TypedActorContext[T]): Behavior[T] = factory(ctx.asScala) override def toString: String = s"Deferred(${LineNumbers(factory)})" @@ -267,16 +267,16 @@ object Behavior { @throws[IllegalArgumentException] private final def validatePostStop(postStop: OptionVal[Behavior[T]]): Unit = { postStop match { - case OptionVal.Some(b: DeferredBehavior[_]) ⇒ + case OptionVal.Some(b: DeferredBehavior[_]) => throw new IllegalArgumentException(s"Behavior used as `postStop` behavior in Stopped(...) was a deferred one [${b.toString}], which is not supported (it would never be evaluated).") - case _ ⇒ // all good + case _ => // all good } } override def toString = "Stopped" + { postStop match { - case OptionVal.Some(_) ⇒ "(postStop)" - case _ ⇒ "()" + case OptionVal.Some(_) => "(postStop)" + case _ => "()" } } } @@ -290,10 +290,10 @@ object Behavior { @tailrec def canonicalize[T](behavior: Behavior[T], current: Behavior[T], ctx: TypedActorContext[T]): Behavior[T] = behavior match { - case SameBehavior ⇒ current - case UnhandledBehavior ⇒ current - case deferred: DeferredBehavior[T] ⇒ canonicalize(deferred(ctx), deferred, ctx) - case other ⇒ other + case SameBehavior => current + case UnhandledBehavior => current + case deferred: DeferredBehavior[T] => canonicalize(deferred(ctx), deferred, ctx) + case other => other } /** @@ -305,13 +305,13 @@ object Behavior { */ @InternalApi @tailrec - private[akka] def wrap[T, U](currentBehavior: Behavior[_], nextBehavior: Behavior[T], ctx: TypedActorContext[T])(f: Behavior[T] ⇒ Behavior[U]): Behavior[U] = + private[akka] def wrap[T, U](currentBehavior: Behavior[_], nextBehavior: Behavior[T], ctx: TypedActorContext[T])(f: Behavior[T] => Behavior[U]): Behavior[U] = nextBehavior match { - case SameBehavior | `currentBehavior` ⇒ same - case UnhandledBehavior ⇒ unhandled - case stopped: StoppedBehavior[T] ⇒ stopped.unsafeCast[U] // won't receive more messages so cast is safe - case deferred: DeferredBehavior[T] ⇒ wrap(currentBehavior, start(deferred, ctx), ctx)(f) - case other ⇒ f(other) + case SameBehavior | `currentBehavior` => same + case UnhandledBehavior => unhandled + case stopped: StoppedBehavior[T] => stopped.unsafeCast[U] // won't receive more messages so cast is safe + case deferred: DeferredBehavior[T] => wrap(currentBehavior, start(deferred, ctx), ctx)(f) + case other => f(other) } /** @@ -321,13 +321,13 @@ object Behavior { def start[T](behavior: Behavior[T], ctx: TypedActorContext[T]): Behavior[T] = { // TODO can this be made @tailrec? behavior match { - case innerDeferred: DeferredBehavior[T] ⇒ start(innerDeferred(ctx), ctx) - case wrapped: WrappingBehavior[T, Any] @unchecked ⇒ + case innerDeferred: DeferredBehavior[T] => start(innerDeferred(ctx), ctx) + case wrapped: WrappingBehavior[T, Any] @unchecked => // make sure that a deferred behavior wrapped inside some other behavior is also started val startedInner = start(wrapped.nestedBehavior, ctx.asInstanceOf[TypedActorContext[Any]]) if (startedInner eq wrapped.nestedBehavior) wrapped else wrapped.replaceNested(startedInner) - case _ ⇒ behavior + case _ => behavior } } @@ -336,18 +336,18 @@ object Behavior { * satisfies it. The stack must not contain any unstarted deferred behavior or an `IllegalArgumentException` * will be thrown. */ - def existsInStack[T](behavior: Behavior[T])(p: Behavior[T] ⇒ Boolean): Boolean = { + def existsInStack[T](behavior: Behavior[T])(p: Behavior[T] => Boolean): Boolean = { @tailrec def loop(b: Behavior[T]): Boolean = b match { - case _ if p(b) ⇒ true - case wrappingBehavior: WrappingBehavior[T, T] @unchecked ⇒ + case _ if p(b) => true + case wrappingBehavior: WrappingBehavior[T, T] @unchecked => loop(wrappingBehavior.nestedBehavior) - case d: DeferredBehavior[T] ⇒ + case d: DeferredBehavior[T] => throw new IllegalArgumentException( "Cannot verify behavior existence when there are deferred in the behavior stack, " + s"Behavior.start the stack first. This is probably a bug, please create an issue. $d") - case _ ⇒ false + case _ => false } loop(behavior) @@ -360,18 +360,18 @@ object Behavior { */ def validateAsInitial[T](behavior: Behavior[T]): Behavior[T] = behavior match { - case SameBehavior | UnhandledBehavior ⇒ + case SameBehavior | UnhandledBehavior => throw new IllegalArgumentException(s"cannot use $behavior as initial behavior") - case x ⇒ x + case x => x } /** * Returns true if the given behavior is not stopped. */ def isAlive[T](behavior: Behavior[T]): Boolean = behavior match { - case _: StoppedBehavior[_] ⇒ false - case _: FailedBehavior ⇒ false - case _ ⇒ true + case _: StoppedBehavior[_] => false + case _: FailedBehavior => false + case _ => true } /** @@ -383,8 +383,8 @@ object Behavior { * Returns true if the given behavior is the special `Unhandled` marker. */ def isDeferred[T](behavior: Behavior[T]): Boolean = behavior match { - case _: DeferredBehavior[T] ⇒ true - case _ ⇒ false + case _: DeferredBehavior[T] => true + case _ => false } /** @@ -400,25 +400,25 @@ object Behavior { val result = interpret(behavior, ctx, signal) // we need to throw here to allow supervision of deathpact exception signal match { - case Terminated(ref) if result == UnhandledBehavior ⇒ throw DeathPactException(ref) - case _ ⇒ result + case Terminated(ref) if result == UnhandledBehavior => throw DeathPactException(ref) + case _ => result } } private def interpret[T](behavior: Behavior[T], ctx: TypedActorContext[T], msg: Any): Behavior[T] = { behavior match { - case null ⇒ throw new InvalidMessageException("[null] is not an allowed behavior") - case SameBehavior | UnhandledBehavior ⇒ + case null => throw new InvalidMessageException("[null] is not an allowed behavior") + case SameBehavior | UnhandledBehavior => throw new IllegalArgumentException(s"cannot execute with [$behavior] as behavior") - case d: DeferredBehavior[_] ⇒ throw new IllegalArgumentException(s"deferred [$d] should not be passed to interpreter") - case IgnoreBehavior ⇒ Behavior.same[T] - case s: StoppedBehavior[T] ⇒ s - case f: FailedBehavior ⇒ f - case EmptyBehavior ⇒ Behavior.unhandled[T] - case ext: ExtensibleBehavior[T] ⇒ + case d: DeferredBehavior[_] => throw new IllegalArgumentException(s"deferred [$d] should not be passed to interpreter") + case IgnoreBehavior => Behavior.same[T] + case s: StoppedBehavior[T] => s + case f: FailedBehavior => f + case EmptyBehavior => Behavior.unhandled[T] + case ext: ExtensibleBehavior[T] => val possiblyDeferredResult = msg match { - case signal: Signal ⇒ ext.receiveSignal(ctx, signal) - case m ⇒ ext.receive(ctx, m.asInstanceOf[T]) + case signal: Signal => ext.receiveSignal(ctx, signal) + case m => ext.receive(ctx, m.asInstanceOf[T]) } start(possiblyDeferredResult, ctx) } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/Extensions.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/Extensions.scala index 8b9827b717..bc60a00776 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/Extensions.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/Extensions.scala @@ -172,7 +172,7 @@ abstract class ExtensionSetup[T <: Extension]( * implementation of the extension. Intended for tests that need to replace * extension with stub/mock implementations. */ -abstract class AbstractExtensionSetup[T <: Extension](extId: ExtensionId[T], createExtension: ActorSystem[_] ⇒ T) +abstract class AbstractExtensionSetup[T <: Extension](extId: ExtensionId[T], createExtension: ActorSystem[_] => T) extends ExtensionSetup[T](extId, new java.util.function.Function[ActorSystem[_], T] { override def apply(sys: ActorSystem[_]): T = createExtension.apply(sys) }) // TODO can be simplified when compiled only with Scala >= 2.12 diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/Logger.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/Logger.scala index 8c846d2c20..3afb7cf4ad 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/Logger.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/Logger.scala @@ -202,11 +202,11 @@ abstract class Logger private[akka] () { * will not actually end up in any logger output. */ def isLevelEnabled(logLevel: LogLevel): Boolean = logLevel match { - case ErrorLevel ⇒ isErrorEnabled - case WarningLevel ⇒ isWarningEnabled - case InfoLevel ⇒ isInfoEnabled - case DebugLevel ⇒ isDebugEnabled - case _ ⇒ false + case ErrorLevel => isErrorEnabled + case WarningLevel => isWarningEnabled + case InfoLevel => isInfoEnabled + case DebugLevel => isDebugEnabled + case _ => false } /** @@ -215,11 +215,11 @@ abstract class Logger private[akka] () { * that will not actually end up in any logger output. */ def isLevelEnabled(logLevel: LogLevel, marker: LogMarker): Boolean = logLevel match { - case ErrorLevel ⇒ isErrorEnabled(marker) - case WarningLevel ⇒ isWarningEnabled(marker) - case InfoLevel ⇒ isInfoEnabled(marker) - case DebugLevel ⇒ isDebugEnabled(marker) - case _ ⇒ false + case ErrorLevel => isErrorEnabled(marker) + case WarningLevel => isWarningEnabled(marker) + case InfoLevel => isInfoEnabled(marker) + case DebugLevel => isDebugEnabled(marker) + case _ => false } // message only error logging diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/MessageAndSignals.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/MessageAndSignals.scala index b656d57d93..4023f54210 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/MessageAndSignals.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/MessageAndSignals.scala @@ -85,8 +85,8 @@ sealed class Terminated(val ref: ActorRef[Nothing]) extends Signal { override def hashCode(): Int = ref.hashCode() override def equals(obj: Any): Boolean = obj match { - case Terminated(`ref`) ⇒ true - case _ ⇒ false + case Terminated(`ref`) => true + case _ => false } } @@ -110,7 +110,7 @@ final class ChildFailed(ref: ActorRef[Nothing], val cause: Throwable) extends Te override def hashCode(): Int = ref.hashCode() override def equals(obj: Any): Boolean = obj match { - case ChildFailed(`ref`, `cause`) ⇒ true - case _ ⇒ false + case ChildFailed(`ref`, `cause`) => true + case _ => false } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/Props.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/Props.scala index 615e417c5e..e027cfdcd6 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/Props.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/Props.scala @@ -79,9 +79,9 @@ abstract class Props private[akka] () extends Product with Serializable { private[akka] def firstOrElse[T <: Props: ClassTag](default: T): T = { @tailrec def rec(d: Props): T = { d match { - case EmptyProps ⇒ default - case t: T ⇒ t - case _ ⇒ rec(d.next) + case EmptyProps => default + case t: T => t + case _ => rec(d.next) } } rec(this) @@ -98,9 +98,9 @@ abstract class Props private[akka] () extends Product with Serializable { private[akka] def allOf[T <: Props: ClassTag]: List[Props] = { @tailrec def select(d: Props, acc: List[Props]): List[Props] = d match { - case EmptyProps ⇒ acc.reverse - case _: T ⇒ select(d.next, (d withNext EmptyProps) :: acc) - case _ ⇒ select(d.next, acc) + case EmptyProps => acc.reverse + case _: T => select(d.next, (d withNext EmptyProps) :: acc) + case _ => select(d.next, acc) } select(this, Nil) } @@ -113,14 +113,14 @@ abstract class Props private[akka] () extends Product with Serializable { private[akka] def filterNot[T <: Props: ClassTag]: Props = { @tailrec def select(d: Props, acc: List[Props]): List[Props] = d match { - case EmptyProps ⇒ acc - case _: T ⇒ select(d.next, acc) - case _ ⇒ select(d.next, d :: acc) + case EmptyProps => acc + case _: T => select(d.next, acc) + case _ => select(d.next, d :: acc) } @tailrec def link(l: List[Props], acc: Props): Props = l match { - case d :: ds ⇒ link(ds, d withNext acc) - case Nil ⇒ acc + case d :: ds => link(ds, d withNext acc) + case Nil => acc } link(select(this, Nil), EmptyProps) } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/SpawnProtocol.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/SpawnProtocol.scala index ce19e5abc3..6e92190e98 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/SpawnProtocol.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/SpawnProtocol.scala @@ -14,14 +14,14 @@ object SpawnProtocol { /** * Special factory to make using Spawn with ask easier */ - def apply[T](behavior: Behavior[T], name: String, props: Props): ActorRef[ActorRef[T]] ⇒ Spawn[T] = - replyTo ⇒ new Spawn(behavior, name, props, replyTo) + def apply[T](behavior: Behavior[T], name: String, props: Props): ActorRef[ActorRef[T]] => Spawn[T] = + replyTo => new Spawn(behavior, name, props, replyTo) /** * Special factory to make using Spawn with ask easier. Props defaults to Props.empty */ - def apply[T](behavior: Behavior[T], name: String): ActorRef[ActorRef[T]] ⇒ Spawn[T] = - replyTo ⇒ new Spawn(behavior, name, Props.empty, replyTo) + def apply[T](behavior: Behavior[T], name: String): ActorRef[ActorRef[T]] => Spawn[T] = + replyTo => new Spawn(behavior, name, Props.empty, replyTo) } /** @@ -42,9 +42,9 @@ object SpawnProtocol { * Behavior implementing the [[SpawnProtocol]]. */ val behavior: Behavior[SpawnProtocol] = - Behaviors.receive { (ctx, msg) ⇒ + Behaviors.receive { (ctx, msg) => msg match { - case Spawn(bhvr, name, props, replyTo) ⇒ + case Spawn(bhvr, name, props, replyTo) => val ref = if (name == null || name.equals("")) ctx.spawnAnonymous(bhvr, props) @@ -53,8 +53,8 @@ object SpawnProtocol { @tailrec def spawnWithUniqueName(c: Int): ActorRef[Any] = { val nameSuggestion = if (c == 0) name else s"$name-$c" ctx.child(nameSuggestion) match { - case Some(_) ⇒ spawnWithUniqueName(c + 1) // already taken, try next - case None ⇒ ctx.spawn(bhvr, nameSuggestion, props) + case Some(_) => spawnWithUniqueName(c + 1) // already taken, try next + case None => ctx.spawn(bhvr, nameSuggestion, props) } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ActorContextImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ActorContextImpl.scala index c9ebcd22ba..42082aadcf 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ActorContextImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ActorContextImpl.scala @@ -6,7 +6,7 @@ package akka.actor.typed package internal import java.time.Duration -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import java.util.ArrayList import java.util.Optional import java.util.concurrent.CompletionStage @@ -27,13 +27,13 @@ import akka.util.JavaDurationConverters._ @InternalApi private[akka] trait ActorContextImpl[T] extends TypedActorContext[T] with javadsl.ActorContext[T] with scaladsl.ActorContext[T] { private var messageAdapterRef: OptionVal[ActorRef[Any]] = OptionVal.None - private var _messageAdapters: List[(Class[_], Any ⇒ T)] = Nil + private var _messageAdapters: List[(Class[_], Any => T)] = Nil private var _timer: OptionVal[TimerSchedulerImpl[T]] = OptionVal.None // context-shared timer needed to allow for nested timer usage def timer: TimerSchedulerImpl[T] = _timer match { - case OptionVal.Some(timer) ⇒ timer - case OptionVal.None ⇒ + case OptionVal.Some(timer) => timer + case OptionVal.None => val timer = new TimerSchedulerImpl[T](this) _timer = OptionVal.Some(timer) timer @@ -45,8 +45,8 @@ import akka.util.JavaDurationConverters._ override def getChild(name: String): Optional[ActorRef[Void]] = child(name) match { - case Some(c) ⇒ Optional.of(c.unsafeUpcast[Void]) - case None ⇒ Optional.empty() + case Some(c) => Optional.of(c.unsafeUpcast[Void]) + case None => Optional.empty() } override def getChildren: java.util.List[ActorRef[Void]] = { @@ -81,7 +81,7 @@ import akka.util.JavaDurationConverters._ spawnAnonymous(behavior, Props.empty) // Scala API impl - override def ask[Req, Res](target: RecipientRef[Req])(createRequest: ActorRef[Res] ⇒ Req)(mapResponse: Try[Res] ⇒ T)(implicit responseTimeout: Timeout, classTag: ClassTag[Res]): Unit = { + override def ask[Req, Res](target: RecipientRef[Req])(createRequest: ActorRef[Res] => Req)(mapResponse: Try[Res] => T)(implicit responseTimeout: Timeout, classTag: ClassTag[Res]): Unit = { import akka.actor.typed.scaladsl.AskPattern._ pipeToSelf((target.ask(createRequest))(responseTimeout, system.scheduler))(mapResponse) } @@ -96,8 +96,8 @@ import akka.util.JavaDurationConverters._ } // Scala API impl - def pipeToSelf[Value](future: Future[Value])(mapResult: Try[Value] ⇒ T): Unit = { - future.onComplete(value ⇒ self.unsafeUpcast ! AdaptMessage(value, mapResult)) + def pipeToSelf[Value](future: Future[Value])(mapResult: Try[Value] => T): Unit = { + future.onComplete(value => self.unsafeUpcast ! AdaptMessage(value, mapResult)) } // Java API impl @@ -110,19 +110,19 @@ import akka.util.JavaDurationConverters._ }) } - private[akka] override def spawnMessageAdapter[U](f: U ⇒ T, name: String): ActorRef[U] = + private[akka] override def spawnMessageAdapter[U](f: U => T, name: String): ActorRef[U] = internalSpawnMessageAdapter(f, name) - private[akka] override def spawnMessageAdapter[U](f: U ⇒ T): ActorRef[U] = + private[akka] override def spawnMessageAdapter[U](f: U => T): ActorRef[U] = internalSpawnMessageAdapter(f, name = "") /** * INTERNAL API: Needed to make Scala 2.12 compiler happy if spawnMessageAdapter is overloaded for scaladsl/javadsl. * Otherwise "ambiguous reference to overloaded definition" because Function is lambda. */ - @InternalApi private[akka] def internalSpawnMessageAdapter[U](f: U ⇒ T, name: String): ActorRef[U] + @InternalApi private[akka] def internalSpawnMessageAdapter[U](f: U => T, name: String): ActorRef[U] - override def messageAdapter[U: ClassTag](f: U ⇒ T): ActorRef[U] = { + override def messageAdapter[U: ClassTag](f: U => T): ActorRef[U] = { val messageClass = implicitly[ClassTag[U]].runtimeClass.asInstanceOf[Class[U]] internalMessageAdapter(messageClass, f) } @@ -130,16 +130,16 @@ import akka.util.JavaDurationConverters._ override def messageAdapter[U](messageClass: Class[U], f: JFunction[U, T]): ActorRef[U] = internalMessageAdapter(messageClass, f.apply) - private def internalMessageAdapter[U](messageClass: Class[U], f: U ⇒ T): ActorRef[U] = { + private def internalMessageAdapter[U](messageClass: Class[U], f: U => T): ActorRef[U] = { // replace existing adapter for same class, only one per class is supported to avoid unbounded growth // in case "same" adapter is added repeatedly - _messageAdapters = (messageClass, f.asInstanceOf[Any ⇒ T]) :: - _messageAdapters.filterNot { case (cls, _) ⇒ cls == messageClass } + _messageAdapters = (messageClass, f.asInstanceOf[Any => T]) :: + _messageAdapters.filterNot { case (cls, _) => cls == messageClass } val ref = messageAdapterRef match { - case OptionVal.Some(ref) ⇒ ref.asInstanceOf[ActorRef[U]] - case OptionVal.None ⇒ + case OptionVal.Some(ref) => ref.asInstanceOf[ActorRef[U]] + case OptionVal.None => // AdaptMessage is not really a T, but that is erased - val ref = internalSpawnMessageAdapter[Any](msg ⇒ AdaptWithRegisteredMessageAdapter(msg).asInstanceOf[T], "adapter") + val ref = internalSpawnMessageAdapter[Any](msg => AdaptWithRegisteredMessageAdapter(msg).asInstanceOf[T], "adapter") messageAdapterRef = OptionVal.Some(ref) ref } @@ -149,6 +149,6 @@ import akka.util.JavaDurationConverters._ /** * INTERNAL API */ - @InternalApi private[akka] def messageAdapters: List[(Class[_], Any ⇒ T)] = _messageAdapters + @InternalApi private[akka] def messageAdapters: List[(Class[_], Any => T)] = _messageAdapters } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ActorRefImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ActorRefImpl.scala index 62304d846d..3702869441 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ActorRefImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ActorRefImpl.scala @@ -13,7 +13,7 @@ import scala.annotation.unchecked.uncheckedVariance * available in the package object, enabling `ref.toImpl` (or `ref.toImplN` * for `ActorRef[Nothing]`—Scala refuses to infer `Nothing` as a type parameter). */ -private[akka] trait ActorRefImpl[-T] extends ActorRef[T] { this: InternalRecipientRef[T] ⇒ +private[akka] trait ActorRefImpl[-T] extends ActorRef[T] { this: InternalRecipientRef[T] => def sendSystem(signal: SystemMessage): Unit def isLocal: Boolean @@ -36,8 +36,8 @@ private[akka] trait ActorRefImpl[-T] extends ActorRef[T] { this: InternalRecipie * Equals takes path and the unique id of the actor cell into account. */ final override def equals(that: Any): Boolean = that match { - case other: ActorRef[_] ⇒ path.uid == other.path.uid && path == other.path - case _ ⇒ false + case other: ActorRef[_] => path.uid == other.path.uid && path == other.path + case _ => false } override def toString: String = s"Actor[${path}#${path.uid}]" diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/BehaviorImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/BehaviorImpl.scala index ded0fe5ef6..70434d82ea 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/BehaviorImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/BehaviorImpl.scala @@ -7,8 +7,8 @@ package internal import akka.util.{ LineNumbers } import akka.annotation.InternalApi -import akka.actor.typed.{ TypedActorContext ⇒ AC } -import akka.actor.typed.scaladsl.{ ActorContext ⇒ SAC } +import akka.actor.typed.{ TypedActorContext => AC } +import akka.actor.typed.scaladsl.{ ActorContext => SAC } /** * INTERNAL API @@ -24,7 +24,7 @@ import akka.actor.typed.scaladsl.{ ActorContext ⇒ SAC } intercept(WidenedInterceptor(matcher))(behavior) class ReceiveBehavior[T]( - val onMessage: (SAC[T], T) ⇒ Behavior[T], + val onMessage: (SAC[T], T) => Behavior[T], onSignal: PartialFunction[(SAC[T], Signal), Behavior[T]] = Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]]) extends ExtensibleBehavior[T] { @@ -42,7 +42,7 @@ import akka.actor.typed.scaladsl.{ ActorContext ⇒ SAC } * another function which drops the context parameter. */ class ReceiveMessageBehavior[T]( - val onMessage: T ⇒ Behavior[T], + val onMessage: T => Behavior[T], onSignal: PartialFunction[(SAC[T], Signal), Behavior[T]] = Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]]) extends ExtensibleBehavior[T] { @@ -68,15 +68,15 @@ import akka.actor.typed.scaladsl.{ ActorContext ⇒ SAC } override def receive(ctx: AC[T], msg: T): Behavior[T] = { Behavior.interpretMessage(first, ctx, msg) match { - case _: UnhandledBehavior.type ⇒ Behavior.interpretMessage(second, ctx, msg) - case handled ⇒ handled + case _: UnhandledBehavior.type => Behavior.interpretMessage(second, ctx, msg) + case handled => handled } } override def receiveSignal(ctx: AC[T], msg: Signal): Behavior[T] = { Behavior.interpretSignal(first, ctx, msg) match { - case _: UnhandledBehavior.type ⇒ Behavior.interpretSignal(second, ctx, msg) - case handled ⇒ handled + case _: UnhandledBehavior.type => Behavior.interpretSignal(second, ctx, msg) + case handled => handled } } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ExtensionsImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ExtensionsImpl.scala index 6c902a89d7..7783cd885b 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ExtensionsImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/ExtensionsImpl.scala @@ -20,7 +20,7 @@ import akka.actor.typed.ExtensionSetup * INTERNAL API */ @InternalApi -trait ExtensionsImpl extends Extensions { self: ActorSystem[_] ⇒ +trait ExtensionsImpl extends Extensions { self: ActorSystem[_] => private val extensions = new ConcurrentHashMap[ExtensionId[_], AnyRef] @@ -36,17 +36,17 @@ trait ExtensionsImpl extends Extensions { self: ActorSystem[_] ⇒ */ def loadExtensions(key: String, throwOnLoadFail: Boolean): Unit = { - settings.config.getStringList(key).asScala.foreach { extensionIdFQCN ⇒ + settings.config.getStringList(key).asScala.foreach { extensionIdFQCN => // it is either a Scala object or it is a Java class with a static singleton accessor val idTry = dynamicAccess.getObjectFor[AnyRef](extensionIdFQCN) - .recoverWith { case _ ⇒ idFromJavaSingletonAccessor(extensionIdFQCN) } + .recoverWith { case _ => idFromJavaSingletonAccessor(extensionIdFQCN) } idTry match { - case Success(id: ExtensionId[_]) ⇒ registerExtension(id) - case Success(_) ⇒ + case Success(id: ExtensionId[_]) => registerExtension(id) + case Success(_) => if (!throwOnLoadFail) log.error("[{}] is not an 'ExtensionId', skipping...", extensionIdFQCN) else throw new RuntimeException(s"[$extensionIdFQCN] is not an 'ExtensionId'") - case Failure(problem) ⇒ + case Failure(problem) => if (!throwOnLoadFail) log.error(problem, "While trying to load extension [{}], skipping...", extensionIdFQCN) else throw new RuntimeException(s"While trying to load extension [$extensionIdFQCN]", problem) } @@ -54,7 +54,7 @@ trait ExtensionsImpl extends Extensions { self: ActorSystem[_] ⇒ } def idFromJavaSingletonAccessor(extensionIdFQCN: String): Try[ExtensionId[Extension]] = - dynamicAccess.getClassFor[ExtensionId[Extension]](extensionIdFQCN).flatMap[ExtensionId[Extension]] { clazz: Class[_] ⇒ + dynamicAccess.getClassFor[ExtensionId[Extension]](extensionIdFQCN).flatMap[ExtensionId[Extension]] { clazz: Class[_] => Try { val singletonAccessor = clazz.getDeclaredMethod("getInstance") @@ -69,33 +69,33 @@ trait ExtensionsImpl extends Extensions { self: ActorSystem[_] ⇒ final override def hasExtension(ext: ExtensionId[_ <: Extension]): Boolean = findExtension(ext) != null final override def extension[T <: Extension](ext: ExtensionId[T]): T = findExtension(ext) match { - case null ⇒ throw new IllegalArgumentException(s"Trying to get non-registered extension [$ext]") - case some ⇒ some.asInstanceOf[T] + case null => throw new IllegalArgumentException(s"Trying to get non-registered extension [$ext]") + case some => some.asInstanceOf[T] } final override def registerExtension[T <: Extension](ext: ExtensionId[T]): T = findExtension(ext) match { - case null ⇒ createExtensionInstance(ext) - case existing ⇒ existing.asInstanceOf[T] + case null => createExtensionInstance(ext) + case existing => existing.asInstanceOf[T] } private def createExtensionInstance[T <: Extension](ext: ExtensionId[T]): T = { val inProcessOfRegistration = new CountDownLatch(1) extensions.putIfAbsent(ext, inProcessOfRegistration) match { // Signal that registration is in process - case null ⇒ try { // Signal was successfully sent + case null => try { // Signal was successfully sent // Create and initialize the extension, first look for ExtensionSetup val instance = self.settings.setup.setups.collectFirst { - case (_, extSetup: ExtensionSetup[_]) if extSetup.extId == ext ⇒ extSetup.createExtension(self) + case (_, extSetup: ExtensionSetup[_]) if extSetup.extId == ext => extSetup.createExtension(self) }.getOrElse(ext.createExtension(self)) instance match { - case null ⇒ throw new IllegalStateException(s"Extension instance created as 'null' for extension [$ext]") - case instance: T @unchecked ⇒ + case null => throw new IllegalStateException(s"Extension instance created as 'null' for extension [$ext]") + case instance: T @unchecked => // Replace our in process signal with the initialized extension extensions.replace(ext, inProcessOfRegistration, instance) instance } } catch { - case t: Throwable ⇒ + case t: Throwable => //In case shit hits the fan, remove the inProcess signal and escalate to caller extensions.replace(ext, inProcessOfRegistration, t) throw t @@ -103,7 +103,7 @@ trait ExtensionsImpl extends Extensions { self: ActorSystem[_] ⇒ //Always notify listeners of the inProcess signal inProcessOfRegistration.countDown() } - case _ ⇒ + case _ => //Someone else is in process of registering an extension for this Extension, retry registerExtension(ext) } @@ -114,11 +114,11 @@ trait ExtensionsImpl extends Extensions { self: ActorSystem[_] ⇒ */ @tailrec private def findExtension[T <: Extension](ext: ExtensionId[T]): T = extensions.get(ext) match { - case c: CountDownLatch ⇒ + case c: CountDownLatch => //Registration in process, await completion and retry c.await() findExtension(ext) - case t: Throwable ⇒ throw t //Initialization failed, throw same again - case other ⇒ other.asInstanceOf[T] //could be a T or null, in which case we return the null as T + case t: Throwable => throw t //Initialization failed, throw same again + case other => other.asInstanceOf[T] //could be a T or null, in which case we return the null as T } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/InterceptorImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/InterceptorImpl.scala index f962064477..aade13f494 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/InterceptorImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/InterceptorImpl.scala @@ -20,7 +20,7 @@ import akka.util.LineNumbers private[akka] object InterceptorImpl { def apply[O, I](interceptor: BehaviorInterceptor[O, I], nestedBehavior: Behavior[I]): Behavior[O] = { - Behavior.DeferredBehavior[O] { ctx ⇒ + Behavior.DeferredBehavior[O] { ctx => val interceptorBehavior = new InterceptorImpl[O, I](interceptor, nestedBehavior) interceptorBehavior.preStart(ctx) } @@ -88,8 +88,8 @@ private[akka] final class InterceptorImpl[O, I](val interceptor: BehaviorInterce } else { // returned behavior could be nested in setups, so we need to start before we deduplicate val duplicateInterceptExists = Behavior.existsInStack(started) { - case i: InterceptorImpl[O, I] if interceptor.isSame(i.interceptor.asInstanceOf[BehaviorInterceptor[Any, Any]]) ⇒ true - case _ ⇒ false + case i: InterceptorImpl[O, I] if interceptor.isSame(i.interceptor.asInstanceOf[BehaviorInterceptor[Any, Any]]) => true + case _ => false } if (duplicateInterceptExists) started.unsafeCast[O] @@ -120,8 +120,8 @@ private[akka] final case class MonitorInterceptor[T](actorRef: ActorRef[T]) exte // only once to the same actor in the same behavior stack override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = other match { - case MonitorInterceptor(`actorRef`) ⇒ true - case _ ⇒ false + case MonitorInterceptor(`actorRef`) => true + case _ => false } } @@ -150,8 +150,8 @@ private[akka] final case class LogMessagesInterceptor[T](opts: LogOptions) exten // only once in the same behavior stack override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = other match { - case LogMessagesInterceptor(`opts`) ⇒ true - case _ ⇒ false + case LogMessagesInterceptor(`opts`) => true + case _ => false } } @@ -161,8 +161,8 @@ private[akka] final case class LogMessagesInterceptor[T](opts: LogOptions) exten @InternalApi private[akka] object WidenedInterceptor { - private final val _any2null = (_: Any) ⇒ null - private final def any2null[T] = _any2null.asInstanceOf[Any ⇒ T] + private final val _any2null = (_: Any) => null + private final def any2null[T] = _any2null.asInstanceOf[Any => T] } /** @@ -176,25 +176,25 @@ private[akka] final case class WidenedInterceptor[O, I](matcher: PartialFunction override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = other match { // If they use the same pf instance we can allow it, to have one way to workaround defining // "recursive" narrowed behaviors. - case WidenedInterceptor(`matcher`) ⇒ true - case WidenedInterceptor(otherMatcher) ⇒ + case WidenedInterceptor(`matcher`) => true + case WidenedInterceptor(otherMatcher) => // there is no safe way to allow this throw new IllegalStateException("Widen can only be used one time in the same behavior stack. " + s"One defined in ${LineNumbers(matcher)}, and another in ${LineNumbers(otherMatcher)}") - case _ ⇒ false + case _ => false } def aroundReceive(ctx: TypedActorContext[O], msg: O, target: ReceiveTarget[I]): Behavior[I] = { // widen would wrap the TimerMessage, which would be wrong, see issue #25318 msg match { - case t: TimerMsg ⇒ throw new IllegalArgumentException( + case t: TimerMsg => throw new IllegalArgumentException( s"Timers and widen can't be used together, [${t.key}]. See issue #25318") - case _ ⇒ () + case _ => () } matcher.applyOrElse(msg, any2null) match { - case null ⇒ Behavior.unhandled - case transformed ⇒ target(ctx, transformed) + case null => Behavior.unhandled + case transformed => target(ctx, transformed) } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/InternalMessage.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/InternalMessage.scala index 3ddbbf3352..d76987d67c 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/InternalMessage.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/InternalMessage.scala @@ -22,6 +22,6 @@ import akka.annotation.InternalApi * function. Used by `ActorContext.spawnMessageAdapter` and `ActorContext.ask` so that the function is * applied in the "parent" actor (for better thread safety).. */ -@InternalApi private[akka] final case class AdaptMessage[U, T](msg: U, adapter: U ⇒ T) extends InternalMessage { +@InternalApi private[akka] final case class AdaptMessage[U, T](msg: U, adapter: U => T) extends InternalMessage { def adapt(): T = adapter(msg) } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/LoggerClass.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/LoggerClass.scala index 78905252e4..e350768e56 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/LoggerClass.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/LoggerClass.scala @@ -39,7 +39,7 @@ private[akka] object LoggerClass { suitableClass.getOrElse(default) } catch { - case NonFatal(_) ⇒ default + case NonFatal(_) => default } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/MiscMessageSerializer.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/MiscMessageSerializer.scala index bef3b16bf2..0fdef18ab5 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/MiscMessageSerializer.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/MiscMessageSerializer.scala @@ -20,20 +20,20 @@ class MiscMessageSerializer(val system: akka.actor.ExtendedActorSystem) extends private val ActorRefManifest = "a" def manifest(o: AnyRef): String = o match { - case _: ActorRef[_] ⇒ ActorRefManifest - case _ ⇒ + case _: ActorRef[_] => ActorRefManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass} in [${getClass.getName}]") } def toBinary(o: AnyRef): Array[Byte] = o match { - case ref: ActorRef[_] ⇒ resolver.toSerializationFormat(ref).getBytes(StandardCharsets.UTF_8) - case _ ⇒ + case ref: ActorRef[_] => resolver.toSerializationFormat(ref).getBytes(StandardCharsets.UTF_8) + case _ => throw new IllegalArgumentException(s"Cannot serialize object of type [${o.getClass.getName}]") } def fromBinary(bytes: Array[Byte], manifest: String): ActorRef[Any] = manifest match { - case ActorRefManifest ⇒ resolver.resolveActorRef(new String(bytes, StandardCharsets.UTF_8)) - case _ ⇒ + case ActorRefManifest => resolver.resolveActorRef(new String(bytes, StandardCharsets.UTF_8)) + case _ => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/PoisonPill.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/PoisonPill.scala index bdda7277ed..5c42453407 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/PoisonPill.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/PoisonPill.scala @@ -36,11 +36,11 @@ import akka.annotation.InternalApi override def aroundSignal(ctx: TypedActorContext[M], signal: Signal, target: BehaviorInterceptor.SignalTarget[M]): Behavior[M] = { signal match { - case p: PoisonPill ⇒ + case p: PoisonPill => val next = target(ctx, p) if (Behavior.isUnhandled(next)) Behavior.stopped else next - case _ ⇒ target(ctx, signal) + case _ => target(ctx, signal) } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/StashBufferImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/StashBufferImpl.scala index 82d63e07c0..e5704734e5 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/StashBufferImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/StashBufferImpl.scala @@ -5,7 +5,7 @@ package akka.actor.typed.internal import java.util.function.Consumer -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import scala.annotation.tailrec import scala.util.control.NonFatal @@ -23,7 +23,7 @@ import akka.util.ConstantFun */ @InternalApi private[akka] object StashBufferImpl { private final class Node[T](var next: Node[T], val message: T) { - def apply(f: T ⇒ Unit): Unit = f(message) + def apply(f: T => Unit): Unit = f(message) } def apply[T](capacity: Int): StashBufferImpl[T] = @@ -83,7 +83,7 @@ import akka.util.ConstantFun if (nonEmpty) _first.message else throw new NoSuchElementException("head of empty buffer") - override def foreach(f: T ⇒ Unit): Unit = { + override def foreach(f: T => Unit): Unit = { var node = _first while (node ne null) { node(f) @@ -100,7 +100,7 @@ import akka.util.ConstantFun unstashAll(ctx.asScala, behavior) override def unstash(ctx: scaladsl.ActorContext[T], behavior: Behavior[T], - numberOfMessages: Int, wrap: T ⇒ T): Behavior[T] = { + numberOfMessages: Int, wrap: T => T): Behavior[T] = { if (isEmpty) behavior // optimization else { @@ -119,11 +119,11 @@ import akka.util.ConstantFun else { val nextB = try { messages.next() match { - case sig: Signal ⇒ Behavior.interpretSignal(b2, ctx, sig) - case msg ⇒ Behavior.interpretMessage(b2, ctx, msg) + case sig: Signal => Behavior.interpretSignal(b2, ctx, sig) + case msg => Behavior.interpretMessage(b2, ctx, msg) } } catch { - case NonFatal(e) ⇒ throw UnstashException(e, b2) + case NonFatal(e) => throw UnstashException(e, b2) } interpretOne(Behavior.canonicalize(nextB, b2, ctx)) // recursive @@ -135,7 +135,7 @@ import akka.util.ConstantFun override def unstash(ctx: javadsl.ActorContext[T], behavior: Behavior[T], numberOfMessages: Int, wrap: JFunction[T, T]): Behavior[T] = - unstash(ctx.asScala, behavior, numberOfMessages, x ⇒ wrap.apply(x)) + unstash(ctx.asScala, behavior, numberOfMessages, x => wrap.apply(x)) override def toString: String = s"StashBuffer($size/$capacity)" @@ -146,8 +146,8 @@ import akka.util.ConstantFun */ @InternalApi private[akka] object UnstashException { def unwrap(t: Throwable): Throwable = t match { - case UnstashException(e, _) ⇒ e - case _ ⇒ t + case UnstashException(e, _) => e + case _ => t } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/Supervision.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/Supervision.scala index acf9a2a735..08d2914a56 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/Supervision.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/Supervision.scala @@ -31,11 +31,11 @@ import akka.util.unused @InternalApi private[akka] object Supervisor { def apply[T, Thr <: Throwable: ClassTag](initialBehavior: Behavior[T], strategy: SupervisorStrategy): Behavior[T] = { strategy match { - case r: RestartOrBackoff ⇒ + case r: RestartOrBackoff => Behaviors.intercept[T, T](new RestartSupervisor(initialBehavior, r))(initialBehavior) - case r: Resume ⇒ + case r: Resume => Behaviors.intercept[T, T](new ResumeSupervisor(r))(initialBehavior) - case r: Stop ⇒ + case r: Stop => Behaviors.intercept[T, T](new StopSupervisor(initialBehavior, r))(initialBehavior) } } @@ -54,8 +54,8 @@ private abstract class AbstractSupervisor[O, I, Thr <: Throwable](strategy: Supe override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = { other match { - case as: AbstractSupervisor[_, _, Thr] if throwableClass == as.throwableClass ⇒ true - case _ ⇒ false + case as: AbstractSupervisor[_, _, Thr] if throwableClass == as.throwableClass => true + case _ => false } } @@ -102,7 +102,7 @@ private abstract class SimpleSupervisor[T, Thr <: Throwable: ClassTag](ss: Super } protected def handleException(@unused ctx: TypedActorContext[T]): Catcher[Behavior[T]] = { - case NonFatal(t) if isInstanceOfTheThrowableClass(t) ⇒ + case NonFatal(t) if isInstanceOfTheThrowableClass(t) => Behavior.failed(t) } @@ -119,7 +119,7 @@ private class StopSupervisor[T, Thr <: Throwable: ClassTag](@unused initial: Beh extends SimpleSupervisor[T, Thr](strategy) { override def handleException(ctx: TypedActorContext[T]): Catcher[Behavior[T]] = { - case NonFatal(t) if isInstanceOfTheThrowableClass(t) ⇒ + case NonFatal(t) if isInstanceOfTheThrowableClass(t) => log(ctx, t) Behavior.failed(t) } @@ -127,11 +127,11 @@ private class StopSupervisor[T, Thr <: Throwable: ClassTag](@unused initial: Beh private class ResumeSupervisor[T, Thr <: Throwable: ClassTag](ss: Resume) extends SimpleSupervisor[T, Thr](ss) { override protected def handleException(ctx: TypedActorContext[T]): Catcher[Behavior[T]] = { - case NonFatal(t) if isInstanceOfTheThrowableClass(t) ⇒ + case NonFatal(t) if isInstanceOfTheThrowableClass(t) => log(ctx, t) t match { - case e: UnstashException[T] @unchecked ⇒ e.behavior - case _ ⇒ Behaviors.same + case e: UnstashException[T] @unchecked => e.behavior + case _ => Behaviors.same } } } @@ -150,8 +150,8 @@ private object RestartSupervisor { maxBackoff else maxBackoff.min(minBackoff * math.pow(2, restartCount)) * rnd match { - case f: FiniteDuration ⇒ f - case _ ⇒ maxBackoff + case f: FiniteDuration => f + case _ => maxBackoff } } @@ -169,17 +169,17 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav private var deadline: OptionVal[Deadline] = OptionVal.None private def deadlineHasTimeLeft: Boolean = deadline match { - case OptionVal.None ⇒ true - case OptionVal.Some(d) ⇒ d.hasTimeLeft + case OptionVal.None => true + case OptionVal.Some(d) => d.hasTimeLeft } override def aroundSignal(ctx: TypedActorContext[O], signal: Signal, target: SignalTarget[T]): Behavior[T] = { restartingInProgress match { - case OptionVal.None ⇒ + case OptionVal.None => super.aroundSignal(ctx, signal, target) - case OptionVal.Some((stashBuffer, children)) ⇒ + case OptionVal.Some((stashBuffer, children)) => signal match { - case Terminated(ref) if strategy.stopChildren && children(ref) ⇒ + case Terminated(ref) if strategy.stopChildren && children(ref) => val remainingChildren = children - ref if (remainingChildren.isEmpty && gotScheduledRestart) { restartCompleted(ctx) @@ -188,7 +188,7 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav Behaviors.same } - case _ ⇒ + case _ => if (stashBuffer.isFull) dropped(ctx, signal) else @@ -200,10 +200,10 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav override def aroundReceive(ctx: TypedActorContext[O], msg: O, target: ReceiveTarget[T]): Behavior[T] = { msg.asInstanceOf[Any] match { - case ScheduledRestart(owner) ⇒ + case ScheduledRestart(owner) => if (owner eq this) { restartingInProgress match { - case OptionVal.Some((_, children)) ⇒ + case OptionVal.Some((_, children)) => if (strategy.stopChildren && children.nonEmpty) { // still waiting for children to stop gotScheduledRestart = true @@ -211,7 +211,7 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav } else restartCompleted(ctx) - case OptionVal.None ⇒ + case OptionVal.None => throw new IllegalStateException("Unexpected ScheduledRestart when restart not in progress") } } else { @@ -219,7 +219,7 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav target(ctx, msg.asInstanceOf[T]) } - case ResetRestartCount(current, owner) ⇒ + case ResetRestartCount(current, owner) => if (owner eq this) { if (current == restartCount) { restartCount = 0 @@ -230,13 +230,13 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav target(ctx, msg.asInstanceOf[T]) } - case m: T @unchecked ⇒ + case m: T @unchecked => restartingInProgress match { - case OptionVal.None ⇒ + case OptionVal.None => try { target(ctx, m) } catch handleReceiveException(ctx, target) - case OptionVal.Some((stashBuffer, _)) ⇒ + case OptionVal.Some((stashBuffer, _)) => if (stashBuffer.isFull) dropped(ctx, m) else @@ -247,9 +247,9 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav } override protected def handleExceptionOnStart(ctx: TypedActorContext[O], @unused target: PreStartTarget[T]): Catcher[Behavior[T]] = { - case NonFatal(t) if isInstanceOfTheThrowableClass(t) ⇒ + case NonFatal(t) if isInstanceOfTheThrowableClass(t) => strategy match { - case _: Restart ⇒ + case _: Restart => // if unlimited restarts then don't restart if starting fails as it would likely be an infinite restart loop if (strategy.unlimitedRestarts() || ((restartCount + 1) >= strategy.maxRestarts && deadlineHasTimeLeft)) { // don't log here as it'll be logged as ActorInitializationException @@ -257,37 +257,37 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav } else { prepareRestart(ctx, t) } - case _: Backoff ⇒ + case _: Backoff => prepareRestart(ctx, t) } } override protected def handleSignalException(ctx: TypedActorContext[O], target: SignalTarget[T]): Catcher[Behavior[T]] = { handleException(ctx, signalRestart = { - case e: UnstashException[O] @unchecked ⇒ Behavior.interpretSignal(e.behavior, ctx, PreRestart) - case _ ⇒ target(ctx, PreRestart) + case e: UnstashException[O] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart) + case _ => target(ctx, PreRestart) }) } override protected def handleReceiveException(ctx: TypedActorContext[O], target: ReceiveTarget[T]): Catcher[Behavior[T]] = { handleException(ctx, signalRestart = { - case e: UnstashException[O] @unchecked ⇒ Behavior.interpretSignal(e.behavior, ctx, PreRestart) - case _ ⇒ target.signalRestart(ctx) + case e: UnstashException[O] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart) + case _ => target.signalRestart(ctx) }) } - private def handleException(ctx: TypedActorContext[O], signalRestart: Throwable ⇒ Unit): Catcher[Behavior[T]] = { - case NonFatal(t) if isInstanceOfTheThrowableClass(t) ⇒ + private def handleException(ctx: TypedActorContext[O], signalRestart: Throwable => Unit): Catcher[Behavior[T]] = { + case NonFatal(t) if isInstanceOfTheThrowableClass(t) => if (strategy.maxRestarts != -1 && restartCount >= strategy.maxRestarts && deadlineHasTimeLeft) { strategy match { - case _: Restart ⇒ throw t - case _: Backoff ⇒ + case _: Restart => throw t + case _: Backoff => log(ctx, t) Behavior.failed(t) } } else { try signalRestart(t) catch { - case NonFatal(ex) ⇒ ctx.asScala.log.error(ex, "failure during PreRestart") + case NonFatal(ex) => ctx.asScala.log.error(ex, "failure during PreRestart") } prepareRestart(ctx, t) @@ -309,12 +309,12 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav restartingInProgress = OptionVal.Some((StashBuffer[Any](stashCapacity), childrenToStop)) strategy match { - case backoff: Backoff ⇒ + case backoff: Backoff => val restartDelay = calculateDelay(currentRestartCount, backoff.minBackoff, backoff.maxBackoff, backoff.randomFactor) gotScheduledRestart = false ctx.asScala.scheduleOnce(restartDelay, ctx.asScala.self.unsafeUpcast[Any], ScheduledRestart(this)) Behaviors.empty - case _: Restart ⇒ + case _: Restart => if (childrenToStop.isEmpty) restartCompleted(ctx) else @@ -324,30 +324,30 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav private def restartCompleted(ctx: TypedActorContext[O]): Behavior[T] = { strategy match { - case backoff: Backoff ⇒ + case backoff: Backoff => gotScheduledRestart = false ctx.asScala.scheduleOnce(backoff.resetBackoffAfter, ctx.asScala.self.unsafeUpcast[Any], ResetRestartCount(restartCount, this)) - case _: Restart ⇒ + case _: Restart => } try { val newBehavior = Behavior.validateAsInitial(Behavior.start(initial, ctx.asInstanceOf[TypedActorContext[T]])) val nextBehavior = restartingInProgress match { - case OptionVal.None ⇒ newBehavior - case OptionVal.Some((stashBuffer, _)) ⇒ + case OptionVal.None => newBehavior + case OptionVal.Some((stashBuffer, _)) => restartingInProgress = OptionVal.None stashBuffer.unstashAll(ctx.asScala.asInstanceOf[scaladsl.ActorContext[Any]], newBehavior.unsafeCast) } nextBehavior.narrow } catch handleException(ctx, signalRestart = { - case e: UnstashException[O] @unchecked ⇒ Behavior.interpretSignal(e.behavior, ctx, PreRestart) - case _ ⇒ () + case e: UnstashException[O] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart) + case _ => () }) } private def stopChildren(ctx: TypedActorContext[_], children: Set[ActorRef[Nothing]]): Unit = { - children.foreach { child ⇒ + children.foreach { child => ctx.asScala.watch(child) ctx.asScala.stop(child) } @@ -355,12 +355,12 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav private def updateRestartCount(): Unit = { strategy match { - case restart: Restart ⇒ + case restart: Restart => val timeLeft = deadlineHasTimeLeft val newDeadline = if (deadline.isDefined && timeLeft) deadline else OptionVal.Some(Deadline.now + restart.withinTimeRange) restartCount = if (timeLeft) restartCount + 1 else 1 deadline = newDeadline - case _: Backoff ⇒ + case _: Backoff => restartCount += 1 } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/TimerSchedulerImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/TimerSchedulerImpl.scala index c0c27cb5b4..dd3459415b 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/TimerSchedulerImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/TimerSchedulerImpl.scala @@ -24,17 +24,17 @@ import scala.concurrent.duration.FiniteDuration override def toString = s"TimerMsg(key=$key, generation=$generation, owner=$owner)" } - def withTimers[T](factory: TimerSchedulerImpl[T] ⇒ Behavior[T]): Behavior[T] = { + def withTimers[T](factory: TimerSchedulerImpl[T] => Behavior[T]): Behavior[T] = { scaladsl.Behaviors.setup[T](wrapWithTimers(factory)) } - def wrapWithTimers[T](factory: TimerSchedulerImpl[T] ⇒ Behavior[T])(ctx: ActorContext[T]): Behavior[T] = + def wrapWithTimers[T](factory: TimerSchedulerImpl[T] => Behavior[T])(ctx: ActorContext[T]): Behavior[T] = ctx match { - case ctxImpl: ActorContextImpl[T] ⇒ + case ctxImpl: ActorContextImpl[T] => val timerScheduler = ctxImpl.timer val behavior = factory(timerScheduler) timerScheduler.intercept(behavior) - case _ ⇒ throw new IllegalArgumentException(s"timers not supported with [${ctx.getClass}]") + case _ => throw new IllegalArgumentException(s"timers not supported with [${ctx.getClass}]") } } @@ -63,8 +63,8 @@ import scala.concurrent.duration.FiniteDuration private def startTimer(key: Any, msg: T, delay: FiniteDuration, repeat: Boolean): Unit = { timers.get(key) match { - case Some(t) ⇒ cancelTimer(t) - case None ⇒ + case Some(t) => cancelTimer(t) + case None => } val nextGen = timerGen.next() @@ -94,8 +94,8 @@ import scala.concurrent.duration.FiniteDuration override def cancel(key: Any): Unit = { timers.get(key) match { - case None ⇒ // already removed/canceled - case Some(t) ⇒ cancelTimer(t) + case None => // already removed/canceled + case Some(t) => cancelTimer(t) } } @@ -107,7 +107,7 @@ import scala.concurrent.duration.FiniteDuration override def cancelAll(): Unit = { ctx.log.debug("Cancel all timers") - timers.valuesIterator.foreach { timer ⇒ + timers.valuesIterator.foreach { timer => timer.task.cancel() } timers = Map.empty @@ -115,11 +115,11 @@ import scala.concurrent.duration.FiniteDuration def interceptTimerMsg(log: Logger, timerMsg: TimerMsg): OptionVal[T] = { timers.get(timerMsg.key) match { - case None ⇒ + case None => // it was from canceled timer that was already enqueued in mailbox log.debug("Received timer [{}] that has been removed, discarding", timerMsg.key) OptionVal.none // message should be ignored - case Some(t) ⇒ + case Some(t) => if (timerMsg.owner ne this) { // after restart, it was from an old instance that was enqueued in mailbox before canceled log.debug("Received timer [{}] from old restarted instance, discarding", timerMsg.key) @@ -158,20 +158,20 @@ private final class TimerInterceptor[T](timerSchedulerImpl: TimerSchedulerImpl[T override def aroundReceive(ctx: typed.TypedActorContext[T], msg: T, target: ReceiveTarget[T]): Behavior[T] = { val maybeIntercepted = msg match { - case msg: TimerMsg ⇒ timerSchedulerImpl.interceptTimerMsg(ctx.asScala.log, msg) - case msg ⇒ OptionVal.Some(msg) + case msg: TimerMsg => timerSchedulerImpl.interceptTimerMsg(ctx.asScala.log, msg) + case msg => OptionVal.Some(msg) } maybeIntercepted match { - case OptionVal.None ⇒ Behavior.same // None means not applicable - case OptionVal.Some(intercepted) ⇒ target(ctx, intercepted) + case OptionVal.None => Behavior.same // None means not applicable + case OptionVal.Some(intercepted) => target(ctx, intercepted) } } override def aroundSignal(ctx: typed.TypedActorContext[T], signal: Signal, target: SignalTarget[T]): Behavior[T] = { signal match { - case PreRestart | PostStop ⇒ timerSchedulerImpl.cancelAll() - case _ ⇒ // unhandled + case PreRestart | PostStop => timerSchedulerImpl.cancelAll() + case _ => // unhandled } target(ctx, signal) } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/WithMdcBehaviorInterceptor.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/WithMdcBehaviorInterceptor.scala index 2d3f12fcc0..2819376665 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/WithMdcBehaviorInterceptor.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/WithMdcBehaviorInterceptor.scala @@ -14,11 +14,11 @@ import scala.collection.immutable.HashMap * INTERNAL API */ @InternalApi private[akka] object WithMdcBehaviorInterceptor { - val noMdcPerMessage = (_: Any) ⇒ Map.empty[String, Any] + val noMdcPerMessage = (_: Any) => Map.empty[String, Any] def apply[T]( staticMdc: Map[String, Any], - mdcForMessage: T ⇒ Map[String, Any], + mdcForMessage: T => Map[String, Any], behavior: Behavior[T]): Behavior[T] = { val interceptor = new WithMdcBehaviorInterceptor[T](staticMdc, mdcForMessage) @@ -34,7 +34,7 @@ import scala.collection.immutable.HashMap */ @InternalApi private[akka] final class WithMdcBehaviorInterceptor[T] private ( staticMdc: Map[String, Any], - mdcForMessage: T ⇒ Map[String, Any]) extends BehaviorInterceptor[T, T] { + mdcForMessage: T => Map[String, Any]) extends BehaviorInterceptor[T, T] { import BehaviorInterceptor._ @@ -49,17 +49,17 @@ import scala.collection.immutable.HashMap // so we need to look through the stack and eliminate any MCD already existing def loop(next: Behavior[T]): Behavior[T] = { next match { - case i: InterceptorImpl[T, T] if i.interceptor.isSame(this.asInstanceOf[BehaviorInterceptor[Any, Any]]) ⇒ + case i: InterceptorImpl[T, T] if i.interceptor.isSame(this.asInstanceOf[BehaviorInterceptor[Any, Any]]) => // eliminate that interceptor loop(i.nestedBehavior) - case w: WrappingBehavior[T, T] ⇒ + case w: WrappingBehavior[T, T] => val nested = w.nestedBehavior val inner = loop(nested) if (inner eq nested) w else w.replaceNested(inner) - case b ⇒ b + case b => b } } @@ -68,8 +68,8 @@ import scala.collection.immutable.HashMap // in the normal case, a new withMDC replaces the previous one override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = other match { - case _: WithMdcBehaviorInterceptor[_] ⇒ true - case _ ⇒ false + case _: WithMdcBehaviorInterceptor[_] => true + case _ => false } override def aroundReceive(ctx: TypedActorContext[T], msg: T, target: ReceiveTarget[T]): Behavior[T] = { diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorAdapter.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorAdapter.scala index ec07ebf4af..c1ee4248ec 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorAdapter.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorAdapter.scala @@ -16,7 +16,7 @@ import scala.util.Success import scala.util.Try import scala.util.control.Exception.Catcher -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } import akka.annotation.InternalApi import akka.util.OptionVal @@ -57,7 +57,7 @@ import akka.util.OptionVal def receive: Receive = running def running: Receive = { - case untyped.Terminated(ref) ⇒ + case untyped.Terminated(ref) => val msg = if (failures contains ref) { val ex = failures(ref) @@ -65,18 +65,18 @@ import akka.util.OptionVal ChildFailed(ActorRefAdapter(ref), ex) } else Terminated(ActorRefAdapter(ref)) handleSignal(msg) - case untyped.ReceiveTimeout ⇒ + case untyped.ReceiveTimeout => handleMessage(ctx.receiveTimeoutMsg) - case wrapped: AdaptMessage[Any, T] @unchecked ⇒ - withSafelyAdapted(() ⇒ wrapped.adapt()) { - case AdaptWithRegisteredMessageAdapter(msg) ⇒ + case wrapped: AdaptMessage[Any, T] @unchecked => + withSafelyAdapted(() => wrapped.adapt()) { + case AdaptWithRegisteredMessageAdapter(msg) => adaptAndHandle(msg) - case msg: T @unchecked ⇒ + case msg: T @unchecked => handleMessage(msg) } - case AdaptWithRegisteredMessageAdapter(msg) ⇒ + case AdaptWithRegisteredMessageAdapter(msg) => adaptAndHandle(msg) - case msg: T @unchecked ⇒ + case msg: T @unchecked => handleMessage(msg) } @@ -93,13 +93,13 @@ import akka.util.OptionVal } private def handleUnstashException: Catcher[Unit] = { - case e: UnstashException[T] @unchecked ⇒ + case e: UnstashException[T] @unchecked => behavior = e.behavior throw e.cause - case TypedActorFailedException(e: UnstashException[T] @unchecked) ⇒ + case TypedActorFailedException(e: UnstashException[T] @unchecked) => behavior = e.behavior throw TypedActorFailedException(e.cause) - case ActorInitializationException(actor, message, e: UnstashException[T] @unchecked) ⇒ + case ActorInitializationException(actor, message, e: UnstashException[T] @unchecked) => behavior = e.behavior throw ActorInitializationException(actor, message, e.cause) } @@ -108,37 +108,37 @@ import akka.util.OptionVal if (Behavior.isUnhandled(b)) unhandled(msg) else { b match { - case s: StoppedBehavior[T] ⇒ + case s: StoppedBehavior[T] => // use StoppedBehavior with previous behavior or an explicitly given `postStop` behavior // until Terminate is received, i.e until postStop is invoked, and there PostStop // will be signaled to the previous/postStop behavior s.postStop match { - case OptionVal.None ⇒ + case OptionVal.None => // use previous as the postStop behavior behavior = new Behavior.StoppedBehavior(OptionVal.Some(behavior)) - case OptionVal.Some(postStop) ⇒ + case OptionVal.Some(postStop) => // use the given postStop behavior, but canonicalize it behavior = new Behavior.StoppedBehavior(OptionVal.Some(Behavior.canonicalize(postStop, behavior, ctx))) } context.stop(self) - case f: FailedBehavior ⇒ + case f: FailedBehavior => // For the parent untyped supervisor to pick up the exception throw TypedActorFailedException(f.cause) - case _ ⇒ + case _ => behavior = Behavior.canonicalize(b, behavior, ctx) } } } private def adaptAndHandle(msg: Any): Unit = { - @tailrec def handle(adapters: List[(Class[_], Any ⇒ T)]): Unit = { + @tailrec def handle(adapters: List[(Class[_], Any => T)]): Unit = { adapters match { - case Nil ⇒ + case Nil => // no adapter function registered for message class unhandled(msg) - case (clazz, f) :: tail ⇒ + case (clazz, f) :: tail => if (clazz.isAssignableFrom(msg.getClass)) { - withSafelyAdapted(() ⇒ f(msg))(handleMessage) + withSafelyAdapted(() => f(msg))(handleMessage) } else handle(tail) // recursive } @@ -146,35 +146,35 @@ import akka.util.OptionVal handle(ctx.messageAdapters) } - private def withSafelyAdapted[U, V](adapt: () ⇒ U)(body: U ⇒ V): Unit = { + private def withSafelyAdapted[U, V](adapt: () => U)(body: U => V): Unit = { Try(adapt()) match { - case Success(a) ⇒ + case Success(a) => body(a) - case Failure(ex) ⇒ + case Failure(ex) => log.error(ex, "Exception thrown out of adapter. Stopping myself.") context.stop(self) } } override def unhandled(msg: Any): Unit = msg match { - case Terminated(ref) ⇒ throw DeathPactException(ref) - case _: Signal ⇒ // that's ok - case other ⇒ super.unhandled(other) + case Terminated(ref) => throw DeathPactException(ref) + case _: Signal => // that's ok + case other => super.unhandled(other) } override val supervisorStrategy = untyped.OneForOneStrategy(loggingEnabled = false) { - case TypedActorFailedException(cause) ⇒ + case TypedActorFailedException(cause) => // These have already been optionally logged by typed supervision recordChildFailure(cause) untyped.SupervisorStrategy.Stop - case ex ⇒ + case ex => recordChildFailure(ex) val logMessage = ex match { - case e: ActorInitializationException if e.getCause ne null ⇒ e.getCause match { - case ex: InvocationTargetException if ex.getCause ne null ⇒ ex.getCause.getMessage - case ex ⇒ ex.getMessage + case e: ActorInitializationException if e.getCause ne null => e.getCause match { + case ex: InvocationTargetException if ex.getCause ne null => ex.getCause.getMessage + case ex => ex.getMessage } - case e ⇒ e.getMessage + case e => e.getMessage } // log at Error as that is what the supervision strategy would have done. log.error(ex, logMessage) @@ -219,14 +219,14 @@ import akka.util.OptionVal override def postStop(): Unit = { behavior match { - case null ⇒ // skip PostStop - case _: DeferredBehavior[_] ⇒ + case null => // skip PostStop + case _: DeferredBehavior[_] => // Do not undefer a DeferredBehavior as that may cause creation side-effects, which we do not want on termination. - case s: StoppedBehavior[_] ⇒ s.postStop match { - case OptionVal.Some(postStop) ⇒ Behavior.interpretSignal(postStop, ctx, PostStop) - case OptionVal.None ⇒ // no postStop behavior defined + case s: StoppedBehavior[_] => s.postStop match { + case OptionVal.Some(postStop) => Behavior.interpretSignal(postStop, ctx, PostStop) + case OptionVal.None => // no postStop behavior defined } - case b ⇒ Behavior.interpretSignal(b, ctx, PostStop) + case b => Behavior.interpretSignal(b, ctx, PostStop) } behavior = Behavior.stopped @@ -254,11 +254,11 @@ private[typed] class GuardianActorAdapter[T](_initialBehavior: Behavior[T]) exte context.become(waitingForStart(Nil)) def waitingForStart(stashed: List[Any]): Receive = { - case GuardianActorAdapter.Start ⇒ + case GuardianActorAdapter.Start => start() stashed.reverse.foreach(receive) - case other ⇒ + case other => // unlikely to happen but not impossible context.become(waitingForStart(other :: stashed)) } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorContextAdapter.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorContextAdapter.scala index 22bad40716..9d27561c07 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorContextAdapter.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorContextAdapter.scala @@ -10,7 +10,7 @@ import akka.actor.ExtendedActorSystem import akka.annotation.InternalApi import akka.event.LoggingFilterWithMarker import akka.util.OptionVal -import akka.{ ConfigurationException, actor ⇒ untyped } +import akka.{ ConfigurationException, actor => untyped } import scala.concurrent.ExecutionContextExecutor import scala.concurrent.duration._ @@ -38,14 +38,14 @@ import scala.concurrent.duration._ override def stop[U](child: ActorRef[U]): Unit = if (child.path.parent == self.path) { // only if a direct child toUntyped(child) match { - case f: akka.actor.FunctionRef ⇒ + case f: akka.actor.FunctionRef => val cell = untypedContext.asInstanceOf[akka.actor.ActorCell] cell.removeFunctionRef(f) - case c ⇒ + case c => untypedContext.child(child.path.name) match { - case Some(`c`) ⇒ + case Some(`c`) => untypedContext.stop(c) - case _ ⇒ + case _ => // child that was already stopped } } @@ -79,10 +79,10 @@ import scala.concurrent.duration._ import untypedContext.dispatcher untypedContext.system.scheduler.scheduleOnce(delay, toUntyped(target), msg) } - override private[akka] def internalSpawnMessageAdapter[U](f: U ⇒ T, _name: String): ActorRef[U] = { + override private[akka] def internalSpawnMessageAdapter[U](f: U => T, _name: String): ActorRef[U] = { val cell = untypedContext.asInstanceOf[akka.actor.ActorCell] // apply the function inside the actor by wrapping the msg and f, handled by ActorAdapter - val ref = cell.addFunctionRef((_, msg) ⇒ untypedContext.self ! AdaptMessage[U, T](msg.asInstanceOf[U], f), _name) + val ref = cell.addFunctionRef((_, msg) => untypedContext.self ! AdaptMessage[U, T](msg.asInstanceOf[U], f), _name) ActorRefAdapter[U](ref) } @@ -96,8 +96,8 @@ import scala.concurrent.duration._ override def log: Logger = { actorLogger match { - case OptionVal.Some(logger) ⇒ logger - case OptionVal.None ⇒ + case OptionVal.Some(logger) => logger + case OptionVal.None => val logClass = LoggerClass.detectLoggerClassFromStack(classOf[Behavior[_]]) initLoggerWithClass(logClass) } @@ -115,8 +115,8 @@ import scala.concurrent.duration._ private def toUntypedImp[U](context: TypedActorContext[_]): untyped.ActorContext = context match { - case adapter: ActorContextAdapter[_] ⇒ adapter.untypedContext - case _ ⇒ + case adapter: ActorContextAdapter[_] => adapter.untypedContext + case _ => throw new UnsupportedOperationException("only adapted untyped ActorContext permissible " + s"($context of class ${context.getClass.getName})") } @@ -125,16 +125,16 @@ import scala.concurrent.duration._ def toUntyped[U](context: scaladsl.ActorContext[_]): untyped.ActorContext = context match { - case c: TypedActorContext[_] ⇒ toUntypedImp(c) - case _ ⇒ + case c: TypedActorContext[_] => toUntypedImp(c) + case _ => throw new UnsupportedOperationException("unknown ActorContext type " + s"($context of class ${context.getClass.getName})") } def toUntyped[U](context: javadsl.ActorContext[_]): untyped.ActorContext = context match { - case c: TypedActorContext[_] ⇒ toUntypedImp(c) - case _ ⇒ + case c: TypedActorContext[_] => toUntypedImp(c) + case _ => throw new UnsupportedOperationException("unknown ActorContext type " + s"($context of class ${context.getClass.getName})") } @@ -142,9 +142,9 @@ import scala.concurrent.duration._ def spawnAnonymous[T](context: akka.actor.ActorContext, behavior: Behavior[T], props: Props): ActorRef[T] = { try { Behavior.validateAsInitial(behavior) - ActorRefAdapter(context.actorOf(PropsAdapter(() ⇒ behavior, props))) + ActorRefAdapter(context.actorOf(PropsAdapter(() => behavior, props))) } catch { - case ex: ConfigurationException if ex.getMessage.startsWith("configuration requested remote deployment") ⇒ + case ex: ConfigurationException if ex.getMessage.startsWith("configuration requested remote deployment") => throw new ConfigurationException("Remote deployment not allowed for typed actors", ex) } } @@ -152,9 +152,9 @@ import scala.concurrent.duration._ def spawn[T](context: akka.actor.ActorContext, behavior: Behavior[T], name: String, props: Props): ActorRef[T] = { try { Behavior.validateAsInitial(behavior) - ActorRefAdapter(context.actorOf(PropsAdapter(() ⇒ behavior, props), name)) + ActorRefAdapter(context.actorOf(PropsAdapter(() => behavior, props), name)) } catch { - case ex: ConfigurationException if ex.getMessage.startsWith("configuration requested remote deployment") ⇒ + case ex: ConfigurationException if ex.getMessage.startsWith("configuration requested remote deployment") => throw new ConfigurationException("Remote deployment not allowed for typed actors", ex) } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorRefAdapter.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorRefAdapter.scala index 5b832fb219..eaea2af89b 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorRefAdapter.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorRefAdapter.scala @@ -8,7 +8,7 @@ package adapter import akka.actor.ActorRefProvider import akka.actor.InvalidMessageException -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } import akka.annotation.InternalApi import akka.dispatch.sysmsg @@ -45,23 +45,23 @@ private[akka] object ActorRefAdapter { def toUntyped[U](ref: ActorRef[U]): akka.actor.InternalActorRef = ref match { - case adapter: ActorRefAdapter[_] ⇒ adapter.untypedRef - case system: ActorSystemAdapter[_] ⇒ system.untypedSystem.guardian - case _ ⇒ + case adapter: ActorRefAdapter[_] => adapter.untypedRef + case system: ActorSystemAdapter[_] => system.untypedSystem.guardian + case _ => throw new UnsupportedOperationException("only adapted untyped ActorRefs permissible " + s"($ref of class ${ref.getClass.getName})") } def sendSystemMessage(untypedRef: akka.actor.InternalActorRef, signal: internal.SystemMessage): Unit = signal match { - case internal.Create() ⇒ throw new IllegalStateException("WAT? No, seriously.") - case internal.Terminate() ⇒ untypedRef.stop() - case internal.Watch(watchee, watcher) ⇒ untypedRef.sendSystemMessage( + case internal.Create() => throw new IllegalStateException("WAT? No, seriously.") + case internal.Terminate() => untypedRef.stop() + case internal.Watch(watchee, watcher) => untypedRef.sendSystemMessage( sysmsg.Watch( toUntyped(watchee), toUntyped(watcher))) - case internal.Unwatch(watchee, watcher) ⇒ untypedRef.sendSystemMessage(sysmsg.Unwatch(toUntyped(watchee), toUntyped(watcher))) - case internal.DeathWatchNotification(ref, _) ⇒ untypedRef.sendSystemMessage(sysmsg.DeathWatchNotification(toUntyped(ref), true, false)) - case internal.NoMessage ⇒ // just to suppress the warning + case internal.Unwatch(watchee, watcher) => untypedRef.sendSystemMessage(sysmsg.Unwatch(toUntyped(watchee), toUntyped(watcher))) + case internal.DeathWatchNotification(ref, _) => untypedRef.sendSystemMessage(sysmsg.DeathWatchNotification(toUntyped(ref), true, false)) + case internal.NoMessage => // just to suppress the warning } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorSystemAdapter.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorSystemAdapter.scala index 5864484026..be93d6e644 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorSystemAdapter.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/ActorSystemAdapter.scala @@ -11,7 +11,7 @@ import java.util.concurrent.CompletionStage import akka.actor import akka.actor.ExtendedActorSystem import akka.actor.InvalidMessageException -import akka.{ actor ⇒ untyped } +import akka.{ actor => untyped } import scala.concurrent.ExecutionContextExecutor import akka.util.Timeout @@ -62,8 +62,8 @@ import akka.event.LoggingFilterWithMarker override def dispatchers: Dispatchers = new Dispatchers { override def lookup(selector: DispatcherSelector): ExecutionContextExecutor = selector match { - case DispatcherDefault(_) ⇒ untypedSystem.dispatcher - case DispatcherFromConfig(str, _) ⇒ untypedSystem.dispatchers.lookup(str) + case DispatcherDefault(_) => untypedSystem.dispatcher + case DispatcherFromConfig(str, _) => untypedSystem.dispatchers.lookup(str) } override def shutdown(): Unit = () // there was no shutdown in untyped Akka } @@ -82,14 +82,14 @@ import akka.event.LoggingFilterWithMarker import akka.dispatch.ExecutionContexts.sameThreadExecutionContext override def terminate(): scala.concurrent.Future[akka.actor.typed.Terminated] = - untypedSystem.terminate().map(t ⇒ Terminated(ActorRefAdapter(t.actor)))(sameThreadExecutionContext) + untypedSystem.terminate().map(t => Terminated(ActorRefAdapter(t.actor)))(sameThreadExecutionContext) override lazy val whenTerminated: scala.concurrent.Future[akka.actor.typed.Terminated] = - untypedSystem.whenTerminated.map(t ⇒ Terminated(ActorRefAdapter(t.actor)))(sameThreadExecutionContext) + untypedSystem.whenTerminated.map(t => Terminated(ActorRefAdapter(t.actor)))(sameThreadExecutionContext) override lazy val getWhenTerminated: CompletionStage[akka.actor.typed.Terminated] = FutureConverters.toJava(whenTerminated) def systemActorOf[U](behavior: Behavior[U], name: String, props: Props)(implicit timeout: Timeout): Future[ActorRef[U]] = { - val ref = untypedSystem.systemActorOf(PropsAdapter(() ⇒ behavior, props), name) + val ref = untypedSystem.systemActorOf(PropsAdapter(() => behavior, props), name) Future.successful(ActorRefAdapter(ref)) } @@ -129,8 +129,8 @@ private[akka] object ActorSystemAdapter { def toUntyped[U](sys: ActorSystem[_]): untyped.ActorSystem = sys match { - case adapter: ActorSystemAdapter[_] ⇒ adapter.untypedSystem - case _ ⇒ throw new UnsupportedOperationException("only adapted untyped ActorSystem permissible " + + case adapter: ActorSystemAdapter[_] => adapter.untypedSystem + case _ => throw new UnsupportedOperationException("only adapted untyped ActorSystem permissible " + s"($sys of class ${sys.getClass.getName})") } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/LoggerAdapterImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/LoggerAdapterImpl.scala index db92150d4a..6988d1cfbe 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/LoggerAdapterImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/LoggerAdapterImpl.scala @@ -7,7 +7,7 @@ package akka.actor.typed.internal.adapter import akka.actor.typed.{ LogMarker, Logger } import akka.annotation.InternalApi import akka.event.Logging._ -import akka.event.{ LoggingBus, LoggingFilter, LoggingFilterWithMarker, LogMarker ⇒ UntypedLM } +import akka.event.{ LoggingBus, LoggingFilter, LoggingFilterWithMarker, LogMarker => UntypedLM } import akka.util.OptionVal import scala.collection.JavaConverters._ @@ -310,11 +310,11 @@ private[akka] abstract class AbstractLogger extends Logger { } protected def notify(level: LogLevel, message: String, marker: OptionVal[LogMarker]): Unit = level match { - case ErrorLevel ⇒ notifyDebug(message, marker) - case WarningLevel ⇒ notifyWarning(message, OptionVal.None, marker) - case InfoLevel ⇒ notifyInfo(message, marker) - case DebugLevel ⇒ notifyDebug(message, marker) - case _ ⇒ () + case ErrorLevel => notifyDebug(message, marker) + case WarningLevel => notifyWarning(message, OptionVal.None, marker) + case InfoLevel => notifyInfo(message, marker) + case DebugLevel => notifyDebug(message, marker) + case _ => () } /** @@ -322,9 +322,9 @@ private[akka] abstract class AbstractLogger extends Logger { * there are more than four arguments. */ private def format(t: String, arg1: Any): String = arg1 match { - case a: Array[_] if !a.getClass.getComponentType.isPrimitive ⇒ formatArray(t, a: _*) - case a: Array[_] ⇒ formatArray(t, (a map (_.asInstanceOf[AnyRef]): _*)) - case x ⇒ formatArray(t, x) + case a: Array[_] if !a.getClass.getComponentType.isPrimitive => formatArray(t, a: _*) + case a: Array[_] => formatArray(t, (a map (_.asInstanceOf[AnyRef]): _*)) + case x => formatArray(t, x) } private def format(t: String, arg1: Any, arg2: Any): String = formatArray(t, arg1, arg2) private def format(t: String, arg1: Any, arg2: Any, arg3: Any): String = formatArray(t, arg1, arg2, arg3) @@ -390,15 +390,15 @@ private[akka] final class LoggerAdapterImpl(bus: LoggingBus, logClass: Class[_], private[akka] def notifyError(message: String, cause: OptionVal[Throwable], marker: OptionVal[LogMarker]): Unit = { val error = cause match { - case OptionVal.Some(cause) ⇒ + case OptionVal.Some(cause) => marker match { - case OptionVal.Some(m) ⇒ Error(cause, logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) - case OptionVal.None ⇒ Error(cause, logSource, logClass, message, mdc) + case OptionVal.Some(m) => Error(cause, logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) + case OptionVal.None => Error(cause, logSource, logClass, message, mdc) } - case OptionVal.None ⇒ + case OptionVal.None => marker match { - case OptionVal.Some(m) ⇒ Error(logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) - case OptionVal.None ⇒ Error(logSource, logClass, message, mdc) + case OptionVal.Some(m) => Error(logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) + case OptionVal.None => Error(logSource, logClass, message, mdc) } } bus.publish(error) @@ -408,24 +408,24 @@ private[akka] final class LoggerAdapterImpl(bus: LoggingBus, logClass: Class[_], val warning = if (cause.isDefined) Warning(cause.get, logSource, logClass, message, mdc, marker.orNull.asInstanceOf[UntypedLM]) else marker match { - case OptionVal.Some(m) ⇒ Warning(logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) - case OptionVal.None ⇒ Warning(logSource, logClass, message, mdc) + case OptionVal.Some(m) => Warning(logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) + case OptionVal.None => Warning(logSource, logClass, message, mdc) } bus.publish(warning) } private[akka] def notifyInfo(message: String, marker: OptionVal[LogMarker]): Unit = { val info = marker match { - case OptionVal.Some(m) ⇒ Info(logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) - case OptionVal.None ⇒ Info(logSource, logClass, message, mdc) + case OptionVal.Some(m) => Info(logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) + case OptionVal.None => Info(logSource, logClass, message, mdc) } bus.publish(info) } private[akka] def notifyDebug(message: String, marker: OptionVal[LogMarker]): Unit = { val debug = marker match { - case OptionVal.Some(m) ⇒ Debug(logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) - case OptionVal.None ⇒ Debug(logSource, logClass, message, mdc) + case OptionVal.Some(m) => Debug(logSource, logClass, message, mdc, m.asInstanceOf[UntypedLM]) + case OptionVal.None => Debug(logSource, logClass, message, mdc) } bus.publish(debug) } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/PropsAdapter.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/PropsAdapter.scala index 3fc7b81e3e..ececc7b5c1 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/PropsAdapter.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/adapter/PropsAdapter.scala @@ -13,7 +13,7 @@ import akka.annotation.InternalApi * INTERNAL API */ @InternalApi private[akka] object PropsAdapter { - def apply[T](behavior: () ⇒ Behavior[T], deploy: Props = Props.empty, isGuardian: Boolean = false): akka.actor.Props = { + def apply[T](behavior: () => Behavior[T], deploy: Props = Props.empty, isGuardian: Boolean = false): akka.actor.Props = { val props = if (isGuardian) akka.actor.Props(new GuardianActorAdapter(behavior())) @@ -21,8 +21,8 @@ import akka.annotation.InternalApi akka.actor.Props(new ActorAdapter(behavior())) (deploy.firstOrElse[DispatcherSelector](DispatcherDefault()) match { - case _: DispatcherDefault ⇒ props - case DispatcherFromConfig(name, _) ⇒ props.withDispatcher(name) + case _: DispatcherDefault => props + case DispatcherFromConfig(name, _) => props.withDispatcher(name) }).withDeploy(Deploy.local) // disallow remote deployment for typed actors } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/receptionist/LocalReceptionist.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/receptionist/LocalReceptionist.scala index 39b32ce127..f59845ced8 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/receptionist/LocalReceptionist.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/receptionist/LocalReceptionist.scala @@ -40,7 +40,7 @@ private[akka] object LocalReceptionist extends ReceptionistBehaviorProvider { final case class RegisteredActorTerminated[T](key: ServiceKey[T], ref: ActorRef[T]) extends InternalCommand final case class SubscriberTerminated[T](key: ServiceKey[T], ref: ActorRef[ReceptionistMessages.Listing[T]]) extends InternalCommand - override def behavior: Behavior[Command] = Behaviors.setup { ctx ⇒ + override def behavior: Behavior[Command] = Behaviors.setup { ctx => ctx.setLoggerClass(classOf[LocalReceptionist]) behavior( TypedMultiMap.empty[AbstractServiceKey, KV], @@ -61,17 +61,17 @@ private[akka] object LocalReceptionist extends ReceptionistBehaviorProvider { * FIXME: replace by simple map in our state */ def watchWith(ctx: ActorContext[Any], target: ActorRef[_], msg: InternalCommand): Unit = - ctx.spawnAnonymous[Nothing](Behaviors.setup[Nothing] { innerCtx ⇒ + ctx.spawnAnonymous[Nothing](Behaviors.setup[Nothing] { innerCtx => innerCtx.watch(target) Behaviors.receiveSignal[Nothing] { - case (_, Terminated(`target`)) ⇒ + case (_, Terminated(`target`)) => ctx.self ! msg Behaviors.stopped } }) // Helper that makes sure that subscribers are notified when an entry is changed - def updateRegistry(changedKeysHint: Set[AbstractServiceKey], f: LocalServiceRegistry ⇒ LocalServiceRegistry): Behavior[Any] = { + def updateRegistry(changedKeysHint: Set[AbstractServiceKey], f: LocalServiceRegistry => LocalServiceRegistry): Behavior[Any] = { val newRegistry = f(serviceRegistry) def notifySubscribersFor[T](key: AbstractServiceKey): Unit = { @@ -87,20 +87,20 @@ private[akka] object LocalReceptionist extends ReceptionistBehaviorProvider { replyTo ! ReceptionistMessages.Listing(key, serviceRegistry get key) def onCommand(ctx: ActorContext[Any], cmd: Command): Behavior[Any] = cmd match { - case ReceptionistMessages.Register(key, serviceInstance, maybeReplyTo) ⇒ + case ReceptionistMessages.Register(key, serviceInstance, maybeReplyTo) => ctx.log.debug("Actor was registered: {} {}", key, serviceInstance) watchWith(ctx, serviceInstance, RegisteredActorTerminated(key, serviceInstance)) maybeReplyTo match { - case Some(replyTo) ⇒ replyTo ! ReceptionistMessages.Registered(key, serviceInstance) - case None ⇒ + case Some(replyTo) => replyTo ! ReceptionistMessages.Registered(key, serviceInstance) + case None => } updateRegistry(Set(key), _.inserted(key)(serviceInstance)) - case ReceptionistMessages.Find(key, replyTo) ⇒ + case ReceptionistMessages.Find(key, replyTo) => replyWithListing(key, replyTo) same - case ReceptionistMessages.Subscribe(key, subscriber) ⇒ + case ReceptionistMessages.Subscribe(key, subscriber) => watchWith(ctx, subscriber, SubscriberTerminated(key, subscriber)) // immediately reply with initial listings to the new subscriber @@ -110,19 +110,19 @@ private[akka] object LocalReceptionist extends ReceptionistBehaviorProvider { } def onInternal(ctx: ActorContext[Any], cmd: InternalCommand): Behavior[Any] = cmd match { - case RegisteredActorTerminated(key, serviceInstance) ⇒ + case RegisteredActorTerminated(key, serviceInstance) => ctx.log.debug("Registered actor terminated: {} {}", key, serviceInstance) updateRegistry(Set(key), _.removed(key)(serviceInstance)) - case SubscriberTerminated(key, subscriber) ⇒ + case SubscriberTerminated(key, subscriber) => next(newSubscriptions = subscriptions.removed(key)(subscriber)) } - receive[Any] { (ctx, msg) ⇒ + receive[Any] { (ctx, msg) => msg match { - case cmd: Command ⇒ onCommand(ctx, cmd) - case cmd: InternalCommand ⇒ onInternal(ctx, cmd) - case _ ⇒ Behaviors.unhandled + case cmd: Command => onCommand(ctx, cmd) + case cmd: InternalCommand => onInternal(ctx, cmd) + case _ => Behaviors.unhandled } } } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/receptionist/ServiceKeySerializer.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/receptionist/ServiceKeySerializer.scala index 1725cabf09..25ab098e29 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/receptionist/ServiceKeySerializer.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/receptionist/ServiceKeySerializer.scala @@ -16,14 +16,14 @@ import akka.serialization.{ BaseSerializer, SerializerWithStringManifest } @InternalApi final class ServiceKeySerializer(val system: akka.actor.ExtendedActorSystem) extends SerializerWithStringManifest with BaseSerializer { def manifest(o: AnyRef): String = o match { - case key: DefaultServiceKey[_] ⇒ key.typeName - case _ ⇒ + case key: DefaultServiceKey[_] => key.typeName + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass} in [${getClass.getName}]") } def toBinary(o: AnyRef): Array[Byte] = o match { - case serviceKey: DefaultServiceKey[_] ⇒ serviceKey.id.getBytes(StandardCharsets.UTF_8) - case _ ⇒ + case serviceKey: DefaultServiceKey[_] => serviceKey.id.getBytes(StandardCharsets.UTF_8) + case _ => throw new IllegalArgumentException(s"Cannot serialize object of type [${o.getClass.getName}]") } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/GroupRouterImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/GroupRouterImpl.scala index 54a547fb08..a16f8282bf 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/GroupRouterImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/GroupRouterImpl.scala @@ -19,16 +19,16 @@ import akka.annotation.InternalApi @InternalApi private[akka] final case class GroupRouterBuilder[T] private[akka] ( key: ServiceKey[T], - logicFactory: () ⇒ RoutingLogic[T] = () ⇒ new RoutingLogics.RandomLogic[T]() + logicFactory: () => RoutingLogic[T] = () => new RoutingLogics.RandomLogic[T]() ) extends javadsl.GroupRouter[T] with scaladsl.GroupRouter[T] { // deferred creation of the actual router def apply(ctx: TypedActorContext[T]): Behavior[T] = new GroupRouterImpl[T](ctx.asScala, key, logicFactory()) - def withRandomRouting(): GroupRouterBuilder[T] = copy(logicFactory = () ⇒ new RoutingLogics.RandomLogic[T]()) + def withRandomRouting(): GroupRouterBuilder[T] = copy(logicFactory = () => new RoutingLogics.RandomLogic[T]()) - def withRoundRobinRouting(): GroupRouterBuilder[T] = copy(logicFactory = () ⇒ new RoutingLogics.RoundRobinLogic[T]) + def withRoundRobinRouting(): GroupRouterBuilder[T] = copy(logicFactory = () => new RoutingLogics.RoundRobinLogic[T]) } @@ -48,12 +48,12 @@ private final class GroupRouterImpl[T]( private var routeesEmpty = true def onMessage(msg: T): Behavior[T] = msg match { - case serviceKey.Listing(update) ⇒ + case serviceKey.Listing(update) => // we don't need to watch, because receptionist already does that routingLogic.routeesUpdated(update) routeesEmpty = update.isEmpty this - case msg: T @unchecked ⇒ + case msg: T @unchecked => if (!routeesEmpty) routingLogic.selectRoutee() ! msg else ctx.system.deadLetters ! Dropped(msg, ctx.self) this diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/PoolRouterImpl.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/PoolRouterImpl.scala index ba5782cc90..2dcfc40551 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/PoolRouterImpl.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/PoolRouterImpl.scala @@ -16,7 +16,7 @@ import akka.annotation.InternalApi private[akka] final case class PoolRouterBuilder[T]( poolSize: Int, behavior: Behavior[T], - logicFactory: () ⇒ RoutingLogic[T] = () ⇒ new RoutingLogics.RoundRobinLogic[T] + logicFactory: () => RoutingLogic[T] = () => new RoutingLogics.RoundRobinLogic[T] ) extends javadsl.PoolRouter[T] with scaladsl.PoolRouter[T] { if (poolSize < 1) throw new IllegalArgumentException(s"pool size must be positive, was $poolSize") @@ -24,9 +24,9 @@ private[akka] final case class PoolRouterBuilder[T]( // deferred creation of the actual router def apply(ctx: TypedActorContext[T]): Behavior[T] = new PoolRouterImpl[T](ctx.asScala, poolSize, behavior, logicFactory()) - def withRandomRouting(): PoolRouterBuilder[T] = copy(logicFactory = () ⇒ new RoutingLogics.RandomLogic[T]()) + def withRandomRouting(): PoolRouterBuilder[T] = copy(logicFactory = () => new RoutingLogics.RandomLogic[T]()) - def withRoundRobinRouting(): PoolRouterBuilder[T] = copy(logicFactory = () ⇒ new RoutingLogics.RoundRobinLogic[T]) + def withRoundRobinRouting(): PoolRouterBuilder[T] = copy(logicFactory = () => new RoutingLogics.RoundRobinLogic[T]) def withPoolSize(poolSize: Int): PoolRouterBuilder[T] = copy(poolSize = poolSize) } @@ -42,7 +42,7 @@ private final class PoolRouterImpl[T]( logic: RoutingLogic[T] ) extends AbstractBehavior[T] { - (1 to poolSize).foreach { _ ⇒ + (1 to poolSize).foreach { _ => val child = ctx.spawnAnonymous(behavior) ctx.watch(child) child @@ -60,7 +60,7 @@ private final class PoolRouterImpl[T]( } override def onSignal: PartialFunction[Signal, Behavior[T]] = { - case Terminated(child) ⇒ + case Terminated(child) => // Note that if several children are stopping concurrently children may already be empty // for the `Terminated` we receive for the first child. This means it is not certain that // there will be a log entry per child in those cases (it does not make sense to keep the diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/RoutingLogic.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/RoutingLogic.scala index 22fcf1489c..73fa2d5ce1 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/RoutingLogic.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/internal/routing/RoutingLogic.scala @@ -55,7 +55,7 @@ private[akka] object RoutingLogics { // make sure we keep a somewhat similar order so we can potentially continue roundrobining // from where we were unless the set of routees completely changed // Also, avoid putting all entries from the same node next to each other in case of cluster - val sortedNewRoutees = newRoutees.toArray.sortBy(ref ⇒ (ref.path.toStringWithoutAddress, ref.path.address)) + val sortedNewRoutees = newRoutees.toArray.sortBy(ref => (ref.path.toStringWithoutAddress, ref.path.address)) if (currentRoutees ne null) { val firstDiffIndex = { diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/AbstractBehavior.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/AbstractBehavior.scala index 5a63fb2cd5..4e67e779b3 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/AbstractBehavior.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/AbstractBehavior.scala @@ -25,11 +25,11 @@ import akka.util.OptionVal abstract class AbstractBehavior[T] extends ExtensibleBehavior[T] { private var _receive: OptionVal[Receive[T]] = OptionVal.None private def receive: Receive[T] = _receive match { - case OptionVal.None ⇒ + case OptionVal.None => val receive = createReceive _receive = OptionVal.Some(receive) receive - case OptionVal.Some(r) ⇒ r + case OptionVal.Some(r) => r } @throws(classOf[Exception]) diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/ActorContext.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/ActorContext.scala index b309473088..d6ed1b5939 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/ActorContext.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/ActorContext.scala @@ -5,7 +5,7 @@ package akka.actor.typed.javadsl import java.time.Duration -import java.util.function.{ BiFunction, Function ⇒ JFunction } +import java.util.function.{ BiFunction, Function => JFunction } import akka.annotation.DoNotInherit import akka.annotation.ApiMayChange diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/Adapter.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/Adapter.scala index a97b0d1ab0..8bdbf892fa 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/Adapter.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/Adapter.scala @@ -103,7 +103,7 @@ object Adapter { * example of that. */ def props[T](behavior: Creator[Behavior[T]], deploy: Props): akka.actor.Props = - akka.actor.typed.internal.adapter.PropsAdapter(() ⇒ behavior.create(), deploy) + akka.actor.typed.internal.adapter.PropsAdapter(() => behavior.create(), deploy) /** * Wrap [[akka.actor.typed.Behavior]] in an untyped [[akka.actor.Props]], i.e. when diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/AskPattern.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/AskPattern.scala index 4ad5cc75a8..ad85dabe8a 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/AskPattern.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/AskPattern.scala @@ -10,7 +10,7 @@ import java.util.concurrent.CompletionStage import akka.actor.Scheduler import akka.actor.typed.scaladsl.AskPattern._ -import akka.japi.function.{ Function ⇒ JFunction } +import akka.japi.function.{ Function => JFunction } import akka.util.JavaDurationConverters._ import scala.compat.java8.FutureConverters._ diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/BehaviorBuilder.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/BehaviorBuilder.scala index e99462326f..d7c42ceed1 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/BehaviorBuilder.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/BehaviorBuilder.scala @@ -5,9 +5,9 @@ package akka.actor.typed.javadsl import scala.annotation.tailrec -import akka.japi.function.{ Function ⇒ JFunction } -import akka.japi.function.{ Function2 ⇒ JFunction2 } -import akka.japi.function.{ Predicate ⇒ JPredicate } +import akka.japi.function.{ Function => JFunction } +import akka.japi.function.{ Function2 => JFunction2 } +import akka.japi.function.{ Predicate => JPredicate } import akka.annotation.InternalApi import akka.actor.typed.Behavior import akka.actor.typed.ExtensibleBehavior @@ -58,7 +58,7 @@ final class BehaviorBuilder[T] private ( def onMessage[M <: T](`type`: Class[M], test: JPredicate[M], handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] = withMessage( OptionVal.Some(`type`), - OptionVal.Some((t: T) ⇒ test.test(t.asInstanceOf[M])), + OptionVal.Some((t: T) => test.test(t.asInstanceOf[M])), handler) /** @@ -126,7 +126,7 @@ final class BehaviorBuilder[T] private ( def onSignal[M <: Signal](`type`: Class[M], test: JPredicate[M], handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] = withSignal( `type`, - OptionVal.Some((t: Signal) ⇒ test.test(t.asInstanceOf[M])), + OptionVal.Some((t: Signal) => test.test(t.asInstanceOf[M])), handler.asInstanceOf[JFunction2[ActorContext[T], Signal, Behavior[T]]] ) @@ -147,7 +147,7 @@ final class BehaviorBuilder[T] private ( } }) - private def withMessage[M <: T](clazz: OptionVal[Class[M]], test: OptionVal[M ⇒ Boolean], handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] = { + private def withMessage[M <: T](clazz: OptionVal[Class[M]], test: OptionVal[M => Boolean], handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] = { val newCase = Case( clazz, test, @@ -156,7 +156,7 @@ final class BehaviorBuilder[T] private ( new BehaviorBuilder[T](newCase.asInstanceOf[Case[T, T]] +: messageHandlers, signalHandlers) } - private def withSignal[M <: Signal](`type`: Class[M], test: OptionVal[Signal ⇒ Boolean], handler: JFunction2[ActorContext[T], Signal, Behavior[T]]): BehaviorBuilder[T] = { + private def withSignal[M <: Signal](`type`: Class[M], test: OptionVal[Signal => Boolean], handler: JFunction2[ActorContext[T], Signal, Behavior[T]]): BehaviorBuilder[T] = { new BehaviorBuilder[T]( messageHandlers, Case(OptionVal.Some(`type`), test, handler).asInstanceOf[Case[T, Signal]] +: signalHandlers @@ -171,7 +171,7 @@ object BehaviorBuilder { // used for both matching signals and messages so we throw away types after they are enforced by the builder API above /** INTERNAL API */ @InternalApi - private[javadsl] final case class Case[BT, MT](`type`: OptionVal[Class[_ <: MT]], test: OptionVal[MT ⇒ Boolean], handler: JFunction2[ActorContext[BT], MT, Behavior[BT]]) + private[javadsl] final case class Case[BT, MT](`type`: OptionVal[Class[_ <: MT]], test: OptionVal[MT => Boolean], handler: JFunction2[ActorContext[BT], MT, Behavior[BT]]) /** * @return new empty immutable behavior builder. @@ -197,11 +197,11 @@ private final class BuiltBehavior[T]( @tailrec private def receive[M](ctx: ActorContext[T], msg: M, handlers: List[Case[T, M]]): Behavior[T] = handlers match { - case Case(cls, predicate, handler) :: tail ⇒ + case Case(cls, predicate, handler) :: tail => if ((cls.isEmpty || cls.get.isAssignableFrom(msg.getClass)) && (predicate.isEmpty || predicate.get.apply(msg))) handler(ctx, msg) else receive(ctx, msg, tail) - case Nil ⇒ + case Nil => unhandled[T] } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/Behaviors.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/Behaviors.scala index 5ccaf2da1d..9c45575c84 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/Behaviors.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/Behaviors.scala @@ -5,12 +5,12 @@ package akka.actor.typed.javadsl import java.util.Collections -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import akka.actor.typed._ import akka.actor.typed.internal.{ BehaviorImpl, Supervisor, TimerSchedulerImpl, WithMdcBehaviorInterceptor } import akka.annotation.ApiMayChange -import akka.japi.function.{ Function2 ⇒ JapiFunction2 } +import akka.japi.function.{ Function2 => JapiFunction2 } import akka.japi.pf.PFBuilder import akka.util.unused @@ -40,7 +40,7 @@ object Behaviors { * processed by the started behavior. */ def setup[T](factory: akka.japi.function.Function[ActorContext[T], Behavior[T]]): Behavior[T] = - Behavior.DeferredBehavior(ctx ⇒ factory.apply(ctx.asJava)) + Behavior.DeferredBehavior(ctx => factory.apply(ctx.asJava)) /** * Return this behavior from message processing in order to advise the @@ -103,7 +103,7 @@ object Behaviors { * a new behavior that holds the new immutable state. */ def receive[T](onMessage: JapiFunction2[ActorContext[T], T, Behavior[T]]): Behavior[T] = - new BehaviorImpl.ReceiveBehavior((ctx, msg) ⇒ onMessage.apply(ctx.asJava, msg)) + new BehaviorImpl.ReceiveBehavior((ctx, msg) => onMessage.apply(ctx.asJava, msg)) /** * Simplified version of [[receive]] with only a single argument - the message @@ -122,7 +122,7 @@ object Behaviors { * a new behavior that holds the new immutable state. */ def receiveMessage[T](onMessage: akka.japi.Function[T, Behavior[T]]): Behavior[T] = - new BehaviorImpl.ReceiveBehavior((_, msg) ⇒ onMessage.apply(msg)) + new BehaviorImpl.ReceiveBehavior((_, msg) => onMessage.apply(msg)) /** * Construct an actor behavior that can react to both incoming messages and @@ -140,8 +140,8 @@ object Behaviors { onMessage: JapiFunction2[ActorContext[T], T, Behavior[T]], onSignal: JapiFunction2[ActorContext[T], Signal, Behavior[T]]): Behavior[T] = { new BehaviorImpl.ReceiveBehavior( - (ctx, msg) ⇒ onMessage.apply(ctx.asJava, msg), - { case (ctx, sig) ⇒ onSignal.apply(ctx.asJava, sig) }) + (ctx, msg) => onMessage.apply(ctx.asJava, msg), + { case (ctx, sig) => onSignal.apply(ctx.asJava, sig) }) } /** @@ -285,7 +285,7 @@ object Behaviors { * @see [[TimerScheduler]] */ def withTimers[T](factory: akka.japi.function.Function[TimerScheduler[T], Behavior[T]]): Behavior[T] = - TimerSchedulerImpl.withTimers(timers ⇒ factory.apply(timers)) + TimerSchedulerImpl.withTimers(timers => factory.apply(timers)) /** * Per message MDC (Mapped Diagnostic Context) logging. @@ -340,10 +340,10 @@ object Behaviors { else m.asScala.toMap } - val mdcForMessageFun: T ⇒ Map[String, Any] = + val mdcForMessageFun: T => Map[String, Any] = if (mdcForMessage == null) Map.empty else { - message ⇒ asScalaMap(mdcForMessage.apply(message)) + message => asScalaMap(mdcForMessage.apply(message)) } WithMdcBehaviorInterceptor[T]( diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/ReceiveBuilder.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/ReceiveBuilder.scala index 1768e22d02..23637ad6c8 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/ReceiveBuilder.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/ReceiveBuilder.scala @@ -6,8 +6,8 @@ package akka.actor.typed.javadsl import scala.annotation.tailrec import akka.japi.function.Creator -import akka.japi.function.{ Function ⇒ JFunction } -import akka.japi.function.{ Predicate ⇒ JPredicate } +import akka.japi.function.{ Function => JFunction } +import akka.japi.function.{ Predicate => JPredicate } import akka.actor.typed.{ Behavior, Signal } import akka.annotation.InternalApi import akka.util.OptionVal @@ -167,10 +167,10 @@ private final class BuiltReceive[T]( @tailrec private def receive[M](msg: M, handlers: List[Case[T, M]]): Behavior[T] = handlers match { - case Case(cls, predicate, handler) :: tail ⇒ + case Case(cls, predicate, handler) :: tail => if ((cls.isEmpty || cls.get.isAssignableFrom(msg.getClass)) && (predicate.isEmpty || predicate.get.test(msg))) handler(msg) else receive[M](msg, tail) - case _ ⇒ + case _ => Behaviors.unhandled } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/StashBuffer.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/StashBuffer.scala index f22bc15982..b1ed2b2444 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/StashBuffer.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/javadsl/StashBuffer.scala @@ -5,7 +5,7 @@ package akka.actor.typed.javadsl import java.util.function.Consumer -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import akka.actor.typed.Behavior import akka.actor.typed.internal.StashBufferImpl diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/receptionist/Receptionist.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/receptionist/Receptionist.scala index 2648f864ca..91a4343764 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/receptionist/Receptionist.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/receptionist/Receptionist.scala @@ -41,7 +41,7 @@ abstract class Receptionist extends Extension { system.dynamicAccess .getObjectFor[ReceptionistBehaviorProvider]("akka.cluster.typed.internal.receptionist.ClusterReceptionist") .recover { - case e ⇒ + case e => throw new RuntimeException("ClusterReceptionist could not be loaded dynamically. Make sure you have " + "'akka-cluster-typed' in the classpath.", e) }.get @@ -76,7 +76,7 @@ object ServiceKey { * Not for user extension, see factories in companion object: [[ServiceKey#create]] and [[ServiceKey#apply]] */ @DoNotInherit -abstract class ServiceKey[T] extends AbstractServiceKey { key ⇒ +abstract class ServiceKey[T] extends AbstractServiceKey { key => type Protocol = T def id: String def asServiceKey: ServiceKey[T] = this @@ -231,7 +231,7 @@ object Receptionist extends ExtensionId[Receptionist] { /** * Special factory to make using Find with ask easier */ - def apply[T](key: ServiceKey[T]): ActorRef[Listing] ⇒ Command = ref ⇒ new ReceptionistMessages.Find(key, ref) + def apply[T](key: ServiceKey[T]): ActorRef[Listing] => Command = ref => new ReceptionistMessages.Find(key, ref) } /** @@ -288,7 +288,7 @@ object Receptionist extends ExtensionId[Receptionist] { } object ReceptionistSetup { - def apply[T <: Extension](createExtension: ActorSystem[_] ⇒ Receptionist): ReceptionistSetup = + def apply[T <: Extension](createExtension: ActorSystem[_] => Receptionist): ReceptionistSetup = new ReceptionistSetup(new java.util.function.Function[ActorSystem[_], Receptionist] { override def apply(sys: ActorSystem[_]): Receptionist = createExtension(sys) }) // TODO can be simplified when compiled only with Scala >= 2.12 diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/AbstractBehavior.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/AbstractBehavior.scala index c466635012..3319f0c473 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/AbstractBehavior.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/AbstractBehavior.scala @@ -60,5 +60,5 @@ abstract class AbstractBehavior[T] extends ExtensibleBehavior[T] { @throws(classOf[Exception]) override final def receiveSignal(ctx: TypedActorContext[T], msg: Signal): Behavior[T] = - onSignal.applyOrElse(msg, { case _ ⇒ Behavior.unhandled }: PartialFunction[Signal, Behavior[T]]) + onSignal.applyOrElse(msg, { case _ => Behavior.unhandled }: PartialFunction[Signal, Behavior[T]]) } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/ActorContext.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/ActorContext.scala index 12f4447105..fd9825a80f 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/ActorContext.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/ActorContext.scala @@ -229,12 +229,12 @@ trait ActorContext[T] extends TypedActorContext[T] { * The function is applied inside the "parent" actor and can safely access * state of the "parent". */ - @InternalApi private[akka] def spawnMessageAdapter[U](f: U ⇒ T, name: String): ActorRef[U] + @InternalApi private[akka] def spawnMessageAdapter[U](f: U => T, name: String): ActorRef[U] /** * INTERNAL API: See `spawnMessageAdapter` with name parameter */ - @InternalApi private[akka] def spawnMessageAdapter[U](f: U ⇒ T): ActorRef[U] + @InternalApi private[akka] def spawnMessageAdapter[U](f: U => T): ActorRef[U] /** * Create a message adapter that will convert or wrap messages such that other Actor’s @@ -262,7 +262,7 @@ trait ActorContext[T] extends TypedActorContext[T] { * *Warning*: This method is not thread-safe and must not be accessed from threads other * than the ordinary actor message processing thread, such as [[scala.concurrent.Future]] callbacks. */ - def messageAdapter[U: ClassTag](f: U ⇒ T): ActorRef[U] + def messageAdapter[U: ClassTag](f: U => T): ActorRef[U] /** * Perform a single request-response message interaction with another actor, and transform the messages back to @@ -287,7 +287,7 @@ trait ActorContext[T] extends TypedActorContext[T] { * @tparam Req The request protocol, what the other actor accepts * @tparam Res The response protocol, what the other actor sends back */ - def ask[Req, Res](target: RecipientRef[Req])(createRequest: ActorRef[Res] ⇒ Req)(mapResponse: Try[Res] ⇒ T)(implicit responseTimeout: Timeout, classTag: ClassTag[Res]): Unit + def ask[Req, Res](target: RecipientRef[Req])(createRequest: ActorRef[Res] => Req)(mapResponse: Try[Res] => T)(implicit responseTimeout: Timeout, classTag: ClassTag[Res]): Unit /** * Sends the result of the given `Future` to this Actor (“`self`”), after adapted it with @@ -296,6 +296,6 @@ trait ActorContext[T] extends TypedActorContext[T] { * This method is thread-safe and can be called from other threads than the ordinary * actor message processing thread, such as [[scala.concurrent.Future]] callbacks. */ - def pipeToSelf[Value](future: Future[Value])(mapResult: Try[Value] ⇒ T): Unit + def pipeToSelf[Value](future: Future[Value])(mapResult: Try[Value] => T): Unit } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/AskPattern.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/AskPattern.scala index 892cc664fd..a3b67a530c 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/AskPattern.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/AskPattern.scala @@ -10,7 +10,7 @@ import scala.concurrent.Future import akka.actor.{ Address, RootActorPath, Scheduler } import akka.actor.typed.ActorRef -import akka.actor.typed.internal.{ adapter ⇒ adapt } +import akka.actor.typed.internal.{ adapter => adapt } import akka.annotation.InternalApi import akka.pattern.PromiseActorRef import akka.util.{ Timeout, unused } @@ -58,7 +58,7 @@ object AskPattern { * Note: it is preferrable to use the non-symbolic ask method as it easier allows for wildcards for * the `ActorRef`. */ - def ?[U](replyTo: ActorRef[U] ⇒ T)(implicit timeout: Timeout, @unused scheduler: Scheduler): Future[U] = { + def ?[U](replyTo: ActorRef[U] => T)(implicit timeout: Timeout, @unused scheduler: Scheduler): Future[U] = { ask(replyTo)(timeout, scheduler) } @@ -90,19 +90,19 @@ object AskPattern { * // to understand the type of the wildcard * }}} */ - def ask[U](replyTo: ActorRef[U] ⇒ T)(implicit timeout: Timeout, @unused scheduler: Scheduler): Future[U] = { + def ask[U](replyTo: ActorRef[U] => T)(implicit timeout: Timeout, @unused scheduler: Scheduler): Future[U] = { // We do not currently use the implicit scheduler, but want to require it // because it might be needed when we move to a 'native' typed runtime, see #24219 ref match { - case a: InternalRecipientRef[_] ⇒ askUntyped(a, timeout, replyTo) - case a ⇒ throw new IllegalStateException( + case a: InternalRecipientRef[_] => askUntyped(a, timeout, replyTo) + case a => throw new IllegalStateException( "Only expect references to be RecipientRef, ActorRefAdapter or ActorSystemAdapter until " + "native system is implemented: " + a.getClass) } } } - private val onTimeout: String ⇒ Throwable = msg ⇒ new TimeoutException(msg) + private val onTimeout: String => Throwable = msg => new TimeoutException(msg) private final class PromiseRef[U](target: InternalRecipientRef[_], timeout: Timeout) { @@ -128,7 +128,7 @@ object AskPattern { val promiseRef: PromiseActorRef = _promiseRef } - private def askUntyped[T, U](target: InternalRecipientRef[T], timeout: Timeout, f: ActorRef[U] ⇒ T): Future[U] = { + private def askUntyped[T, U](target: InternalRecipientRef[T], timeout: Timeout, f: ActorRef[U] => T): Future[U] = { val p = new PromiseRef[U](target, timeout) val m = f(p.ref) if (p.promiseRef ne null) p.promiseRef.messageClassName = m.getClass.getName diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/Behaviors.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/Behaviors.scala index 21128f801c..dc0e928130 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/Behaviors.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/Behaviors.scala @@ -27,7 +27,7 @@ object Behaviors { * case it will be started immediately after it is returned, i.e. next message will be * processed by the started behavior. */ - def setup[T](factory: ActorContext[T] ⇒ Behavior[T]): Behavior[T] = + def setup[T](factory: ActorContext[T] => Behavior[T]): Behavior[T] = Behavior.DeferredBehavior(factory) /** @@ -90,7 +90,7 @@ object Behaviors { * that can potentially be different from this one. State is maintained by returning * a new behavior that holds the new immutable state. */ - def receive[T](onMessage: (ActorContext[T], T) ⇒ Behavior[T]): Receive[T] = + def receive[T](onMessage: (ActorContext[T], T) => Behavior[T]): Receive[T] = new ReceiveImpl(onMessage) /** @@ -109,7 +109,7 @@ object Behaviors { * that can potentially be different from this one. State is maintained by returning * a new behavior that holds the new immutable state. */ - def receiveMessage[T](onMessage: T ⇒ Behavior[T]): Receive[T] = + def receiveMessage[T](onMessage: T => Behavior[T]): Receive[T] = new ReceiveMessageImpl(onMessage) /** @@ -118,8 +118,8 @@ object Behaviors { * Behaviors can also be composed with [[Behavior#orElse]]. */ def receivePartial[T](onMessage: PartialFunction[(ActorContext[T], T), Behavior[T]]): Receive[T] = - Behaviors.receive[T] { (ctx, t) ⇒ - onMessage.applyOrElse((ctx, t), (_: (ActorContext[T], T)) ⇒ Behaviors.unhandled[T]) + Behaviors.receive[T] { (ctx, t) => + onMessage.applyOrElse((ctx, t), (_: (ActorContext[T], T)) => Behaviors.unhandled[T]) } /** @@ -128,15 +128,15 @@ object Behaviors { * Behaviors can also be composed with [[Behavior#orElse]]. */ def receiveMessagePartial[T](onMessage: PartialFunction[T, Behavior[T]]): Receive[T] = - Behaviors.receive[T] { (_, t) ⇒ - onMessage.applyOrElse(t, (_: T) ⇒ Behaviors.unhandled[T]) + Behaviors.receive[T] { (_, t) => + onMessage.applyOrElse(t, (_: T) => Behaviors.unhandled[T]) } /** * Construct an actor `Behavior` that can react to lifecycle signals only. */ def receiveSignal[T](handler: PartialFunction[(ActorContext[T], Signal), Behavior[T]]): Behavior[T] = - receive[T]((_, _) ⇒ same).receiveSignal(handler) + receive[T]((_, _) => same).receiveSignal(handler) /** * Intercept messages and signals for a `behavior` by first passing them to a [[akka.actor.typed.BehaviorInterceptor]] @@ -216,7 +216,7 @@ object Behaviors { * is restarted or stopped. * @see [[TimerScheduler]] */ - def withTimers[T](factory: TimerScheduler[T] ⇒ Behavior[T]): Behavior[T] = + def withTimers[T](factory: TimerScheduler[T] => Behavior[T]): Behavior[T] = TimerSchedulerImpl.withTimers(factory) /** @@ -229,7 +229,7 @@ object Behaviors { * * See also [[akka.actor.typed.Logger.withMdc]] */ - def withMdc[T](mdcForMessage: T ⇒ Map[String, Any])(behavior: Behavior[T]): Behavior[T] = + def withMdc[T](mdcForMessage: T => Map[String, Any])(behavior: Behavior[T]): Behavior[T] = withMdc[T](Map.empty[String, Any], mdcForMessage)(behavior) /** @@ -242,7 +242,7 @@ object Behaviors { * See also [[akka.actor.typed.Logger.withMdc]] */ def withMdc[T](staticMdc: Map[String, Any])(behavior: Behavior[T]): Behavior[T] = - withMdc[T](staticMdc, (_: T) ⇒ Map.empty[String, Any])(behavior) + withMdc[T](staticMdc, (_: T) => Map.empty[String, Any])(behavior) /** * Combination of static and per message MDC (Mapped Diagnostic Context). @@ -261,7 +261,7 @@ object Behaviors { * * See also [[akka.actor.typed.Logger.withMdc]] */ - def withMdc[T](staticMdc: Map[String, Any], mdcForMessage: T ⇒ Map[String, Any])(behavior: Behavior[T]): Behavior[T] = + def withMdc[T](staticMdc: Map[String, Any], mdcForMessage: T => Map[String, Any])(behavior: Behavior[T]): Behavior[T] = WithMdcBehaviorInterceptor[T](staticMdc, mdcForMessage, behavior) /** @@ -274,14 +274,14 @@ object Behaviors { } @InternalApi - private[akka] final class ReceiveImpl[T](onMessage: (ActorContext[T], T) ⇒ Behavior[T]) + private[akka] final class ReceiveImpl[T](onMessage: (ActorContext[T], T) => Behavior[T]) extends BehaviorImpl.ReceiveBehavior[T](onMessage) with Receive[T] { override def receiveSignal(onSignal: PartialFunction[(ActorContext[T], Signal), Behavior[T]]): Behavior[T] = new BehaviorImpl.ReceiveBehavior(onMessage, onSignal) } @InternalApi - private[akka] final class ReceiveMessageImpl[T](onMessage: T ⇒ Behavior[T]) + private[akka] final class ReceiveMessageImpl[T](onMessage: T => Behavior[T]) extends BehaviorImpl.ReceiveMessageBehavior[T](onMessage) with Receive[T] { override def receiveSignal(onSignal: PartialFunction[(ActorContext[T], Signal), Behavior[T]]): Behavior[T] = diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/StashBuffer.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/StashBuffer.scala index 7768f87c48..e0d80659da 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/StashBuffer.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/StashBuffer.scala @@ -78,7 +78,7 @@ object StashBuffer { * * @param f the function to apply to each element */ - def foreach(f: T ⇒ Unit): Unit + def foreach(f: T => Unit): Unit /** * Process all stashed messages with the `behavior` and the returned @@ -115,7 +115,7 @@ object StashBuffer { * messages will not be processed by this call and have to be unstashed * in another call. */ - def unstash(ctx: ActorContext[T], behavior: Behavior[T], numberOfMessages: Int, wrap: T ⇒ T): Behavior[T] + def unstash(ctx: ActorContext[T], behavior: Behavior[T], numberOfMessages: Int, wrap: T => T): Behavior[T] } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/adapter/PropsAdapter.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/adapter/PropsAdapter.scala index a5d8aec57c..dde13cf318 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/adapter/PropsAdapter.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/adapter/PropsAdapter.scala @@ -17,6 +17,6 @@ import akka.actor.typed.Props * example of that. */ object PropsAdapter { - def apply[T](behavior: ⇒ Behavior[T], deploy: Props = Props.empty): akka.actor.Props = - akka.actor.typed.internal.adapter.PropsAdapter(() ⇒ behavior, deploy) + def apply[T](behavior: => Behavior[T], deploy: Props = Props.empty): akka.actor.Props = + akka.actor.typed.internal.adapter.PropsAdapter(() => behavior, deploy) } diff --git a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/adapter/package.scala b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/adapter/package.scala index ecd0df4df2..ced5740ebe 100644 --- a/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/adapter/package.scala +++ b/akka-actor-typed/src/main/scala/akka/actor/typed/scaladsl/adapter/package.scala @@ -6,7 +6,7 @@ package akka.actor.typed package scaladsl import akka.actor.ExtendedActorSystem -import akka.actor.typed.internal.adapter.{ PropsAdapter ⇒ _, _ } +import akka.actor.typed.internal.adapter.{ PropsAdapter => _, _ } import akka.annotation.InternalApi /** diff --git a/akka-actor/src/main/scala-2.11/akka/compat/Future.scala b/akka-actor/src/main/scala-2.11/akka/compat/Future.scala index 7502e0d19c..2ff28a041d 100644 --- a/akka-actor/src/main/scala-2.11/akka/compat/Future.scala +++ b/akka-actor/src/main/scala-2.11/akka/compat/Future.scala @@ -5,7 +5,7 @@ package akka.compat import akka.annotation.InternalApi -import scala.concurrent.{ ExecutionContext, Future ⇒ SFuture } +import scala.concurrent.{ ExecutionContext, Future => SFuture } /** * INTERNAL API @@ -16,12 +16,12 @@ import scala.concurrent.{ ExecutionContext, Future ⇒ SFuture } * Remove these classes as soon as support for Scala 2.11 is dropped! */ @InternalApi private[akka] object Future { - def fold[T, R](futures: TraversableOnce[SFuture[T]])(zero: R)(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = + def fold[T, R](futures: TraversableOnce[SFuture[T]])(zero: R)(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = SFuture.fold[T, R](futures)(zero)(op)(executor) - def reduce[T, R >: T](futures: TraversableOnce[SFuture[T]])(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = + def reduce[T, R >: T](futures: TraversableOnce[SFuture[T]])(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = SFuture.reduce[T, R](futures)(op)(executor) - def find[T](futures: TraversableOnce[SFuture[T]])(p: T ⇒ Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = + def find[T](futures: TraversableOnce[SFuture[T]])(p: T => Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = SFuture.find[T](futures)(p)(executor) } diff --git a/akka-actor/src/main/scala-2.11/akka/util/ByteIterator.scala b/akka-actor/src/main/scala-2.11/akka/util/ByteIterator.scala index 3f76464180..a0120fdc0c 100644 --- a/akka-actor/src/main/scala-2.11/akka/util/ByteIterator.scala +++ b/akka-actor/src/main/scala-2.11/akka/util/ByteIterator.scala @@ -26,7 +26,7 @@ object ByteIterator { } class ByteArrayIterator private (private var array: Array[Byte], private var from: Int, private var until: Int) extends ByteIterator { - iterator ⇒ + iterator => @inline final def len: Int = until - from @@ -44,11 +44,11 @@ object ByteIterator { final override def length: Int = { val l = len; clear(); l } final override def ++(that: TraversableOnce[Byte]): ByteIterator = that match { - case that: ByteIterator ⇒ + case that: ByteIterator => if (that.isEmpty) this else if (this.isEmpty) that else that match { - case that: ByteArrayIterator ⇒ + case that: ByteArrayIterator => if ((this.array eq that.array) && (this.until == that.from)) { this.until = that.until that.clear() @@ -58,9 +58,9 @@ object ByteIterator { this.clear() result } - case that: MultiByteArrayIterator ⇒ this ++: that + case that: MultiByteArrayIterator => this ++: that } - case _ ⇒ super.++(that) + case _ => super.++(that) } final override def clone: ByteArrayIterator = new ByteArrayIterator(array, from, until) @@ -75,14 +75,14 @@ object ByteIterator { this } - final override def takeWhile(p: Byte ⇒ Boolean): this.type = { + final override def takeWhile(p: Byte => Boolean): this.type = { val prev = from dropWhile(p) until = from; from = prev this } - final override def dropWhile(p: Byte ⇒ Boolean): this.type = { + final override def dropWhile(p: Byte => Boolean): this.type = { var stop = false while (!stop && hasNext) { if (p(array(from))) { from = from + 1 } else { stop = true } @@ -212,22 +212,22 @@ object ByteIterator { } final override def ++(that: TraversableOnce[Byte]): ByteIterator = that match { - case that: ByteIterator ⇒ + case that: ByteIterator => if (that.isEmpty) this else if (this.isEmpty) that else { that match { - case that: ByteArrayIterator ⇒ + case that: ByteArrayIterator => iterators = this.iterators :+ that that.clear() this - case that: MultiByteArrayIterator ⇒ + case that: MultiByteArrayIterator => iterators = this.iterators ++ that.iterators that.clear() this } } - case _ ⇒ super.++(that) + case _ => super.++(that) } final override def clone: MultiByteArrayIterator = { @@ -262,7 +262,7 @@ object ByteIterator { drop(rest) } else this - final override def takeWhile(p: Byte ⇒ Boolean): this.type = { + final override def takeWhile(p: Byte => Boolean): this.type = { var stop = false var builder = new ListBuffer[ByteArrayIterator] while (!stop && !iterators.isEmpty) { @@ -276,7 +276,7 @@ object ByteIterator { normalize() } - @tailrec final override def dropWhile(p: Byte ⇒ Boolean): this.type = + @tailrec final override def dropWhile(p: Byte => Boolean): this.type = if (!isEmpty) { current.dropWhile(p) val dropMore = current.isEmpty @@ -299,7 +299,7 @@ object ByteIterator { normalize() } - override def foreach[@specialized U](f: Byte ⇒ U): Unit = { + override def foreach[@specialized U](f: Byte => U): Unit = { iterators foreach { _ foreach f } clear() } @@ -313,7 +313,7 @@ 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 = + @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) EmptyImmutableSeq.iterator.next() val nDone = if (current.len >= elemSize) { @@ -424,22 +424,22 @@ abstract class ByteIterator extends BufferedIterator[Byte] { // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in // the parent class. - override def takeWhile(p: Byte ⇒ Boolean): this.type = throw new UnsupportedOperationException("Method takeWhile is not implemented in ByteIterator") + override def takeWhile(p: Byte => Boolean): this.type = throw new UnsupportedOperationException("Method takeWhile is not implemented in ByteIterator") // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in // the parent class. - override def dropWhile(p: Byte ⇒ Boolean): this.type = throw new UnsupportedOperationException("Method dropWhile is not implemented in ByteIterator") + override def dropWhile(p: Byte => Boolean): this.type = throw new UnsupportedOperationException("Method dropWhile is not implemented in ByteIterator") - override def span(p: Byte ⇒ Boolean): (ByteIterator, ByteIterator) = { + override def span(p: Byte => Boolean): (ByteIterator, ByteIterator) = { val that = clone this.takeWhile(p) that.drop(this.len) (this, that) } - override def indexWhere(p: Byte ⇒ Boolean): Int = indexWhere(p, 0) - def indexWhere(p: Byte ⇒ Boolean, from: Int): Int = { + override def indexWhere(p: Byte => Boolean): Int = indexWhere(p, 0) + def indexWhere(p: Byte => Boolean, from: Int): Int = { var index = from var found = false while (!found && hasNext) if (p(next())) { found = true } else { index += 1 } @@ -456,12 +456,12 @@ abstract class ByteIterator extends BufferedIterator[Byte] { override def toSeq: ByteString = toByteString - override def foreach[@specialized U](f: Byte ⇒ U): Unit = + override def foreach[@specialized U](f: Byte => U): Unit = while (hasNext) f(next()) - override def foldLeft[@specialized B](z: B)(op: (B, Byte) ⇒ B): B = { + override def foldLeft[@specialized B](z: B)(op: (B, Byte) => B): B = { var acc = z - foreach { byte ⇒ acc = op(acc, byte) } + foreach { byte => acc = op(acc, byte) } acc } @@ -536,11 +536,11 @@ abstract class ByteIterator extends BufferedIterator[Byte] { def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = { if (byteOrder == ByteOrder.BIG_ENDIAN) { var x = 0L - (1 to n) foreach (_ ⇒ x = (x << 8) | (next() & 0xff)) + (1 to n) foreach (_ => x = (x << 8) | (next() & 0xff)) x } else if (byteOrder == ByteOrder.LITTLE_ENDIAN) { var x = 0L - (0 until n) foreach (i ⇒ x |= (next() & 0xff) << 8 * i) + (0 until n) foreach (i => x |= (next() & 0xff) << 8 * i) x } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) } diff --git a/akka-actor/src/main/scala-2.12/akka/compat/Future.scala b/akka-actor/src/main/scala-2.12/akka/compat/Future.scala index db901bbc70..cba195a5cb 100644 --- a/akka-actor/src/main/scala-2.12/akka/compat/Future.scala +++ b/akka-actor/src/main/scala-2.12/akka/compat/Future.scala @@ -5,7 +5,7 @@ package akka.compat import akka.annotation.InternalApi -import scala.concurrent.{ ExecutionContext, Future ⇒ SFuture } +import scala.concurrent.{ ExecutionContext, Future => SFuture } import scala.collection.immutable import akka.util.ccompat._ @@ -18,22 +18,22 @@ import akka.util.ccompat._ * Remove these classes as soon as support for Scala 2.11 is dropped! */ @InternalApi private[akka] object Future { - def fold[T, R](futures: IterableOnce[SFuture[T]])(zero: R)(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = + def fold[T, R](futures: IterableOnce[SFuture[T]])(zero: R)(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = SFuture.fold[T, R](futures)(zero)(op)(executor) - def fold[T, R](futures: immutable.Iterable[SFuture[T]])(zero: R)(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = + def fold[T, R](futures: immutable.Iterable[SFuture[T]])(zero: R)(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = SFuture.foldLeft[T, R](futures)(zero)(op)(executor) - def reduce[T, R >: T](futures: IterableOnce[SFuture[T]])(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = + def reduce[T, R >: T](futures: IterableOnce[SFuture[T]])(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = SFuture.reduce[T, R](futures)(op)(executor) - def reduce[T, R >: T](futures: immutable.Iterable[SFuture[T]])(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = + def reduce[T, R >: T](futures: immutable.Iterable[SFuture[T]])(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = SFuture.reduceLeft[T, R](futures)(op)(executor) - def find[T](futures: IterableOnce[SFuture[T]])(p: T ⇒ Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = + def find[T](futures: IterableOnce[SFuture[T]])(p: T => Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = SFuture.find[T](futures)(p)(executor) - def find[T](futures: immutable.Iterable[SFuture[T]])(p: T ⇒ Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = + def find[T](futures: immutable.Iterable[SFuture[T]])(p: T => Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = SFuture.find[T](futures)(p)(executor) } diff --git a/akka-actor/src/main/scala-2.12/akka/util/ByteIterator.scala b/akka-actor/src/main/scala-2.12/akka/util/ByteIterator.scala index 6c92b05a46..8041f8ff4d 100644 --- a/akka-actor/src/main/scala-2.12/akka/util/ByteIterator.scala +++ b/akka-actor/src/main/scala-2.12/akka/util/ByteIterator.scala @@ -26,7 +26,7 @@ object ByteIterator { } class ByteArrayIterator private (private var array: Array[Byte], private var from: Int, private var until: Int) extends ByteIterator { - iterator ⇒ + iterator => @inline final def len: Int = until - from @@ -44,11 +44,11 @@ object ByteIterator { final override def length: Int = { val l = len; clear(); l } final override def ++(that: TraversableOnce[Byte]): ByteIterator = that match { - case that: ByteIterator ⇒ + case that: ByteIterator => if (that.isEmpty) this else if (this.isEmpty) that else that match { - case that: ByteArrayIterator ⇒ + case that: ByteArrayIterator => if ((this.array eq that.array) && (this.until == that.from)) { this.until = that.until that.clear() @@ -58,9 +58,9 @@ object ByteIterator { this.clear() result } - case that: MultiByteArrayIterator ⇒ this ++: that + case that: MultiByteArrayIterator => this ++: that } - case _ ⇒ super.++(that) + case _ => super.++(that) } final override def clone: ByteArrayIterator = new ByteArrayIterator(array, from, until) @@ -75,14 +75,14 @@ object ByteIterator { this } - final override def takeWhile(p: Byte ⇒ Boolean): this.type = { + final override def takeWhile(p: Byte => Boolean): this.type = { val prev = from dropWhile(p) until = from; from = prev this } - final override def dropWhile(p: Byte ⇒ Boolean): this.type = { + final override def dropWhile(p: Byte => Boolean): this.type = { var stop = false while (!stop && hasNext) { if (p(array(from))) { from = from + 1 } else { stop = true } @@ -212,22 +212,22 @@ object ByteIterator { } final override def ++(that: TraversableOnce[Byte]): ByteIterator = that match { - case that: ByteIterator ⇒ + case that: ByteIterator => if (that.isEmpty) this else if (this.isEmpty) that else { that match { - case that: ByteArrayIterator ⇒ + case that: ByteArrayIterator => iterators = this.iterators :+ that that.clear() this - case that: MultiByteArrayIterator ⇒ + case that: MultiByteArrayIterator => iterators = this.iterators ++ that.iterators that.clear() this } } - case _ ⇒ super.++(that) + case _ => super.++(that) } final override def clone: MultiByteArrayIterator = { @@ -262,7 +262,7 @@ object ByteIterator { drop(rest) } else this - final override def takeWhile(p: Byte ⇒ Boolean): this.type = { + final override def takeWhile(p: Byte => Boolean): this.type = { var stop = false var builder = new ListBuffer[ByteArrayIterator] while (!stop && !iterators.isEmpty) { @@ -276,7 +276,7 @@ object ByteIterator { normalize() } - @tailrec final override def dropWhile(p: Byte ⇒ Boolean): this.type = + @tailrec final override def dropWhile(p: Byte => Boolean): this.type = if (!isEmpty) { current.dropWhile(p) val dropMore = current.isEmpty @@ -299,7 +299,7 @@ object ByteIterator { normalize() } - override def foreach[@specialized U](f: Byte ⇒ U): Unit = { + override def foreach[@specialized U](f: Byte => U): Unit = { iterators foreach { _ foreach f } clear() } @@ -313,7 +313,7 @@ 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 = + @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) EmptyImmutableSeq.iterator.next() val nDone = if (current.len >= elemSize) { @@ -424,22 +424,22 @@ abstract class ByteIterator extends BufferedIterator[Byte] { // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in // the parent class. - override def takeWhile(p: Byte ⇒ Boolean): this.type = throw new UnsupportedOperationException("Method takeWhile is not implemented in ByteIterator") + override def takeWhile(p: Byte => Boolean): this.type = throw new UnsupportedOperationException("Method takeWhile is not implemented in ByteIterator") // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in // the parent class. - override def dropWhile(p: Byte ⇒ Boolean): this.type = throw new UnsupportedOperationException("Method dropWhile is not implemented in ByteIterator") + override def dropWhile(p: Byte => Boolean): this.type = throw new UnsupportedOperationException("Method dropWhile is not implemented in ByteIterator") - override def span(p: Byte ⇒ Boolean): (ByteIterator, ByteIterator) = { + override def span(p: Byte => Boolean): (ByteIterator, ByteIterator) = { val that = clone this.takeWhile(p) that.drop(this.len) (this, that) } - override def indexWhere(p: Byte ⇒ Boolean): Int = indexWhere(p, 0) - override def indexWhere(p: Byte ⇒ Boolean, from: Int): Int = { + override def indexWhere(p: Byte => Boolean): Int = indexWhere(p, 0) + override def indexWhere(p: Byte => Boolean, from: Int): Int = { var index = from var found = false while (!found && hasNext) if (p(next())) { found = true } else { index += 1 } @@ -456,12 +456,12 @@ abstract class ByteIterator extends BufferedIterator[Byte] { override def toSeq: ByteString = toByteString - override def foreach[@specialized U](f: Byte ⇒ U): Unit = + override def foreach[@specialized U](f: Byte => U): Unit = while (hasNext) f(next()) - override def foldLeft[@specialized B](z: B)(op: (B, Byte) ⇒ B): B = { + override def foldLeft[@specialized B](z: B)(op: (B, Byte) => B): B = { var acc = z - foreach { byte ⇒ acc = op(acc, byte) } + foreach { byte => acc = op(acc, byte) } acc } @@ -536,11 +536,11 @@ abstract class ByteIterator extends BufferedIterator[Byte] { def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = { if (byteOrder == ByteOrder.BIG_ENDIAN) { var x = 0L - (1 to n) foreach (_ ⇒ x = (x << 8) | (next() & 0xff)) + (1 to n) foreach (_ => x = (x << 8) | (next() & 0xff)) x } else if (byteOrder == ByteOrder.LITTLE_ENDIAN) { var x = 0L - (0 until n) foreach (i ⇒ x |= (next() & 0xff) << 8 * i) + (0 until n) foreach (i => x |= (next() & 0xff) << 8 * i) x } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) } diff --git a/akka-actor/src/main/scala-2.13+/akka/util/ByteIterator.scala b/akka-actor/src/main/scala-2.13+/akka/util/ByteIterator.scala index 72c50637aa..450a098aac 100644 --- a/akka-actor/src/main/scala-2.13+/akka/util/ByteIterator.scala +++ b/akka-actor/src/main/scala-2.13+/akka/util/ByteIterator.scala @@ -27,7 +27,7 @@ object ByteIterator { } class ByteArrayIterator private (private var array: Array[Byte], private var from: Int, private var until: Int) extends ByteIterator { - iterator ⇒ + iterator => @inline final def len: Int = until - from @@ -45,11 +45,11 @@ object ByteIterator { final override def size: Int = { val l = len; clear(); l } final override def ++(that: IterableOnce[Byte]): ByteIterator = that match { - case that: ByteIterator ⇒ + case that: ByteIterator => if (that.isEmpty) this else if (this.isEmpty) that else that match { - case that: ByteArrayIterator ⇒ + case that: ByteArrayIterator => if ((this.array eq that.array) && (this.until == that.from)) { this.until = that.until that.clear() @@ -59,9 +59,9 @@ object ByteIterator { this.clear() result } - case that: MultiByteArrayIterator ⇒ this ++: that + case that: MultiByteArrayIterator => this ++: that } - case _ ⇒ super.++(that) + case _ => super.++(that) } final override def clone: ByteArrayIterator = new ByteArrayIterator(array, from, until) @@ -76,14 +76,14 @@ object ByteIterator { this } - final override def takeWhile(p: Byte ⇒ Boolean): this.type = { + final override def takeWhile(p: Byte => Boolean): this.type = { val prev = from dropWhile(p) until = from; from = prev this } - final override def dropWhile(p: Byte ⇒ Boolean): this.type = { + final override def dropWhile(p: Byte => Boolean): this.type = { var stop = false while (!stop && hasNext) { if (p(array(from))) { from = from + 1 } else { stop = true } @@ -215,22 +215,22 @@ object ByteIterator { } final override def ++(that: IterableOnce[Byte]): ByteIterator = that match { - case that: ByteIterator ⇒ + case that: ByteIterator => if (that.isEmpty) this else if (this.isEmpty) that else { that match { - case that: ByteArrayIterator ⇒ + case that: ByteArrayIterator => iterators = this.iterators :+ that that.clear() this - case that: MultiByteArrayIterator ⇒ + case that: MultiByteArrayIterator => iterators = this.iterators ++ that.iterators that.clear() this } } - case _ ⇒ super.++(that) + case _ => super.++(that) } final override def clone: MultiByteArrayIterator = { @@ -265,7 +265,7 @@ object ByteIterator { drop(rest) } else this - final override def takeWhile(p: Byte ⇒ Boolean): this.type = { + final override def takeWhile(p: Byte => Boolean): this.type = { var stop = false var builder = new ListBuffer[ByteArrayIterator] while (!stop && !iterators.isEmpty) { @@ -279,7 +279,7 @@ object ByteIterator { normalize() } - @tailrec final override def dropWhile(p: Byte ⇒ Boolean): this.type = + @tailrec final override def dropWhile(p: Byte => Boolean): this.type = if (!isEmpty) { current.dropWhile(p) val dropMore = current.isEmpty @@ -303,7 +303,7 @@ object ByteIterator { len - rest } - override def foreach[@specialized U](f: Byte ⇒ U): Unit = { + override def foreach[@specialized U](f: Byte => U): Unit = { iterators foreach { _ foreach f } clear() } @@ -317,7 +317,7 @@ 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 = + @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) EmptyImmutableSeq.iterator.next() val nDone = if (current.len >= elemSize) { @@ -427,21 +427,21 @@ abstract class ByteIterator extends BufferedIterator[Byte] { // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in // the parent class. - override def takeWhile(p: Byte ⇒ Boolean): this.type = throw new UnsupportedOperationException("Method takeWhile is not implemented in ByteIterator") + override def takeWhile(p: Byte => Boolean): this.type = throw new UnsupportedOperationException("Method takeWhile is not implemented in ByteIterator") // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in // the parent class. - override def dropWhile(p: Byte ⇒ Boolean): this.type = throw new UnsupportedOperationException("Method dropWhile is not implemented in ByteIterator") + override def dropWhile(p: Byte => Boolean): this.type = throw new UnsupportedOperationException("Method dropWhile is not implemented in ByteIterator") - override def span(p: Byte ⇒ Boolean): (ByteIterator, ByteIterator) = { + override def span(p: Byte => Boolean): (ByteIterator, ByteIterator) = { val that = clone this.takeWhile(p) that.drop(this.len) (this, that) } - override def indexWhere(p: Byte ⇒ Boolean, from: Int = 0): Int = { + override def indexWhere(p: Byte => Boolean, from: Int = 0): Int = { var index = from var found = false while (!found && hasNext) if (p(next())) { found = true } else { index += 1 } @@ -458,12 +458,12 @@ abstract class ByteIterator extends BufferedIterator[Byte] { override def toSeq: ByteString = toByteString - override def foreach[@specialized U](f: Byte ⇒ U): Unit = + override def foreach[@specialized U](f: Byte => U): Unit = while (hasNext) f(next()) - override def foldLeft[@specialized B](z: B)(op: (B, Byte) ⇒ B): B = { + override def foldLeft[@specialized B](z: B)(op: (B, Byte) => B): B = { var acc = z - foreach { byte ⇒ acc = op(acc, byte) } + foreach { byte => acc = op(acc, byte) } acc } @@ -538,11 +538,11 @@ abstract class ByteIterator extends BufferedIterator[Byte] { def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = { if (byteOrder == ByteOrder.BIG_ENDIAN) { var x = 0L - (1 to n) foreach (_ ⇒ x = (x << 8) | (next() & 0xff)) + (1 to n) foreach (_ => x = (x << 8) | (next() & 0xff)) x } else if (byteOrder == ByteOrder.LITTLE_ENDIAN) { var x = 0L - (0 until n) foreach (i ⇒ x |= (next() & 0xff) << 8 * i) + (0 until n) foreach (i => x |= (next() & 0xff) << 8 * i) x } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) } diff --git a/akka-actor/src/main/scala-2.13+/akka/util/ByteString.scala b/akka-actor/src/main/scala-2.13+/akka/util/ByteString.scala index 77b1432e0c..12b323163f 100644 --- a/akka-actor/src/main/scala-2.13+/akka/util/ByteString.scala +++ b/akka-actor/src/main/scala-2.13+/akka/util/ByteString.scala @@ -8,7 +8,7 @@ import akka.compat._ import java.io.{ ObjectInputStream, ObjectOutputStream } import java.nio.{ ByteBuffer, ByteOrder } -import java.lang.{ Iterable ⇒ JIterable } +import java.lang.{ Iterable => JIterable } import scala.annotation.{ tailrec, varargs } import scala.collection.mutable.{ Builder, WrappedArray } @@ -361,12 +361,12 @@ object ByteString { if (that.isEmpty) this else if (this.isEmpty) that else that match { - case b: ByteString1C ⇒ ByteStrings(this, b.toByteString1) - case b: ByteString1 ⇒ + case b: ByteString1C => ByteStrings(this, b.toByteString1) + case b: ByteString1 => if ((bytes eq b.bytes) && (startIndex + length == b.startIndex)) new ByteString1(bytes, startIndex, length + b.length) else ByteStrings(this, b) - case bs: ByteStrings ⇒ ByteStrings(this, bs) + case bs: ByteStrings => ByteStrings(this, bs) } } @@ -393,31 +393,31 @@ object ByteString { def apply(bytestrings: Vector[ByteString1], length: Int): ByteString = new ByteStrings(bytestrings, length) def apply(b1: ByteString1, b2: ByteString1): ByteString = compare(b1, b2) match { - case 3 ⇒ new ByteStrings(Vector(b1, b2), b1.length + b2.length) - case 2 ⇒ b2 - case 1 ⇒ b1 - case 0 ⇒ ByteString.empty + case 3 => new ByteStrings(Vector(b1, b2), b1.length + b2.length) + case 2 => b2 + case 1 => b1 + case 0 => ByteString.empty } def apply(b: ByteString1, bs: ByteStrings): ByteString = compare(b, bs) match { - case 3 ⇒ new ByteStrings(b +: bs.bytestrings, bs.length + b.length) - case 2 ⇒ bs - case 1 ⇒ b - case 0 ⇒ ByteString.empty + case 3 => new ByteStrings(b +: bs.bytestrings, bs.length + b.length) + case 2 => bs + case 1 => b + case 0 => ByteString.empty } def apply(bs: ByteStrings, b: ByteString1): ByteString = compare(bs, b) match { - case 3 ⇒ new ByteStrings(bs.bytestrings :+ b, bs.length + b.length) - case 2 ⇒ b - case 1 ⇒ bs - case 0 ⇒ ByteString.empty + case 3 => new ByteStrings(bs.bytestrings :+ b, bs.length + b.length) + case 2 => b + case 1 => bs + case 0 => ByteString.empty } def apply(bs1: ByteStrings, bs2: ByteStrings): ByteString = compare(bs1, bs2) match { - case 3 ⇒ new ByteStrings(bs1.bytestrings ++ bs2.bytestrings, bs1.length + bs2.length) - case 2 ⇒ bs2 - case 1 ⇒ bs1 - case 0 ⇒ ByteString.empty + case 3 => new ByteStrings(bs1.bytestrings ++ bs2.bytestrings, bs1.length + bs2.length) + case 2 => bs2 + case 1 => bs1 + case 0 => ByteString.empty } // 0: both empty, 1: 2nd empty, 2: 1st empty, 3: neither empty @@ -436,7 +436,7 @@ object ByteString { builder.sizeHint(nByteStrings) - for (_ ← 0 until nByteStrings) { + for (_ <- 0 until nByteStrings) { val bs = ByteString1.readFromInputStream(is) builder += bs length += bs.length @@ -473,9 +473,9 @@ object ByteString { if (that.isEmpty) this else if (this.isEmpty) that else that match { - case b: ByteString1C ⇒ ByteStrings(this, b.toByteString1) - case b: ByteString1 ⇒ ByteStrings(this, b) - case bs: ByteStrings ⇒ ByteStrings(this, bs) + case b: ByteString1C => ByteStrings(this, b.toByteString1) + case b: ByteString1 => ByteStrings(this, b) + case bs: ByteStrings => ByteStrings(this, bs) } } @@ -496,7 +496,7 @@ object ByteString { else { val ar = new Array[Byte](length) var pos = 0 - bytestrings foreach { b ⇒ + bytestrings foreach { b => b.copyToArray(ar, pos, b.length) pos += b.length } @@ -640,8 +640,8 @@ object ByteString { private[akka] object Companion { private val companionMap = Seq(ByteString1, ByteString1C, ByteStrings). - map(x ⇒ x.SerializationIdentity → x).toMap. - withDefault(x ⇒ throw new IllegalArgumentException("Invalid serialization id " + x)) + map(x => x.SerializationIdentity -> x).toMap. + withDefault(x => throw new IllegalArgumentException("Invalid serialization id " + x)) def apply(from: Byte): Companion = companionMap(from) } @@ -706,14 +706,14 @@ sealed abstract class ByteString // *must* be overridden by derived classes. override def dropRight(n: Int): ByteString = throw new UnsupportedOperationException("Method dropRight is not implemented in ByteString") - override def takeWhile(p: Byte ⇒ Boolean): ByteString = iterator.takeWhile(p).toByteString - override def dropWhile(p: Byte ⇒ Boolean): ByteString = iterator.dropWhile(p).toByteString - override def span(p: Byte ⇒ Boolean): (ByteString, ByteString) = + override def takeWhile(p: Byte => Boolean): ByteString = iterator.takeWhile(p).toByteString + override def dropWhile(p: Byte => Boolean): ByteString = iterator.dropWhile(p).toByteString + override def span(p: Byte => Boolean): (ByteString, ByteString) = { val (a, b) = iterator.span(p); (a.toByteString, b.toByteString) } override def splitAt(n: Int): (ByteString, ByteString) = (take(n), drop(n)) - override def indexWhere(p: Byte ⇒ Boolean): Int = iterator.indexWhere(p) + override def indexWhere(p: Byte => Boolean): Int = iterator.indexWhere(p) // optimized in subclasses override def indexOf[B >: Byte](elem: B): Int = indexOf(elem, 0) @@ -747,7 +747,7 @@ sealed abstract class ByteString // override def copyToArray[B >: Byte](xs: Array[B], start: Int, len: Int): Unit = // iterator.copyToArray(xs, start, len) - override def foreach[@specialized U](f: Byte ⇒ U): Unit = iterator foreach f + override def foreach[@specialized U](f: Byte => U): Unit = iterator foreach f private[akka] def writeToOutputStream(os: ObjectOutputStream): Unit @@ -834,9 +834,9 @@ sealed abstract class ByteString /** * map method that will automatically cast Int back into Byte. */ - final def mapI(f: Byte ⇒ Int): ByteString = map(f andThen (_.toByte)) + final def mapI(f: Byte => Int): ByteString = map(f andThen (_.toByte)) - def map[A](f: Byte ⇒ Byte): ByteString = fromSpecific(super.map(f)) + def map[A](f: Byte => Byte): ByteString = fromSpecific(super.map(f)) } object CompactByteString { @@ -869,7 +869,7 @@ object CompactByteString { */ def apply[T](bytes: T*)(implicit num: Integral[T]): CompactByteString = { if (bytes.isEmpty) empty - else ByteString.ByteString1C(bytes.iterator.map(x ⇒ num.toInt(x).toByte).to(Array)) + else ByteString.ByteString1C(bytes.iterator.map(x => num.toInt(x).toByte).to(Array)) } /** @@ -936,7 +936,7 @@ sealed abstract class CompactByteString extends ByteString with Serializable { * The created ByteString is not automatically compacted. */ final class ByteStringBuilder extends Builder[Byte, ByteString] { - builder ⇒ + builder => import ByteString.{ ByteString1C, ByteString1, ByteStrings } private var _length: Int = 0 @@ -945,7 +945,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { private var _tempLength: Int = 0 private var _tempCapacity: Int = 0 - protected def fillArray(len: Int)(fill: (Array[Byte], Int) ⇒ Unit): this.type = { + protected def fillArray(len: Int)(fill: (Array[Byte], Int) => Unit): this.type = { ensureTempSize(_tempLength + len) fill(_temp, _tempLength) _tempLength += len @@ -953,9 +953,9 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { this } - @inline protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer ⇒ Unit): this.type = { + @inline protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer => Unit): this.type = { fillArray(len) { - case (array, start) ⇒ + case (array, start) => val buffer = ByteBuffer.wrap(array, start, len) buffer.order(byteOrder) fill(buffer) @@ -1004,34 +1004,34 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { override def addAll(xs: IterableOnce[Byte]): this.type = { xs match { - case _ if xs.isEmpty ⇒ + case _ if xs.isEmpty => // do nothing - case b: ByteString1C ⇒ + case b: ByteString1C => clearTemp() _builder += b.toByteString1 _length += b.length - case b: ByteString1 ⇒ + case b: ByteString1 => clearTemp() _builder += b _length += b.length - case bs: ByteStrings ⇒ + case bs: ByteStrings => clearTemp() _builder ++= bs.bytestrings _length += bs.length - case xs: WrappedArray.ofByte ⇒ + case xs: WrappedArray.ofByte => putByteArrayUnsafe(xs.array.clone) - case seq: collection.IndexedSeq[Byte] if shouldResizeTempFor(seq.length) ⇒ + case seq: collection.IndexedSeq[Byte] if shouldResizeTempFor(seq.length) => val copied = Array.from(xs) clearTemp() _builder += ByteString.ByteString1(copied) _length += seq.length - case seq: collection.IndexedSeq[Byte] ⇒ + case seq: collection.IndexedSeq[Byte] => ensureTempSize(_tempLength + seq.size) seq.copyToArray(_temp, _tempLength) _tempLength += seq.length _length += seq.length - case _ ⇒ + case _ => super.++=(xs) } this @@ -1071,7 +1071,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a single Int to this builder. */ def putInt(x: Int)(implicit byteOrder: ByteOrder): this.type = { - fillArray(4) { (target, offset) ⇒ + fillArray(4) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { target(offset + 0) = (x >>> 24).toByte target(offset + 1) = (x >>> 16).toByte @@ -1091,7 +1091,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a single Long to this builder. */ def putLong(x: Long)(implicit byteOrder: ByteOrder): this.type = { - fillArray(8) { (target, offset) ⇒ + fillArray(8) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { target(offset + 0) = (x >>> 56).toByte target(offset + 1) = (x >>> 48).toByte @@ -1119,12 +1119,12 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add the `n` least significant bytes of the given Long to this builder. */ def putLongPart(x: Long, n: Int)(implicit byteOrder: ByteOrder): this.type = { - fillArray(n) { (target, offset) ⇒ + fillArray(n) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { val start = n * 8 - 8 - (0 until n) foreach { i ⇒ target(offset + i) = (x >>> start - 8 * i).toByte } + (0 until n) foreach { i => target(offset + i) = (x >>> start - 8 * i).toByte } } else if (byteOrder == ByteOrder.LITTLE_ENDIAN) { - (0 until n) foreach { i ⇒ target(offset + i) = (x >>> 8 * i).toByte } + (0 until n) foreach { i => target(offset + i) = (x >>> 8 * i).toByte } } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) } } @@ -1151,7 +1151,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Bytes from an array to this builder. */ def putBytes(array: Array[Byte], start: Int, len: Int): this.type = - fillArray(len) { case (target, targetOffset) ⇒ Array.copy(array, start, target, targetOffset, len) } + fillArray(len) { case (target, targetOffset) => Array.copy(array, start, target, targetOffset, len) } /** * Add a number of Shorts from an array to this builder. diff --git a/akka-actor/src/main/scala-2.13-/akka/util/ByteString.scala b/akka-actor/src/main/scala-2.13-/akka/util/ByteString.scala index 2807eec092..da834ac606 100644 --- a/akka-actor/src/main/scala-2.13-/akka/util/ByteString.scala +++ b/akka-actor/src/main/scala-2.13-/akka/util/ByteString.scala @@ -6,7 +6,7 @@ package akka.util import java.io.{ ObjectInputStream, ObjectOutputStream } import java.nio.{ ByteBuffer, ByteOrder } -import java.lang.{ Iterable ⇒ JIterable } +import java.lang.{ Iterable => JIterable } import scala.annotation.{ tailrec, varargs } import scala.collection.IndexedSeqOptimized @@ -355,12 +355,12 @@ object ByteString { if (that.isEmpty) this else if (this.isEmpty) that else that match { - case b: ByteString1C ⇒ ByteStrings(this, b.toByteString1) - case b: ByteString1 ⇒ + case b: ByteString1C => ByteStrings(this, b.toByteString1) + case b: ByteString1 => if ((bytes eq b.bytes) && (startIndex + length == b.startIndex)) new ByteString1(bytes, startIndex, length + b.length) else ByteStrings(this, b) - case bs: ByteStrings ⇒ ByteStrings(this, bs) + case bs: ByteStrings => ByteStrings(this, bs) } } @@ -387,31 +387,31 @@ object ByteString { def apply(bytestrings: Vector[ByteString1], length: Int): ByteString = new ByteStrings(bytestrings, length) def apply(b1: ByteString1, b2: ByteString1): ByteString = compare(b1, b2) match { - case 3 ⇒ new ByteStrings(Vector(b1, b2), b1.length + b2.length) - case 2 ⇒ b2 - case 1 ⇒ b1 - case 0 ⇒ ByteString.empty + case 3 => new ByteStrings(Vector(b1, b2), b1.length + b2.length) + case 2 => b2 + case 1 => b1 + case 0 => ByteString.empty } def apply(b: ByteString1, bs: ByteStrings): ByteString = compare(b, bs) match { - case 3 ⇒ new ByteStrings(b +: bs.bytestrings, bs.length + b.length) - case 2 ⇒ bs - case 1 ⇒ b - case 0 ⇒ ByteString.empty + case 3 => new ByteStrings(b +: bs.bytestrings, bs.length + b.length) + case 2 => bs + case 1 => b + case 0 => ByteString.empty } def apply(bs: ByteStrings, b: ByteString1): ByteString = compare(bs, b) match { - case 3 ⇒ new ByteStrings(bs.bytestrings :+ b, bs.length + b.length) - case 2 ⇒ b - case 1 ⇒ bs - case 0 ⇒ ByteString.empty + case 3 => new ByteStrings(bs.bytestrings :+ b, bs.length + b.length) + case 2 => b + case 1 => bs + case 0 => ByteString.empty } def apply(bs1: ByteStrings, bs2: ByteStrings): ByteString = compare(bs1, bs2) match { - case 3 ⇒ new ByteStrings(bs1.bytestrings ++ bs2.bytestrings, bs1.length + bs2.length) - case 2 ⇒ bs2 - case 1 ⇒ bs1 - case 0 ⇒ ByteString.empty + case 3 => new ByteStrings(bs1.bytestrings ++ bs2.bytestrings, bs1.length + bs2.length) + case 2 => bs2 + case 1 => bs1 + case 0 => ByteString.empty } // 0: both empty, 1: 2nd empty, 2: 1st empty, 3: neither empty @@ -430,7 +430,7 @@ object ByteString { builder.sizeHint(nByteStrings) - for (_ ← 0 until nByteStrings) { + for (_ <- 0 until nByteStrings) { val bs = ByteString1.readFromInputStream(is) builder += bs length += bs.length @@ -467,9 +467,9 @@ object ByteString { if (that.isEmpty) this else if (this.isEmpty) that else that match { - case b: ByteString1C ⇒ ByteStrings(this, b.toByteString1) - case b: ByteString1 ⇒ ByteStrings(this, b) - case bs: ByteStrings ⇒ ByteStrings(this, bs) + case b: ByteString1C => ByteStrings(this, b.toByteString1) + case b: ByteString1 => ByteStrings(this, b) + case bs: ByteStrings => ByteStrings(this, bs) } } @@ -490,7 +490,7 @@ object ByteString { else { val ar = new Array[Byte](length) var pos = 0 - bytestrings foreach { b ⇒ + bytestrings foreach { b => b.copyToArray(ar, pos, b.length) pos += b.length } @@ -634,8 +634,8 @@ object ByteString { private[akka] object Companion { private val companionMap = Seq(ByteString1, ByteString1C, ByteStrings). - map(x ⇒ x.SerializationIdentity → x).toMap. - withDefault(x ⇒ throw new IllegalArgumentException("Invalid serialization id " + x)) + map(x => x.SerializationIdentity -> x).toMap. + withDefault(x => throw new IllegalArgumentException("Invalid serialization id " + x)) def apply(from: Byte): Companion = companionMap(from) } @@ -689,14 +689,14 @@ sealed abstract class ByteString extends IndexedSeq[Byte] with IndexedSeqOptimiz // *must* be overridden by derived classes. override def dropRight(n: Int): ByteString = throw new UnsupportedOperationException("Method dropRight is not implemented in ByteString") - override def takeWhile(p: Byte ⇒ Boolean): ByteString = iterator.takeWhile(p).toByteString - override def dropWhile(p: Byte ⇒ Boolean): ByteString = iterator.dropWhile(p).toByteString - override def span(p: Byte ⇒ Boolean): (ByteString, ByteString) = + override def takeWhile(p: Byte => Boolean): ByteString = iterator.takeWhile(p).toByteString + override def dropWhile(p: Byte => Boolean): ByteString = iterator.dropWhile(p).toByteString + override def span(p: Byte => Boolean): (ByteString, ByteString) = { val (a, b) = iterator.span(p); (a.toByteString, b.toByteString) } override def splitAt(n: Int): (ByteString, ByteString) = (take(n), drop(n)) - override def indexWhere(p: Byte ⇒ Boolean): Int = iterator.indexWhere(p) + override def indexWhere(p: Byte => Boolean): Int = iterator.indexWhere(p) // optimized in subclasses override def indexOf[B >: Byte](elem: B): Int = indexOf(elem, 0) @@ -730,7 +730,7 @@ sealed abstract class ByteString extends IndexedSeq[Byte] with IndexedSeqOptimiz override def copyToArray[B >: Byte](xs: Array[B], start: Int, len: Int): Unit = iterator.copyToArray(xs, start, len) - override def foreach[@specialized U](f: Byte ⇒ U): Unit = iterator foreach f + override def foreach[@specialized U](f: Byte => U): Unit = iterator foreach f private[akka] def writeToOutputStream(os: ObjectOutputStream): Unit @@ -818,7 +818,7 @@ sealed abstract class ByteString extends IndexedSeq[Byte] with IndexedSeqOptimiz /** * map method that will automatically cast Int back into Byte. */ - final def mapI(f: Byte ⇒ Int): ByteString = map(f andThen (_.toByte)) + final def mapI(f: Byte => Int): ByteString = map(f andThen (_.toByte)) } object CompactByteString { @@ -845,7 +845,7 @@ object CompactByteString { */ def apply[T](bytes: T*)(implicit num: Integral[T]): CompactByteString = { if (bytes.isEmpty) empty - else ByteString.ByteString1C(bytes.map(x ⇒ num.toInt(x).toByte)(collection.breakOut)) + else ByteString.ByteString1C(bytes.map(x => num.toInt(x).toByte)(collection.breakOut)) } /** @@ -912,7 +912,7 @@ sealed abstract class CompactByteString extends ByteString with Serializable { * The created ByteString is not automatically compacted. */ final class ByteStringBuilder extends Builder[Byte, ByteString] { - builder ⇒ + builder => import ByteString.{ ByteString1C, ByteString1, ByteStrings } private var _length: Int = 0 @@ -921,7 +921,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { private var _tempLength: Int = 0 private var _tempCapacity: Int = 0 - protected def fillArray(len: Int)(fill: (Array[Byte], Int) ⇒ Unit): this.type = { + protected def fillArray(len: Int)(fill: (Array[Byte], Int) => Unit): this.type = { ensureTempSize(_tempLength + len) fill(_temp, _tempLength) _tempLength += len @@ -929,9 +929,9 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { this } - @inline protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer ⇒ Unit): this.type = { + @inline protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer => Unit): this.type = { fillArray(len) { - case (array, start) ⇒ + case (array, start) => val buffer = ByteBuffer.wrap(array, start, len) buffer.order(byteOrder) fill(buffer) @@ -980,35 +980,35 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { override def ++=(xs: TraversableOnce[Byte]): this.type = { xs match { - case b: ByteString if b.isEmpty ⇒ + case b: ByteString if b.isEmpty => // do nothing - case b: ByteString1C ⇒ + case b: ByteString1C => clearTemp() _builder += b.toByteString1 _length += b.length - case b: ByteString1 ⇒ + case b: ByteString1 => clearTemp() _builder += b _length += b.length - case bs: ByteStrings ⇒ + case bs: ByteStrings => clearTemp() _builder ++= bs.bytestrings _length += bs.length - case xs: WrappedArray.ofByte ⇒ + case xs: WrappedArray.ofByte => putByteArrayUnsafe(xs.array.clone) - case seq: collection.IndexedSeq[Byte] if shouldResizeTempFor(seq.length) ⇒ + case seq: collection.IndexedSeq[Byte] if shouldResizeTempFor(seq.length) => val copied = new Array[Byte](seq.length) seq.copyToArray(copied) clearTemp() _builder += ByteString.ByteString1(copied) _length += seq.length - case seq: collection.IndexedSeq[_] ⇒ + case seq: collection.IndexedSeq[_] => ensureTempSize(_tempLength + xs.size) xs.copyToArray(_temp, _tempLength) _tempLength += seq.length _length += seq.length - case _ ⇒ + case _ => super.++=(xs) } this @@ -1048,7 +1048,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a single Int to this builder. */ def putInt(x: Int)(implicit byteOrder: ByteOrder): this.type = { - fillArray(4) { (target, offset) ⇒ + fillArray(4) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { target(offset + 0) = (x >>> 24).toByte target(offset + 1) = (x >>> 16).toByte @@ -1068,7 +1068,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a single Long to this builder. */ def putLong(x: Long)(implicit byteOrder: ByteOrder): this.type = { - fillArray(8) { (target, offset) ⇒ + fillArray(8) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { target(offset + 0) = (x >>> 56).toByte target(offset + 1) = (x >>> 48).toByte @@ -1096,12 +1096,12 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add the `n` least significant bytes of the given Long to this builder. */ def putLongPart(x: Long, n: Int)(implicit byteOrder: ByteOrder): this.type = { - fillArray(n) { (target, offset) ⇒ + fillArray(n) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { val start = n * 8 - 8 - (0 until n) foreach { i ⇒ target(offset + i) = (x >>> start - 8 * i).toByte } + (0 until n) foreach { i => target(offset + i) = (x >>> start - 8 * i).toByte } } else if (byteOrder == ByteOrder.LITTLE_ENDIAN) { - (0 until n) foreach { i ⇒ target(offset + i) = (x >>> 8 * i).toByte } + (0 until n) foreach { i => target(offset + i) = (x >>> 8 * i).toByte } } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) } } @@ -1128,7 +1128,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Bytes from an array to this builder. */ def putBytes(array: Array[Byte], start: Int, len: Int): this.type = - fillArray(len) { case (target, targetOffset) ⇒ Array.copy(array, start, target, targetOffset, len) } + fillArray(len) { case (target, targetOffset) => Array.copy(array, start, target, targetOffset, len) } /** * Add a number of Shorts from an array to this builder. diff --git a/akka-actor/src/main/scala-2.13-/akka/util/ccompat/CompatImpl.scala b/akka-actor/src/main/scala-2.13-/akka/util/ccompat/CompatImpl.scala index 3e835a561d..a6a169414b 100644 --- a/akka-actor/src/main/scala-2.13-/akka/util/ccompat/CompatImpl.scala +++ b/akka-actor/src/main/scala-2.13-/akka/util/ccompat/CompatImpl.scala @@ -15,7 +15,7 @@ import scala.collection.mutable.Builder * not promising binary compatibility yet at the time of writing. */ private[ccompat] object CompatImpl { - def simpleCBF[A, C](f: ⇒ Builder[A, C]): CanBuildFrom[Any, A, C] = new CanBuildFrom[Any, A, C] { + def simpleCBF[A, C](f: => Builder[A, C]): CanBuildFrom[Any, A, C] = new CanBuildFrom[Any, A, C] { def apply(from: Any): Builder[A, C] = apply() def apply(): Builder[A, C] = f } diff --git a/akka-actor/src/main/scala-2.13-/akka/util/ccompat/package.scala b/akka-actor/src/main/scala-2.13-/akka/util/ccompat/package.scala index 0858a286f8..e6670db036 100644 --- a/akka-actor/src/main/scala-2.13-/akka/util/ccompat/package.scala +++ b/akka-actor/src/main/scala-2.13-/akka/util/ccompat/package.scala @@ -8,10 +8,10 @@ import scala.language.implicitConversions import scala.language.higherKinds import scala.collection.GenTraversable -import scala.{ collection ⇒ c } +import scala.{ collection => c } import scala.collection.generic.{ CanBuildFrom, GenericCompanion, Sorted, SortedSetFactory } -import scala.collection.{ immutable ⇒ i } -import scala.collection.{ mutable ⇒ m } +import scala.collection.{ immutable => i } +import scala.collection.{ mutable => m } /** * INTERNAL API diff --git a/akka-actor/src/main/scala-2.13/akka/compat/Future.scala b/akka-actor/src/main/scala-2.13/akka/compat/Future.scala index 9c021ead40..047be51fa1 100644 --- a/akka-actor/src/main/scala-2.13/akka/compat/Future.scala +++ b/akka-actor/src/main/scala-2.13/akka/compat/Future.scala @@ -5,7 +5,7 @@ package akka.compat import akka.annotation.InternalApi -import scala.concurrent.{ ExecutionContext, Future ⇒ SFuture } +import scala.concurrent.{ ExecutionContext, Future => SFuture } import scala.collection.immutable /** @@ -17,27 +17,27 @@ import scala.collection.immutable * Remove these classes as soon as support for Scala 2.11 is dropped! */ @InternalApi private[akka] object Future { - def fold[T, R](futures: IterableOnce[SFuture[T]])(zero: R)(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = { + def fold[T, R](futures: IterableOnce[SFuture[T]])(zero: R)(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = { // This will have performance implications since the elements are copied to a Vector SFuture.foldLeft[T, R](futures.to(immutable.Iterable))(zero)(op)(executor) } - def fold[T, R](futures: immutable.Iterable[SFuture[T]])(zero: R)(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = + def fold[T, R](futures: immutable.Iterable[SFuture[T]])(zero: R)(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = SFuture.foldLeft[T, R](futures)(zero)(op)(executor) - def reduce[T, R >: T](futures: IterableOnce[SFuture[T]])(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = { + def reduce[T, R >: T](futures: IterableOnce[SFuture[T]])(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = { // This will have performance implications since the elements are copied to a Vector SFuture.reduceLeft[T, R](futures.to(immutable.Iterable))(op)(executor) } - def reduce[T, R >: T](futures: immutable.Iterable[SFuture[T]])(op: (R, T) ⇒ R)(implicit executor: ExecutionContext): SFuture[R] = + def reduce[T, R >: T](futures: immutable.Iterable[SFuture[T]])(op: (R, T) => R)(implicit executor: ExecutionContext): SFuture[R] = SFuture.reduceLeft[T, R](futures)(op)(executor) - def find[T](futures: IterableOnce[SFuture[T]])(p: T ⇒ Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = { + def find[T](futures: IterableOnce[SFuture[T]])(p: T => Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = { // This will have performance implications since the elements are copied to a Vector SFuture.find[T](futures.to(immutable.Iterable))(p)(executor) } - def find[T](futures: immutable.Iterable[SFuture[T]])(p: T ⇒ Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = + def find[T](futures: immutable.Iterable[SFuture[T]])(p: T => Boolean)(implicit executor: ExecutionContext): SFuture[Option[T]] = SFuture.find[T](futures)(p)(executor) } diff --git a/akka-actor/src/main/scala/akka/AkkaException.scala b/akka-actor/src/main/scala/akka/AkkaException.scala index 4646da76d0..b7c2a4c894 100644 --- a/akka-actor/src/main/scala/akka/AkkaException.scala +++ b/akka-actor/src/main/scala/akka/AkkaException.scala @@ -16,11 +16,11 @@ class AkkaException(message: String, cause: Throwable) extends RuntimeException( * Mix in this trait to suppress the StackTrace for the instance of the exception but not the cause, * scala.util.control.NoStackTrace suppresses all the StackTraces. */ -trait OnlyCauseStackTrace { self: Throwable ⇒ +trait OnlyCauseStackTrace { self: Throwable => override def fillInStackTrace(): Throwable = { setStackTrace(getCause match { - case null ⇒ Array.empty - case some ⇒ some.getStackTrace + case null => Array.empty + case some => some.getStackTrace }) this } diff --git a/akka-actor/src/main/scala/akka/AkkaVersion.scala b/akka-actor/src/main/scala/akka/AkkaVersion.scala index b296203e4c..a7ee6b9208 100644 --- a/akka-actor/src/main/scala/akka/AkkaVersion.scala +++ b/akka-actor/src/main/scala/akka/AkkaVersion.scala @@ -30,9 +30,9 @@ object AkkaVersion { private[akka] def require(libraryName: String, requiredVersion: String, currentVersion: String): Unit = { val VersionPattern = """(\d+)\.(\d+)\.(\d+)(-(?:M|RC)\d+)?""".r currentVersion match { - case VersionPattern(currentMajorStr, currentMinorStr, currentPatchStr, mOrRc) ⇒ + case VersionPattern(currentMajorStr, currentMinorStr, currentPatchStr, mOrRc) => requiredVersion match { - case requiredVersion @ VersionPattern(requiredMajorStr, requiredMinorStr, requiredPatchStr, _) ⇒ + case requiredVersion @ VersionPattern(requiredMajorStr, requiredMinorStr, requiredPatchStr, _) => // a M or RC is basically in-between versions, so offset val currentPatch = if (mOrRc ne null) currentPatchStr.toInt - 1 @@ -41,10 +41,10 @@ object AkkaVersion { requiredMinorStr.toInt > currentMinorStr.toInt || (requiredMinorStr == currentMinorStr && requiredPatchStr.toInt > currentPatch)) throw new UnsupportedAkkaVersion(s"Current version of Akka is [$currentVersion], but $libraryName requires version [$requiredVersion]") - case _ ⇒ throw new IllegalArgumentException(s"Required version string is invalid: [$requiredVersion]") + case _ => throw new IllegalArgumentException(s"Required version string is invalid: [$requiredVersion]") } - case _ ⇒ // SNAPSHOT or unknown - you're on your own + case _ => // SNAPSHOT or unknown - you're on your own } } diff --git a/akka-actor/src/main/scala/akka/Main.scala b/akka-actor/src/main/scala/akka/Main.scala index 4969f37c55..c8aefbc817 100644 --- a/akka-actor/src/main/scala/akka/Main.scala +++ b/akka-actor/src/main/scala/akka/Main.scala @@ -33,7 +33,7 @@ object Main { val app = system.actorOf(Props(appClass), "app") system.actorOf(Props(classOf[Terminator], app), "app-terminator") } catch { - case NonFatal(e) ⇒ system.terminate(); throw e + case NonFatal(e) => system.terminate(); throw e } } } @@ -41,7 +41,7 @@ object Main { class Terminator(app: ActorRef) extends Actor with ActorLogging { context watch app def receive = { - case Terminated(_) ⇒ + case Terminated(_) => log.info("application supervisor has terminated, shutting down") context.system.terminate() } diff --git a/akka-actor/src/main/scala/akka/actor/AbstractActor.scala b/akka-actor/src/main/scala/akka/actor/AbstractActor.scala index 4783d9fd65..5fbe627ace 100644 --- a/akka-actor/src/main/scala/akka/actor/AbstractActor.scala +++ b/akka-actor/src/main/scala/akka/actor/AbstractActor.scala @@ -333,7 +333,7 @@ abstract class UntypedAbstractActor extends AbstractActor { final override def createReceive(): AbstractActor.Receive = throw new UnsupportedOperationException("createReceive should not be used by UntypedAbstractActor") - override def receive: PartialFunction[Any, Unit] = { case msg ⇒ onReceive(msg) } + override def receive: PartialFunction[Any, Unit] = { case msg => onReceive(msg) } /** * To be implemented by concrete UntypedAbstractActor, this defines the behavior of the diff --git a/akka-actor/src/main/scala/akka/actor/AbstractFSM.scala b/akka-actor/src/main/scala/akka/actor/AbstractFSM.scala index 45dcd21626..ce24be80ec 100644 --- a/akka-actor/src/main/scala/akka/actor/AbstractFSM.scala +++ b/akka-actor/src/main/scala/akka/actor/AbstractFSM.scala @@ -30,7 +30,7 @@ object AbstractFSM { * */ abstract class AbstractFSM[S, D] extends FSM[S, D] { - import java.util.{ List ⇒ JList } + import java.util.{ List => JList } import FSM._ import akka.japi.pf.FI._ diff --git a/akka-actor/src/main/scala/akka/actor/AbstractProps.scala b/akka-actor/src/main/scala/akka/actor/AbstractProps.scala index b1b3bb5924..5218337c2c 100644 --- a/akka-actor/src/main/scala/akka/actor/AbstractProps.scala +++ b/akka-actor/src/main/scala/akka/actor/AbstractProps.scala @@ -46,14 +46,14 @@ private[akka] trait AbstractProps { val ac = classOf[Actor] val coc = classOf[Creator[_]] val actorClass = Reflect.findMarker(cc, coc) match { - case t: ParameterizedType ⇒ + case t: ParameterizedType => t.getActualTypeArguments.head match { - case c: Class[_] ⇒ c // since T <: Actor - case v: TypeVariable[_] ⇒ - v.getBounds collectFirst { case c: Class[_] if ac.isAssignableFrom(c) && c != ac ⇒ c } getOrElse ac - case x ⇒ throw new IllegalArgumentException(s"unsupported type found in Creator argument [$x]") + case c: Class[_] => c // since T <: Actor + case v: TypeVariable[_] => + v.getBounds collectFirst { case c: Class[_] if ac.isAssignableFrom(c) && c != ac => c } getOrElse ac + case x => throw new IllegalArgumentException(s"unsupported type found in Creator argument [$x]") } - case c: Class[_] if (c == coc) ⇒ + case c: Class[_] if (c == coc) => throw new IllegalArgumentException("erased Creator types (e.g. lambdas) are unsupported, use Props.create(actorClass, creator) instead") } create(classOf[CreatorConsumer], actorClass, creator) diff --git a/akka-actor/src/main/scala/akka/actor/Actor.scala b/akka-actor/src/main/scala/akka/actor/Actor.scala index 63322fc9cc..51698cb68e 100644 --- a/akka-actor/src/main/scala/akka/actor/Actor.scala +++ b/akka-actor/src/main/scala/akka/actor/Actor.scala @@ -39,6 +39,7 @@ abstract class PoisonPill extends AutoReceivedMessage with PossiblyHarmful with */ @SerialVersionUID(1L) case object PoisonPill extends PoisonPill { + /** * Java API: get the singleton instance */ @@ -46,12 +47,14 @@ case object PoisonPill extends PoisonPill { } abstract class Kill extends AutoReceivedMessage with PossiblyHarmful + /** * A message all Actors will understand, that when processed will make the Actor throw an ActorKilledException, * which will trigger supervision. */ @SerialVersionUID(1L) case object Kill extends Kill { + /** * Java API: get the singleton instance */ @@ -76,8 +79,10 @@ final case class Identify(messageId: Any) extends AutoReceivedMessage with NotIn @SerialVersionUID(1L) final case class ActorIdentity(correlationId: Any, ref: Option[ActorRef]) { if (ref.isDefined && ref.get == null) { - throw new IllegalArgumentException("ActorIdentity created with ref = Some(null) is not allowed, " + - "this could happen when serializing with Scala 2.12 and deserializing with Scala 2.11 which is not supported.") + throw new IllegalArgumentException( + "ActorIdentity created with ref = Some(null) is not allowed, " + + "this could happen when serializing with Scala 2.12 and deserializing with Scala 2.11 which is not supported." + ) } /** @@ -112,11 +117,12 @@ final case class ActorIdentity(correlationId: Any, ref: Option[ActorRef]) { * that the remote node hosting the watched actor was detected as unreachable */ @SerialVersionUID(1L) -final case class Terminated private[akka] (@BeanProperty actor: ActorRef)( - @BeanProperty val existenceConfirmed: Boolean, - @BeanProperty val addressTerminated: Boolean) - extends AutoReceivedMessage with PossiblyHarmful with DeadLetterSuppression - with NoSerializationVerificationNeeded // local message, the remote one is DeathWatchNotification +final case class Terminated private[akka] (@BeanProperty actor: ActorRef)(@BeanProperty val existenceConfirmed: Boolean, + @BeanProperty val addressTerminated: Boolean) + extends AutoReceivedMessage + with PossiblyHarmful + with DeadLetterSuppression + with NoSerializationVerificationNeeded // local message, the remote one is DeathWatchNotification /** * INTERNAL API @@ -129,7 +135,9 @@ final case class Terminated private[akka] (@BeanProperty actor: ActorRef)( */ @SerialVersionUID(1L) private[akka] final case class AddressTerminated(address: Address) - extends AutoReceivedMessage with PossiblyHarmful with DeadLetterSuppression + extends AutoReceivedMessage + with PossiblyHarmful + with DeadLetterSuppression abstract class ReceiveTimeout extends PossiblyHarmful @@ -139,6 +147,7 @@ abstract class ReceiveTimeout extends PossiblyHarmful */ @SerialVersionUID(1L) case object ReceiveTimeout extends ReceiveTimeout { + /** * Java API: get the singleton instance */ @@ -183,7 +192,7 @@ final case class InvalidActorNameException(message: String) extends AkkaExceptio */ @SerialVersionUID(1L) class ActorInitializationException protected (actor: ActorRef, message: String, cause: Throwable) - extends AkkaException(ActorInitializationException.enrichedMessage(actor, message), cause) { + extends AkkaException(ActorInitializationException.enrichedMessage(actor, message), cause) { def getActor: ActorRef = actor } object ActorInitializationException { @@ -191,8 +200,10 @@ object ActorInitializationException { if (actor == null) message else s"${actor.path}: $message" private[akka] def apply(actor: ActorRef, message: String, cause: Throwable = null): ActorInitializationException = new ActorInitializationException(actor, message, cause) - private[akka] def apply(message: String): ActorInitializationException = new ActorInitializationException(null, message, null) - def unapply(ex: ActorInitializationException): Option[(ActorRef, String, Throwable)] = Some((ex.getActor, ex.getMessage, ex.getCause)) + private[akka] def apply(message: String): ActorInitializationException = + new ActorInitializationException(null, message, null) + def unapply(ex: ActorInitializationException): Option[(ActorRef, String, Throwable)] = + Some((ex.getActor, ex.getMessage, ex.getCause)) } /** @@ -207,13 +218,18 @@ object ActorInitializationException { * @param messageOption is the message which was optionally passed into preRestart() */ @SerialVersionUID(1L) -final case class PreRestartException private[akka] (actor: ActorRef, cause: Throwable, originalCause: Throwable, messageOption: Option[Any]) - extends ActorInitializationException( - actor, - "exception in preRestart(" + +final case class PreRestartException private[akka] (actor: ActorRef, + cause: Throwable, + originalCause: Throwable, + messageOption: Option[Any]) + extends ActorInitializationException( + actor, + "exception in preRestart(" + (if (originalCause == null) "null" else originalCause.getClass) + ", " + - (messageOption match { case Some(m: AnyRef) ⇒ m.getClass; case _ ⇒ "None" }) + - ")", cause) + (messageOption match { case Some(m: AnyRef) => m.getClass; case _ => "None" }) + + ")", + cause + ) /** * A PostRestartException is thrown when constructor or postRestart() method @@ -225,9 +241,11 @@ final case class PreRestartException private[akka] (actor: ActorRef, cause: Thro */ @SerialVersionUID(1L) final case class PostRestartException private[akka] (actor: ActorRef, cause: Throwable, originalCause: Throwable) - extends ActorInitializationException( - actor, - "exception post restart (" + (if (originalCause == null) "null" else originalCause.getClass) + ")", cause) + extends ActorInitializationException( + actor, + "exception post restart (" + (if (originalCause == null) "null" else originalCause.getClass) + ")", + cause + ) /** * This is an extractor for retrieving the original cause (i.e. the first @@ -239,8 +257,8 @@ final case class PostRestartException private[akka] (actor: ActorRef, cause: Thr object OriginalRestartException { def unapply(ex: PostRestartException): Option[Throwable] = { @tailrec def rec(ex: PostRestartException): Option[Throwable] = ex match { - case PostRestartException(_, _, e: PostRestartException) ⇒ rec(e) - case PostRestartException(_, _, e) ⇒ Some(e) + case PostRestartException(_, _, e: PostRestartException) => rec(e) + case PostRestartException(_, _, e) => Some(e) } rec(ex) } @@ -259,8 +277,8 @@ final case class InvalidMessageException private[akka] (message: String) extends */ @SerialVersionUID(1L) final case class DeathPactException private[akka] (dead: ActorRef) - extends AkkaException("Monitored actor [" + dead + "] terminated") - with NoStackTrace + extends AkkaException("Monitored actor [" + dead + "] terminated") + with NoStackTrace /** * When an InterruptedException is thrown inside an Actor, it is wrapped as an ActorInterruptedException as to @@ -273,8 +291,10 @@ class ActorInterruptedException private[akka] (cause: Throwable) extends AkkaExc * This message is published to the EventStream whenever an Actor receives a message it doesn't understand */ @SerialVersionUID(1L) -final case class UnhandledMessage(@BeanProperty message: Any, @BeanProperty sender: ActorRef, @BeanProperty recipient: ActorRef) - extends NoSerializationVerificationNeeded +final case class UnhandledMessage(@BeanProperty message: Any, + @BeanProperty sender: ActorRef, + @BeanProperty recipient: ActorRef) + extends NoSerializationVerificationNeeded /** * Classes for passing status back to the sender. @@ -309,7 +329,7 @@ object Status { * } * }}} */ -trait ActorLogging { this: Actor ⇒ +trait ActorLogging { this: Actor => private var _log: LoggingAdapter = _ def log: LoggingAdapter = { @@ -344,15 +364,17 @@ trait DiagnosticActorLogging extends Actor { val log = akka.event.Logging(this) def mdc(@unused currentMessage: Any): MDC = emptyMDC - override protected[akka] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = try { - log.mdc(mdc(msg)) - super.aroundReceive(receive, msg) - } finally { - log.clearMDC() - } + override protected[akka] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = + try { + log.mdc(mdc(msg)) + super.aroundReceive(receive, msg) + } finally { + log.clearMDC() + } } object Actor { + /** * Type alias representing a Receive-expression for Akka Actors. */ @@ -393,7 +415,7 @@ object Actor { /** * INTERNAL API */ - private final val notHandledFun = (_: Any) ⇒ NotHandled + private final val notHandledFun = (_: Any) => NotHandled } /** @@ -469,7 +491,8 @@ trait Actor { if ((contextStack.isEmpty) || (contextStack.head eq null)) throw ActorInitializationException( s"You cannot create an instance of [${getClass.getName}] explicitly using the constructor (new). " + - "You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.") + "You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation." + ) val c = contextStack.head ActorCell.contextStack.set(null :: contextStack) c @@ -593,7 +616,7 @@ trait Actor { @throws(classOf[Exception]) // when changing this you MUST also change ActorDocTest //#lifecycle-hooks def preRestart(@unused reason: Throwable, @unused message: Option[Any]): Unit = { - context.children foreach { child ⇒ + context.children foreach { child => context.unwatch(child) context.stop(child) } @@ -625,8 +648,8 @@ trait Actor { */ def unhandled(message: Any): Unit = { message match { - case Terminated(dead) ⇒ throw DeathPactException(dead) - case _ ⇒ context.system.eventStream.publish(UnhandledMessage(message, sender(), self)) + case Terminated(dead) => throw DeathPactException(dead) + case _ => context.system.eventStream.publish(UnhandledMessage(message, sender(), self)) } } } diff --git a/akka-actor/src/main/scala/akka/actor/ActorCell.scala b/akka-actor/src/main/scala/akka/actor/ActorCell.scala index 673cba7a59..d3766cddfa 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorCell.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorCell.scala @@ -509,9 +509,9 @@ private[akka] class ActorCell( def shouldStash(m: SystemMessage, state: Int): Boolean = (state: @switch) match { - case DefaultState ⇒ false - case SuspendedState ⇒ m.isInstanceOf[StashWhenFailed] - case SuspendedWaitForChildrenState ⇒ m.isInstanceOf[StashWhenWaitingForChildren] + case DefaultState => false + case SuspendedState => m.isInstanceOf[StashWhenFailed] + case SuspendedWaitForChildrenState => m.isInstanceOf[StashWhenWaitingForChildren] } @tailrec @@ -521,20 +521,20 @@ private[akka] class ActorCell( message.unlink() try { message match { - case message: SystemMessage if shouldStash(message, currentState) ⇒ stash(message) - case f: Failed ⇒ handleFailure(f) - case DeathWatchNotification(a, ec, at) ⇒ watchedActorTerminated(a, ec, at) - case Create(failure) ⇒ create(failure) - case Watch(watchee, watcher) ⇒ addWatcher(watchee, watcher) - case Unwatch(watchee, watcher) ⇒ remWatcher(watchee, watcher) - case Recreate(cause) ⇒ faultRecreate(cause) - case Suspend() ⇒ faultSuspend() - case Resume(inRespToFailure) ⇒ faultResume(inRespToFailure) - case Terminate() ⇒ terminate() - case Supervise(child, async) ⇒ supervise(child, async) - case NoMessage ⇒ // only here to suppress warning + case message: SystemMessage if shouldStash(message, currentState) => stash(message) + case f: Failed => handleFailure(f) + case DeathWatchNotification(a, ec, at) => watchedActorTerminated(a, ec, at) + case Create(failure) => create(failure) + case Watch(watchee, watcher) => addWatcher(watchee, watcher) + case Unwatch(watchee, watcher) => remWatcher(watchee, watcher) + case Recreate(cause) => faultRecreate(cause) + case Suspend() => faultSuspend() + case Resume(inRespToFailure) => faultResume(inRespToFailure) + case Terminate() => terminate() + case Supervise(child, async) => supervise(child, async) + case NoMessage => // only here to suppress warning } - } catch handleNonFatalOrInterruptedException { e ⇒ + } catch handleNonFatalOrInterruptedException { e => handleInvokeFailure(Nil, e) } val newState = calculateState @@ -557,11 +557,11 @@ private[akka] class ActorCell( if (influenceReceiveTimeout) cancelReceiveTimeout() messageHandle.message match { - case _: AutoReceivedMessage ⇒ autoReceiveMessage(messageHandle) - case msg ⇒ receiveMessage(msg) + case _: AutoReceivedMessage => autoReceiveMessage(messageHandle) + case msg => receiveMessage(msg) } currentMessage = null // reset current message after successful invocation - } catch handleNonFatalOrInterruptedException { e ⇒ + } catch handleNonFatalOrInterruptedException { e => handleInvokeFailure(Nil, e) } finally { // Schedule or reschedule receive timeout @@ -574,12 +574,12 @@ private[akka] class ActorCell( publish(Debug(self.path.toString, clazz(actor), "received AutoReceiveMessage " + msg)) msg.message match { - case t: Terminated ⇒ receivedTerminated(t) - case AddressTerminated(address) ⇒ addressTerminated(address) - case Kill ⇒ throw ActorKilledException("Kill") - case PoisonPill ⇒ self.stop() - case sel: ActorSelectionMessage ⇒ receiveSelection(sel) - case Identify(messageId) ⇒ sender() ! ActorIdentity(messageId, Some(self)) + case t: Terminated => receivedTerminated(t) + case AddressTerminated(address) => addressTerminated(address) + case Kill => throw ActorKilledException("Kill") + case PoisonPill => self.stop() + case sel: ActorSelectionMessage => receiveSelection(sel) + case Identify(messageId) => sender() ! ActorIdentity(messageId, Some(self)) } } @@ -596,9 +596,9 @@ private[akka] class ActorCell( */ final def sender(): ActorRef = currentMessage match { - case null ⇒ system.deadLetters - case msg if msg.sender ne null ⇒ msg.sender - case _ ⇒ system.deadLetters + case null => system.deadLetters + case msg if msg.sender ne null => msg.sender + case _ => system.deadLetters } def become(behavior: Actor.Receive, discardOld: Boolean = true): Unit = @@ -607,7 +607,7 @@ private[akka] class ActorCell( def become(behavior: Procedure[Any]): Unit = become(behavior, discardOld = true) def become(behavior: Procedure[Any], discardOld: Boolean): Unit = - become({ case msg ⇒ behavior.apply(msg) }: Actor.Receive, discardOld) + become({ case msg => behavior.apply(msg) }: Actor.Receive, discardOld) def unbecome(): Unit = { val original = behaviorStack @@ -657,20 +657,20 @@ private[akka] class ActorCell( checkReceiveTimeout() if (system.settings.DebugLifecycle) publish(Debug(self.path.toString, clazz(created), "started (" + created + ")")) } catch { - case e: InterruptedException ⇒ + case e: InterruptedException => clearOutActorIfNonNull() Thread.currentThread().interrupt() throw ActorInitializationException(self, "interruption during creation", e) - case NonFatal(e) ⇒ + case NonFatal(e) => clearOutActorIfNonNull() e match { - case i: InstantiationException ⇒ throw ActorInitializationException( + case i: InstantiationException => throw ActorInitializationException( self, """exception during creation, this problem is likely to occur because the class of the Actor you tried to create is either, a non-static inner class (in which case make it a static inner class or use Props(new ...) or Props( new Creator ... ) or is missing an appropriate, reachable no-args constructor. """, i.getCause) - case x ⇒ throw ActorInitializationException(self, "exception during creation", x) + case x => throw ActorInitializationException(self, "exception during creation", x) } } } @@ -679,17 +679,17 @@ private[akka] class ActorCell( if (!isTerminating) { // Supervise is the first thing we get from a new child, so store away the UID for later use in handleFailure() initChild(child) match { - case Some(_) ⇒ + case Some(_) => handleSupervise(child, async) if (system.settings.DebugLifecycle) publish(Debug(self.path.toString, clazz(actor), "now supervising " + child)) - case None ⇒ publish(Error(self.path.toString, clazz(actor), "received Supervise from unregistered child " + child + ", this will not end well")) + case None => publish(Error(self.path.toString, clazz(actor), "received Supervise from unregistered child " + child + ", this will not end well")) } } // future extension point protected def handleSupervise(child: ActorRef, async: Boolean): Unit = child match { - case r: RepointableActorRef if async ⇒ r.point(catchFailures = true) - case _ ⇒ + case r: RepointableActorRef if async => r.point(catchFailures = true) + case _ => } final protected def clearActorCellFields(cell: ActorCell): Unit = { @@ -712,7 +712,7 @@ private[akka] class ActorCell( } // logging is not the main purpose, and if it fails there’s nothing we can do - protected final def publish(e: LogEvent): Unit = try system.eventStream.publish(e) catch { case NonFatal(_) ⇒ } + protected final def publish(e: LogEvent): Unit = try system.eventStream.publish(e) catch { case NonFatal(_) => } protected final def clazz(o: AnyRef): Class[_] = if (o eq null) this.getClass else o.getClass } diff --git a/akka-actor/src/main/scala/akka/actor/ActorDSL.scala b/akka-actor/src/main/scala/akka/actor/ActorDSL.scala index 94c16dc0c5..25317f2730 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorDSL.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorDSL.scala @@ -90,8 +90,8 @@ object ActorDSL extends dsl.Inbox with dsl.Creators { private val boss = system.systemActorOf(Props( new Actor { def receive = { - case MkChild(props, name) ⇒ sender() ! context.actorOf(props, name) - case any ⇒ sender() ! any + case MkChild(props, name) => sender() ! context.actorOf(props, name) + case any => sender() ! any } }), "dsl").asInstanceOf[RepointableActorRef] diff --git a/akka-actor/src/main/scala/akka/actor/ActorPath.scala b/akka-actor/src/main/scala/akka/actor/ActorPath.scala index 0f8697b07d..daf65a6fc8 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorPath.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorPath.scala @@ -7,7 +7,7 @@ import scala.annotation.{ switch, tailrec } import scala.collection.immutable import akka.japi.Util.immutableSeq import java.net.MalformedURLException -import java.lang.{ StringBuilder ⇒ JStringBuilder } +import java.lang.{ StringBuilder => JStringBuilder } /** * Java API @@ -55,8 +55,8 @@ object ActorPath { * Parse string as actor path; throws java.net.MalformedURLException if unable to do so. */ def fromString(s: String): ActorPath = s match { - case ActorPathExtractor(address, elems) ⇒ RootActorPath(address) / elems - case _ ⇒ throw new MalformedURLException("cannot parse as ActorPath: " + s) + case ActorPathExtractor(address, elems) => RootActorPath(address) / elems + case _ => throw new MalformedURLException("cannot parse as ActorPath: " + s) } private final val ValidSymbols = """-_.*$+:@&=,!~';""" @@ -83,11 +83,11 @@ object ActorPath { def fullPathMsg = if (fullPath ne null) s""" (in path [$fullPath])""" else "" (findInvalidPathElementCharPosition(element): @switch) match { - case ValidPathCode ⇒ + case ValidPathCode => // valid - case EmptyPathCode ⇒ + case EmptyPathCode => throw InvalidActorNameException(s"Actor path element must not be empty $fullPathMsg") - case invalidAt ⇒ + case invalidAt => throw InvalidActorNameException( s"""Invalid actor path element [$element]$fullPathMsg, illegal character [${element(invalidAt)}] at position: $invalidAt. """ + """Actor paths MUST: """ + @@ -117,9 +117,9 @@ object ActorPath { def validate(pos: Int): Int = if (pos < len) s.charAt(pos) match { - case c if isValidChar(c) ⇒ validate(pos + 1) - case '%' if pos + 2 < len && isHexChar(s.charAt(pos + 1)) && isHexChar(s.charAt(pos + 2)) ⇒ validate(pos + 3) - case _ ⇒ pos + case c if isValidChar(c) => validate(pos + 1) + case '%' if pos + 2 < len && isHexChar(s.charAt(pos + 1)) && isHexChar(s.charAt(pos + 2)) => validate(pos + 3) + case _ => pos } else ValidPathCode @@ -177,7 +177,7 @@ sealed trait ActorPath extends Comparable[ActorPath] with Serializable { /** * Recursively create a descendant’s path by appending all child names. */ - def /(child: Iterable[String]): ActorPath = child.foldLeft(this)((path, elem) ⇒ if (elem.isEmpty) path else path / elem) + def /(child: Iterable[String]): ActorPath = child.foldLeft(this)((path, elem) => if (elem.isEmpty) path else path / elem) /** * Java API: Recursively create a descendant’s path by appending all child names. @@ -280,8 +280,8 @@ final case class RootActorPath(address: Address, name: String = "/") extends Act override def toSerializationFormatWithAddress(addr: Address): String = toStringWithAddress(addr) override def compareTo(other: ActorPath): Int = other match { - case r: RootActorPath ⇒ toString compareTo r.toString // FIXME make this cheaper by comparing address and name in isolation - case _: ChildActorPath ⇒ 1 + case r: RootActorPath => toString compareTo r.toString // FIXME make this cheaper by comparing address and name in isolation + case _: ChildActorPath => 1 } /** @@ -315,8 +315,8 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin override def elements: immutable.Iterable[String] = { @tailrec def rec(p: ActorPath, acc: List[String]): immutable.Iterable[String] = p match { - case _: RootActorPath ⇒ acc - case _ ⇒ rec(p.parent, p.name :: acc) + case _: RootActorPath => acc + case _ => rec(p.parent, p.name :: acc) } rec(this, Nil) } @@ -324,8 +324,8 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin override def root: RootActorPath = { @tailrec def rec(p: ActorPath): RootActorPath = p match { - case r: RootActorPath ⇒ r - case _ ⇒ rec(p.parent) + case r: RootActorPath => r + case _ => rec(p.parent) } rec(this) } @@ -351,8 +351,8 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin private def toStringLength: Int = toStringOffset + name.length private val toStringOffset: Int = parent match { - case r: RootActorPath ⇒ r.address.toString.length + r.name.length - case c: ChildActorPath ⇒ c.toStringLength + 1 + case r: RootActorPath => r.address.toString.length + r.name.length + case c: ChildActorPath => c.toStringLength + 1 } override def toStringWithAddress(addr: Address): String = { @@ -384,13 +384,13 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin * @param diff difference in offset for each child element, due to different address * @param rootString function to construct the root element string */ - private def buildToString(sb: JStringBuilder, length: Int, diff: Int, rootString: RootActorPath ⇒ String): JStringBuilder = { + private def buildToString(sb: JStringBuilder, length: Int, diff: Int, rootString: RootActorPath => String): JStringBuilder = { @tailrec def rec(p: ActorPath): JStringBuilder = p match { - case r: RootActorPath ⇒ + case r: RootActorPath => val rootStr = rootString(r) sb.replace(0, rootStr.length, rootStr) - case c: ChildActorPath ⇒ + case c: ChildActorPath => val start = c.toStringOffset + diff val end = start + c.name.length sb.replace(start, end, c.name) @@ -417,8 +417,8 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin else left.name == right.name && rec(left.parent, right.parent) other match { - case p: ActorPath ⇒ rec(this, p) - case _ ⇒ false + case p: ActorPath => rec(this, p) + case _ => false } } @@ -428,8 +428,8 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin @tailrec def rec(p: ActorPath, h: Int, c: Int, k: Int): Int = p match { - case r: RootActorPath ⇒ extendHash(h, r.##, c, k) - case _ ⇒ rec(p.parent, extendHash(h, stringHash(name), c, k), nextMagicA(c), nextMagicB(k)) + case r: RootActorPath => extendHash(h, r.##, c, k) + case _ => rec(p.parent, extendHash(h, stringHash(name), c, k), nextMagicA(c), nextMagicB(k)) } finalizeHash(rec(this, startHash(42), startMagicA, startMagicB)) diff --git a/akka-actor/src/main/scala/akka/actor/ActorRef.scala b/akka-actor/src/main/scala/akka/actor/ActorRef.scala index e6f76b6521..cd469765ae 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorRef.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorRef.scala @@ -101,7 +101,7 @@ object ActorRef { * the unique id of the actor is not taken into account when comparing actor paths. */ abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable { - scalaRef: InternalActorRef ⇒ + scalaRef: InternalActorRef => /** * Returns the path for this actor (from this actor up to the root actor). @@ -150,8 +150,8 @@ abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable * Equals takes path and the unique id of the actor cell into account. */ final override def equals(that: Any): Boolean = that match { - case other: ActorRef ⇒ path.uid == other.path.uid && path == other.path - case _ ⇒ false + case other: ActorRef => path.uid == other.path.uid && path == other.path + case _ => false } override def toString: String = @@ -164,7 +164,7 @@ abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable * There are implicit conversions in package.scala * from ActorRef -> ScalaActorRef and back */ -trait ScalaActorRef { ref: ActorRef ⇒ +trait ScalaActorRef { ref: ActorRef => /** * Sends a one-way asynchronous message. E.g. fire-and-forget semantics. @@ -217,7 +217,7 @@ private[akka] trait RepointableRef extends ActorRefScope { * * DO NOT USE THIS UNLESS INTERNALLY WITHIN AKKA! */ -private[akka] abstract class InternalActorRef extends ActorRef with ScalaActorRef { this: ActorRefScope ⇒ +private[akka] abstract class InternalActorRef extends ActorRef with ScalaActorRef { this: ActorRefScope => /* * Actor life-cycle management, invoked only internally (in response to user requests via ActorContext). */ @@ -267,7 +267,7 @@ private[akka] abstract class InternalActorRef extends ActorRef with ScalaActorRe * type of `underlying` so that follow-up calls can use invokevirtual instead * of invokeinterface. */ -private[akka] abstract class ActorRefWithCell extends InternalActorRef { this: ActorRefScope ⇒ +private[akka] abstract class ActorRefWithCell extends InternalActorRef { this: ActorRefScope => def underlying: Cell def children: immutable.Iterable[ActorRef] def getSingleChild(name: String): InternalActorRef @@ -378,14 +378,14 @@ private[akka] class LocalActorRef private[akka] ( @tailrec def rec(ref: InternalActorRef, name: Iterator[String]): InternalActorRef = ref match { - case l: LocalActorRef ⇒ + case l: LocalActorRef => val next = name.next() match { - case ".." ⇒ l.getParent - case "" ⇒ l - case any ⇒ l.getSingleChild(any) + case ".." => l.getParent + case "" => l + case any => l.getSingleChild(any) } if (next == Nobody || name.isEmpty) next else rec(next, name) - case _ ⇒ + case _ => ref.getChild(name) } @@ -421,11 +421,11 @@ private[akka] final case class SerializedActorRef private (path: String) { @throws(classOf[java.io.ObjectStreamException]) def readResolve(): AnyRef = currentSystem.value match { - case null ⇒ + case null => throw new IllegalStateException( "Trying to deserialize a serialized ActorRef without an ActorSystem in scope." + " Use 'akka.serialization.JavaSerializer.currentSystem.withValue(system) { ... }'") - case someSystem ⇒ + case someSystem => someSystem.provider.resolveActorRef(path) } } @@ -532,36 +532,36 @@ private[akka] class EmptyLocalActorRef( } override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = message match { - case null ⇒ throw InvalidMessageException("Message is null") - case d: DeadLetter ⇒ + case null => throw InvalidMessageException("Message is null") + case d: DeadLetter => specialHandle(d.message, d.sender) // do NOT form endless loops, since deadLetters will resend! - case _ if !specialHandle(message, sender) ⇒ + case _ if !specialHandle(message, sender) => eventStream.publish(DeadLetter(message, if (sender eq Actor.noSender) provider.deadLetters else sender, this)) - case _ ⇒ + case _ => } protected def specialHandle(msg: Any, sender: ActorRef): Boolean = msg match { - case w: Watch ⇒ + case w: Watch => if (w.watchee == this && w.watcher != this) w.watcher.sendSystemMessage( DeathWatchNotification(w.watchee, existenceConfirmed = false, addressTerminated = false)) true - case _: Unwatch ⇒ true // Just ignore - case Identify(messageId) ⇒ + case _: Unwatch => true // Just ignore + case Identify(messageId) => sender ! ActorIdentity(messageId, None) true - case sel: ActorSelectionMessage ⇒ + case sel: ActorSelectionMessage => sel.identifyRequest match { - case Some(identify) ⇒ + case Some(identify) => if (!sel.wildcardFanOut) sender ! ActorIdentity(identify.messageId, None) - case None ⇒ + case None => eventStream.publish(DeadLetter(sel.msg, if (sender eq Actor.noSender) provider.deadLetters else sender, this)) } true - case m: DeadLetterSuppression ⇒ + case m: DeadLetterSuppression => eventStream.publish(SuppressedDeadLetter(m, if (sender eq Actor.noSender) provider.deadLetters else sender, this)) true - case _ ⇒ false + case _ => false } } @@ -577,20 +577,20 @@ private[akka] class DeadLetterActorRef( _eventStream: EventStream) extends EmptyLocalActorRef(_provider, _path, _eventStream) { override def !(message: Any)(implicit sender: ActorRef = this): Unit = message match { - case null ⇒ throw InvalidMessageException("Message is null") - case Identify(messageId) ⇒ sender ! ActorIdentity(messageId, None) - case d: DeadLetter ⇒ if (!specialHandle(d.message, d.sender)) eventStream.publish(d) - case _ ⇒ if (!specialHandle(message, sender)) + case null => throw InvalidMessageException("Message is null") + case Identify(messageId) => sender ! ActorIdentity(messageId, None) + case d: DeadLetter => if (!specialHandle(d.message, d.sender)) eventStream.publish(d) + case _ => if (!specialHandle(message, sender)) eventStream.publish(DeadLetter(message, if (sender eq Actor.noSender) provider.deadLetters else sender, this)) } override protected def specialHandle(msg: Any, sender: ActorRef): Boolean = msg match { - case w: Watch ⇒ + case w: Watch => if (w.watchee != this && w.watcher != this) w.watcher.sendSystemMessage( DeathWatchNotification(w.watchee, existenceConfirmed = false, addressTerminated = false)) true - case _ ⇒ super.specialHandle(msg, sender) + case _ => super.specialHandle(msg, sender) } @throws(classOf[java.io.ObjectStreamException]) @@ -615,37 +615,37 @@ private[akka] class VirtualPathContainer( * are supported, otherwise messages are sent to [[EmptyLocalActorRef]]. */ override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = message match { - case sel @ ActorSelectionMessage(msg, elements, wildcardFanOut) ⇒ { + case sel @ ActorSelectionMessage(msg, elements, wildcardFanOut) => { require(elements.nonEmpty) def emptyRef = new EmptyLocalActorRef(provider, path / sel.elements.map(_.toString), provider.systemGuardian.underlying.system.eventStream) elements.head match { - case SelectChildName(name) ⇒ + case SelectChildName(name) => getChild(name) match { - case null ⇒ + case null => if (!wildcardFanOut) emptyRef.tell(msg, sender) - case child ⇒ + case child => if (elements.tail.isEmpty) { child ! msg } else if (!wildcardFanOut) { emptyRef.tell(msg, sender) } } - case _ ⇒ + case _ => if (!wildcardFanOut) emptyRef.tell(msg, sender) } } - case _ ⇒ super.!(message) + case _ => super.!(message) } def addChild(name: String, ref: InternalActorRef): Unit = { children.put(name, ref) match { - case null ⇒ // okay - case old ⇒ + case null => // okay + case old => // this can happen from RemoteSystemDaemon if a new child is created // before the old is removed from RemoteSystemDaemon children log.debug("{} replacing child {} ({} -> {})", path, name, old, ref) @@ -676,8 +676,8 @@ private[akka] class VirtualPathContainer( val n = name.next() if (n.isEmpty) this else children.get(n) match { - case null ⇒ Nobody - case some ⇒ + case null => Nobody + case some => if (name.isEmpty) some else some.getChild(name) } @@ -686,7 +686,7 @@ private[akka] class VirtualPathContainer( def hasChildren: Boolean = !children.isEmpty - def foreachChild(f: ActorRef ⇒ Unit): Unit = { + def foreachChild(f: ActorRef => Unit): Unit = { val iter = children.values.iterator while (iter.hasNext) f(iter.next) } @@ -713,22 +713,22 @@ private[akka] final class FunctionRef( override val path: ActorPath, override val provider: ActorRefProvider, system: ActorSystem, - f: (ActorRef, Any) ⇒ Unit) extends MinimalActorRef { + f: (ActorRef, Any) => Unit) extends MinimalActorRef { override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = { message match { - case AddressTerminated(address) ⇒ addressTerminated(address) - case _ ⇒ f(sender, message) + case AddressTerminated(address) => addressTerminated(address) + case _ => f(sender, message) } } override def sendSystemMessage(message: SystemMessage): Unit = { message match { - case w: Watch ⇒ addWatcher(w.watchee, w.watcher) - case u: Unwatch ⇒ remWatcher(u.watchee, u.watcher) - case DeathWatchNotification(actorRef, _, _) ⇒ + case w: Watch => addWatcher(w.watchee, w.watcher) + case u: Unwatch => remWatcher(u.watchee, u.watcher) + case DeathWatchNotification(actorRef, _, _) => this.!(Terminated(actorRef)(existenceConfirmed = true, addressTerminated = false))(actorRef) - case _ ⇒ //ignore all other messages + case _ => //ignore all other messages } } @@ -748,7 +748,7 @@ private[akka] final class FunctionRef( val (toUnwatch, watchedBy) = this.synchronized { _watchedBy match { - case OptionVal.Some(wBy) ⇒ + case OptionVal.Some(wBy) => val oldWatching = watching watching = Set.empty @@ -757,7 +757,7 @@ private[akka] final class FunctionRef( (oldWatching, wBy) - case OptionVal.None ⇒ + case OptionVal.None => (ActorCell.emptyActorRefSet, ActorCell.emptyActorRefSet) } } @@ -780,10 +780,10 @@ private[akka] final class FunctionRef( val toNotify = this.synchronized { // cleanup watchedBy since we know they are dead _watchedBy match { - case OptionVal.None ⇒ + case OptionVal.None => // terminated ActorCell.emptyActorRefSet - case OptionVal.Some(watchedBy) ⇒ + case OptionVal.Some(watchedBy) => maintainAddressTerminatedSubscription(OptionVal.None) { _watchedBy = OptionVal.Some(watchedBy.filterNot(_.path.address == address)) } @@ -793,7 +793,7 @@ private[akka] final class FunctionRef( // outside of synchronized block // send DeathWatchNotification to self for all matching subjects - for (a ← toNotify; if a.path.address == address) { + for (a <- toNotify; if a.path.address == address) { this.sendSystemMessage(DeathWatchNotification(a, existenceConfirmed = false, addressTerminated = true)) } } @@ -803,9 +803,9 @@ private[akka] final class FunctionRef( private def addWatcher(watchee: ActorRef, watcher: ActorRef): Unit = { val selfTerminated = this.synchronized { _watchedBy match { - case OptionVal.None ⇒ + case OptionVal.None => true - case OptionVal.Some(watchedBy) ⇒ + case OptionVal.Some(watchedBy) => val watcheeSelf = watchee == this val watcherSelf = watcher == this @@ -832,8 +832,8 @@ private[akka] final class FunctionRef( private def remWatcher(watchee: ActorRef, watcher: ActorRef): Unit = this.synchronized { _watchedBy match { - case OptionVal.None ⇒ // do nothing... - case OptionVal.Some(watchedBy) ⇒ + case OptionVal.None => // do nothing... + case OptionVal.Some(watchedBy) => val watcheeSelf = watchee == this val watcherSelf = watcher == this @@ -851,7 +851,7 @@ private[akka] final class FunctionRef( } } - private def publish(e: Logging.LogEvent): Unit = try system.eventStream.publish(e) catch { case NonFatal(_) ⇒ } + private def publish(e: Logging.LogEvent): Unit = try system.eventStream.publish(e) catch { case NonFatal(_) => } /** * Have this FunctionRef watch the given Actor. @@ -901,23 +901,23 @@ private[akka] final class FunctionRef( * This method must only be used from synchronized methods because AddressTerminatedTopic * must be updated together with changes to watching or watchedBy. */ - private def maintainAddressTerminatedSubscription[T](change: OptionVal[ActorRef])(block: ⇒ T): T = { + private def maintainAddressTerminatedSubscription[T](change: OptionVal[ActorRef])(block: => T): T = { def isNonLocal(ref: ActorRef) = ref match { - case a: InternalActorRef if !a.isLocal ⇒ true - case _ ⇒ false + case a: InternalActorRef if !a.isLocal => true + case _ => false } def watchedByOrEmpty: Set[ActorRef] = _watchedBy match { - case OptionVal.Some(watchedBy) ⇒ watchedBy - case OptionVal.None ⇒ ActorCell.emptyActorRefSet + case OptionVal.Some(watchedBy) => watchedBy + case OptionVal.None => ActorCell.emptyActorRefSet } change match { - case OptionVal.Some(ref) if !isNonLocal(ref) ⇒ + case OptionVal.Some(ref) if !isNonLocal(ref) => // AddressTerminatedTopic update not needed block - case _ ⇒ + case _ => def hasNonLocalAddress: Boolean = (watching exists isNonLocal) || (watchedByOrEmpty exists isNonLocal) val had = hasNonLocalAddress diff --git a/akka-actor/src/main/scala/akka/actor/ActorRefProvider.scala b/akka-actor/src/main/scala/akka/actor/ActorRefProvider.scala index be244835b4..166eeac275 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorRefProvider.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorRefProvider.scala @@ -343,13 +343,13 @@ trait ActorRefFactory { * replies in order to resolve the matching set of actors. */ def actorSelection(path: String): ActorSelection = path match { - case RelativeActorPath(elems) ⇒ + case RelativeActorPath(elems) => if (elems.isEmpty) ActorSelection(provider.deadLetters, "") else if (elems.head.isEmpty) ActorSelection(provider.rootGuardian, elems.tail) else ActorSelection(lookupRoot, elems) - case ActorPathExtractor(address, elems) ⇒ + case ActorPathExtractor(address, elems) => ActorSelection(provider.rootGuardianAt(address), elems) - case _ ⇒ + case _ => ActorSelection(provider.deadLetters, "") } @@ -405,8 +405,8 @@ private[akka] object LocalActorRefProvider { with RequiresMessageQueue[UnboundedMessageQueueSemantics] { def receive = { - case Terminated(_) ⇒ context.stop(self) - case StopChild(child) ⇒ context.stop(child) + case Terminated(_) => context.stop(self) + case StopChild(child) => context.stop(child) } // guardian MUST NOT lose its children during restart @@ -423,26 +423,26 @@ private[akka] object LocalActorRefProvider { var terminationHooks = Set.empty[ActorRef] def receive = { - case Terminated(`guardian`) ⇒ + case Terminated(`guardian`) => // time for the systemGuardian to stop, but first notify all the // termination hooks, they will reply with TerminationHookDone // and when all are done the systemGuardian is stopped context.become(terminating) terminationHooks foreach { _ ! TerminationHook } stopWhenAllTerminationHooksDone() - case Terminated(a) ⇒ + case Terminated(a) => // a registered, and watched termination hook terminated before // termination process of guardian has started terminationHooks -= a - case StopChild(child) ⇒ context.stop(child) - case RegisterTerminationHook if sender() != context.system.deadLetters ⇒ + case StopChild(child) => context.stop(child) + case RegisterTerminationHook if sender() != context.system.deadLetters => terminationHooks += sender() context watch sender() } def terminating: Receive = { - case Terminated(a) ⇒ stopWhenAllTerminationHooksDone(a) - case TerminationHookDone ⇒ stopWhenAllTerminationHooksDone(sender()) + case Terminated(a) => stopWhenAllTerminationHooksDone(a) + case TerminationHookDone => stopWhenAllTerminationHooksDone(sender()) } def stopWhenAllTerminationHooksDone(remove: ActorRef): Unit = { @@ -475,7 +475,7 @@ private[akka] class LocalActorRefProvider private[akka] ( val eventStream: EventStream, val dynamicAccess: DynamicAccess, override val deployer: Deployer, - _deadLetters: Option[ActorPath ⇒ InternalActorRef]) + _deadLetters: Option[ActorPath => InternalActorRef]) extends ActorRefProvider { // this is the constructor needed for reflectively instantiating the provider @@ -497,7 +497,7 @@ private[akka] class LocalActorRefProvider private[akka] ( private[akka] val log: MarkerLoggingAdapter = Logging.withMarker(eventStream, getClass.getName + "(" + rootPath.address + ")") override val deadLetters: InternalActorRef = - _deadLetters.getOrElse((p: ActorPath) ⇒ new DeadLetterActorRef(this, p, eventStream)).apply(rootPath / "deadLetters") + _deadLetters.getOrElse((p: ActorPath) => new DeadLetterActorRef(this, p, eventStream)).apply(rootPath / "deadLetters") private[this] final val terminationPromise: Promise[Terminated] = Promise[Terminated]() @@ -536,19 +536,19 @@ private[akka] class LocalActorRefProvider private[akka] ( override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = if (isWalking) message match { - case null ⇒ throw InvalidMessageException("Message is null") - case _ ⇒ log.error(s"$this received unexpected message [$message]") + case null => throw InvalidMessageException("Message is null") + case _ => log.error(s"$this received unexpected message [$message]") } override def sendSystemMessage(message: SystemMessage): Unit = if (isWalking) { message match { - case Failed(child: InternalActorRef, ex, _) ⇒ + case Failed(child: InternalActorRef, ex, _) => log.error(ex, s"guardian $child failed, shutting down!") causeOfTermination.tryFailure(ex) child.stop() - case Supervise(_, _) ⇒ // TODO register child in some map to keep track of it and enable shutdown after all dead - case _: DeathWatchNotification ⇒ stop() - case _ ⇒ log.error(s"$this received unexpected system message [$message]") + case Supervise(_, _) => // TODO register child in some map to keep track of it and enable shutdown after all dead + case _: DeathWatchNotification => stop() + case _ => log.error(s"$this received unexpected system message [$message]") } } } @@ -581,7 +581,7 @@ private[akka] class LocalActorRefProvider private[akka] ( * Overridable supervision strategy to be used by the “/user” guardian. */ protected def rootGuardianStrategy: SupervisorStrategy = OneForOneStrategy() { - case ex ⇒ + case ex => log.error(ex, "guardian failed, shutting down system") SupervisorStrategy.Stop } @@ -610,9 +610,9 @@ private[akka] class LocalActorRefProvider private[akka] ( rootPath) { override def getParent: InternalActorRef = this override def getSingleChild(name: String): InternalActorRef = name match { - case "temp" ⇒ tempContainer - case "deadLetters" ⇒ deadLetters - case other ⇒ extraNames.get(other).getOrElse(super.getSingleChild(other)) + case "temp" => tempContainer + case "deadLetters" => deadLetters + case other => extraNames.get(other).getOrElse(super.getSingleChild(other)) } } @@ -664,14 +664,14 @@ private[akka] class LocalActorRefProvider private[akka] ( @deprecated("use actorSelection instead of actorFor", "2.2") private[akka] override def actorFor(ref: InternalActorRef, path: String): InternalActorRef = path match { - case RelativeActorPath(elems) ⇒ + case RelativeActorPath(elems) => if (elems.isEmpty) { log.debug("look-up of empty path string [{}] fails (per definition)", path) deadLetters } else if (elems.head.isEmpty) actorFor(rootGuardian, elems.tail) else actorFor(ref, elems) - case ActorPathExtractor(address, elems) if address == rootPath.address ⇒ actorFor(rootGuardian, elems) - case _ ⇒ + case ActorPathExtractor(address, elems) if address == rootPath.address => actorFor(rootGuardian, elems) + case _ => log.debug("look-up of unknown path [{}] failed", path) deadLetters } @@ -690,15 +690,15 @@ private[akka] class LocalActorRefProvider private[akka] ( log.debug("look-up of empty path sequence fails (per definition)") deadLetters } else ref.getChild(path.iterator) match { - case Nobody ⇒ + case Nobody => log.debug("look-up of path sequence [/{}] failed", path.mkString("/")) new EmptyLocalActorRef(system.provider, ref.path / path, eventStream) - case x ⇒ x + case x => x } def resolveActorRef(path: String): ActorRef = path match { - case ActorPathExtractor(address, elems) if address == rootPath.address ⇒ resolveActorRef(rootGuardian, elems) - case _ ⇒ + case ActorPathExtractor(address, elems) if address == rootPath.address => resolveActorRef(rootGuardian, elems) + case _ => log.debug("Resolve (deserialization) of unknown (invalid) path [{}], using deadLetters.", path) deadLetters } @@ -721,22 +721,22 @@ private[akka] class LocalActorRefProvider private[akka] ( log.debug("Resolve (deserialization) of empty path doesn't match an active actor, using deadLetters.") deadLetters } else ref.getChild(pathElements.iterator) match { - case Nobody ⇒ + case Nobody => if (log.isDebugEnabled) log.debug( "Resolve (deserialization) of path [{}] doesn't match an active actor. " + "It has probably been stopped, using deadLetters.", pathElements.mkString("/")) new EmptyLocalActorRef(system.provider, ref.path / pathElements, eventStream) - case x ⇒ x + case x => x } def actorOf(system: ActorSystemImpl, props: Props, supervisor: InternalActorRef, path: ActorPath, systemService: Boolean, deploy: Option[Deploy], lookupDeploy: Boolean, async: Boolean): InternalActorRef = { props.deploy.routerConfig match { - case NoRouter ⇒ + case NoRouter => if (settings.DebugRouterMisconfiguration) { - deployer.lookup(path) foreach { d ⇒ + deployer.lookup(path) foreach { d => if (d.routerConfig != NoRouter) log.warning("Configuration says that [{}] should be a router, but code disagrees. Remove the config or add a routerConfig to its Props.", path) } @@ -745,14 +745,14 @@ private[akka] class LocalActorRefProvider private[akka] ( val props2 = // mailbox and dispatcher defined in deploy should override props (if (lookupDeploy) deployer.lookup(path) else deploy) match { - case Some(d) ⇒ + case Some(d) => (d.dispatcher, d.mailbox) match { - case (Deploy.NoDispatcherGiven, Deploy.NoMailboxGiven) ⇒ props - case (dsp, Deploy.NoMailboxGiven) ⇒ props.withDispatcher(dsp) - case (Deploy.NoMailboxGiven, mbx) ⇒ props.withMailbox(mbx) - case (dsp, mbx) ⇒ props.withDispatcher(dsp).withMailbox(mbx) + case (Deploy.NoDispatcherGiven, Deploy.NoMailboxGiven) => props + case (dsp, Deploy.NoMailboxGiven) => props.withDispatcher(dsp) + case (Deploy.NoMailboxGiven, mbx) => props.withMailbox(mbx) + case (dsp, mbx) => props.withDispatcher(dsp).withMailbox(mbx) } - case _ ⇒ props // no deployment config found + case _ => props // no deployment config found } if (!system.dispatchers.hasDispatcher(props2.dispatcher)) @@ -765,13 +765,13 @@ private[akka] class LocalActorRefProvider private[akka] ( if (async) new RepointableActorRef(system, props2, dispatcher, mailboxType, supervisor, path).initialize(async) else new LocalActorRef(system, props2, dispatcher, mailboxType, supervisor, path) } catch { - case NonFatal(e) ⇒ throw new ConfigurationException( + case NonFatal(e) => throw new ConfigurationException( s"configuration problem while creating [$path] with dispatcher [${props2.dispatcher}] and mailbox [${props2.mailbox}]", e) } - case router ⇒ + case router => val lookup = if (lookupDeploy) deployer.lookup(path) else None - val r = router :: deploy.map(_.routerConfig).toList ::: lookup.map(_.routerConfig).toList reduce ((a, b) ⇒ b withFallback a) + val r = router :: deploy.map(_.routerConfig).toList ::: lookup.map(_.routerConfig).toList reduce ((a, b) => b withFallback a) val p = props.withRouter(r) if (!system.dispatchers.hasDispatcher(p.dispatcher)) @@ -795,7 +795,7 @@ private[akka] class LocalActorRefProvider private[akka] ( new RoutedActorRef(system, routerProps, routerDispatcher, routerMailbox, routeeProps, supervisor, path).initialize(async) } catch { - case NonFatal(e) ⇒ throw new ConfigurationException( + case NonFatal(e) => throw new ConfigurationException( s"configuration problem while creating [$path] with router dispatcher [${routerProps.dispatcher}] and mailbox [${routerProps.mailbox}] " + s"and routee dispatcher [${routeeProps.dispatcher}] and mailbox [${routeeProps.mailbox}]", e) } @@ -811,8 +811,8 @@ private[akka] class LocalActorRefProvider private[akka] ( @InternalApi override private[akka] def serializationInformation: Serialization.Information = { Serialization.Information(getDefaultAddress, system) serializationInformationCache match { - case OptionVal.Some(info) ⇒ info - case OptionVal.None ⇒ + case OptionVal.Some(info) => info + case OptionVal.None => if (system eq null) throw new IllegalStateException("Too early access of serializationInformation") else { diff --git a/akka-actor/src/main/scala/akka/actor/ActorSelection.scala b/akka-actor/src/main/scala/akka/actor/ActorSelection.scala index f6256ee98a..fd798c1848 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorSelection.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorSelection.scala @@ -30,7 +30,7 @@ import akka.util.ccompat._ */ @SerialVersionUID(1L) abstract class ActorSelection extends Serializable { - this: ScalaActorSelection ⇒ + this: ScalaActorSelection => protected[akka] val anchor: ActorRef @@ -67,8 +67,8 @@ abstract class ActorSelection extends Serializable { implicit val ec = ExecutionContexts.sameThreadExecutionContext val p = Promise[ActorRef]() this.ask(Identify(None)) onComplete { - case Success(ActorIdentity(_, Some(ref))) ⇒ p.success(ref) - case _ ⇒ p.failure(ActorNotFound(this)) + case Success(ActorIdentity(_, Some(ref))) => p.success(ref) + case _ => p.failure(ActorNotFound(this)) } p.future } @@ -154,8 +154,8 @@ abstract class ActorSelection extends Serializable { */ def toSerializationFormat: String = { val anchorPath = anchor match { - case a: ActorRefWithCell ⇒ anchor.path.toStringWithAddress(a.provider.getDefaultAddress) - case _ ⇒ anchor.path.toString + case a: ActorRefWithCell => anchor.path.toStringWithAddress(a.provider.getDefaultAddress) + case _ => anchor.path.toString } val builder = new java.lang.StringBuilder() @@ -169,8 +169,8 @@ abstract class ActorSelection extends Serializable { } override def equals(obj: Any): Boolean = obj match { - case s: ActorSelection ⇒ this.anchor == s.anchor && this.path == s.path - case _ ⇒ false + case s: ActorSelection => this.anchor == s.anchor && this.path == s.path + case _ => false } override lazy val hashCode: Int = { @@ -205,7 +205,7 @@ object ActorSelection { */ def apply(anchorRef: ActorRef, elements: Iterable[String]): ActorSelection = { val compiled: immutable.IndexedSeq[SelectionPathElement] = elements.iterator.collect({ - case x if !x.isEmpty ⇒ + case x if !x.isEmpty => if ((x.indexOf('?') != -1) || (x.indexOf('*') != -1)) SelectChildPattern(x) else if (x == "..") SelectParent else SelectChildName(x) @@ -230,19 +230,19 @@ object ActorSelection { @tailrec def rec(ref: InternalActorRef): Unit = { ref match { - case refWithCell: ActorRefWithCell ⇒ + case refWithCell: ActorRefWithCell => def emptyRef = new EmptyLocalActorRef(refWithCell.provider, anchor.path / sel.elements.map(_.toString), refWithCell.underlying.system.eventStream) iter.next() match { - case SelectParent ⇒ + case SelectParent => val parent = ref.getParent if (iter.isEmpty) parent.tell(sel.msg, sender) else rec(parent) - case SelectChildName(name) ⇒ + case SelectChildName(name) => val child = refWithCell.getSingleChild(name) if (child == Nobody) { // don't send to emptyRef after wildcard fan-out @@ -251,18 +251,18 @@ object ActorSelection { child.tell(sel.msg, sender) else rec(child) - case p: SelectChildPattern ⇒ + case p: SelectChildPattern => // fan-out when there is a wildcard val chldr = refWithCell.children if (iter.isEmpty) { // leaf - val matchingChildren = chldr.filter(c ⇒ p.pattern.matcher(c.path.name).matches) + val matchingChildren = chldr.filter(c => p.pattern.matcher(c.path.name).matches) if (matchingChildren.isEmpty && !sel.wildcardFanOut) emptyRef.tell(sel, sender) else matchingChildren.foreach(_.tell(sel.msg, sender)) } else { - val matchingChildren = chldr.filter(c ⇒ p.pattern.matcher(c.path.name).matches) + val matchingChildren = chldr.filter(c => p.pattern.matcher(c.path.name).matches) // don't send to emptyRef after wildcard fan-out if (matchingChildren.isEmpty && !sel.wildcardFanOut) emptyRef.tell(sel, sender) @@ -270,12 +270,12 @@ object ActorSelection { val m = sel.copy( elements = iter.toVector, wildcardFanOut = sel.wildcardFanOut || matchingChildren.size > 1) - matchingChildren.foreach(c ⇒ deliverSelection(c.asInstanceOf[InternalActorRef], sender, m)) + matchingChildren.foreach(c => deliverSelection(c.asInstanceOf[InternalActorRef], sender, m)) } } } - case _ ⇒ + case _ => // foreign ref, continue by sending ActorSelectionMessage to it with remaining elements ref.tell(sel.copy(elements = iter.toVector), sender) } @@ -290,7 +290,7 @@ object ActorSelection { * as per the usual implicit ActorRef pattern. */ trait ScalaActorSelection { - this: ActorSelection ⇒ + this: ActorSelection => def !(msg: Any)(implicit sender: ActorRef = Actor.noSender): Unit = tell(msg, sender) } @@ -309,8 +309,8 @@ private[akka] final case class ActorSelectionMessage( extends AutoReceivedMessage with PossiblyHarmful { def identifyRequest: Option[Identify] = msg match { - case x: Identify ⇒ Some(x) - case _ ⇒ None + case x: Identify => Some(x) + case _ => None } } diff --git a/akka-actor/src/main/scala/akka/actor/ActorSystem.scala b/akka-actor/src/main/scala/akka/actor/ActorSystem.scala index 51e64e1eeb..758758935b 100644 --- a/akka-actor/src/main/scala/akka/actor/ActorSystem.scala +++ b/akka-actor/src/main/scala/akka/actor/ActorSystem.scala @@ -139,13 +139,13 @@ object ActorSystem { val Version: String = akka.Version.current // generated file val EnvHome: Option[String] = System.getenv("AKKA_HOME") match { - case null | "" | "." ⇒ None - case value ⇒ Some(value) + case null | "" | "." => None + case value => Some(value) } val SystemHome: Option[String] = System.getProperty("akka.home") match { - case null | "" ⇒ None - case value ⇒ Some(value) + case null | "" => None + case value => Some(value) } val GlobalHome: Option[String] = SystemHome orElse EnvHome @@ -318,11 +318,11 @@ object ActorSystem { setup.get[BootstrapSetup] .flatMap(_.actorRefProvider).map(_.identifier) .getOrElse(getString("akka.actor.provider")) match { - case "local" ⇒ classOf[LocalActorRefProvider].getName + case "local" => classOf[LocalActorRefProvider].getName // these two cannot be referenced by class as they may not be on the classpath - case "remote" ⇒ "akka.remote.RemoteActorRefProvider" - case "cluster" ⇒ "akka.cluster.ClusterActorRefProvider" - case fqcn ⇒ fqcn + case "remote" => "akka.remote.RemoteActorRefProvider" + case "cluster" => "akka.cluster.ClusterActorRefProvider" + case fqcn => fqcn } final val SupervisorStrategyClass: String = getString("akka.actor.guardian-supervisor-strategy") @@ -343,9 +343,9 @@ object ActorSystem { final val LoggerStartTimeout: Timeout = Timeout(config.getMillisDuration("akka.logger-startup-timeout")) final val LogConfigOnStart: Boolean = config.getBoolean("akka.log-config-on-start") final val LogDeadLetters: Int = toRootLowerCase(config.getString("akka.log-dead-letters")) match { - case "off" | "false" ⇒ 0 - case "on" | "true" ⇒ Int.MaxValue - case _ ⇒ config.getInt("akka.log-dead-letters") + case "off" | "false" => 0 + case "on" | "true" => Int.MaxValue + case _ => config.getInt("akka.log-dead-letters") } final val LogDeadLettersDuringShutdown: Boolean = config.getBoolean("akka.log-dead-letters-during-shutdown") @@ -358,8 +358,8 @@ object ActorSystem { final val DebugRouterMisconfiguration: Boolean = getBoolean("akka.actor.debug.router-misconfiguration") final val Home: Option[String] = config.getString("akka.home") match { - case "" ⇒ None - case x ⇒ Some(x) + case "" => None + case x => Some(x) } final val SchedulerClass: String = getString("akka.scheduler.implementation") @@ -535,7 +535,7 @@ abstract class ActorSystem extends ActorRefFactory { * * Scala API */ - def registerOnTermination[T](code: ⇒ T): Unit + def registerOnTermination[T](code: => T): Unit /** * Java API: Register a block of code (callback) to run after [[ActorSystem.terminate()]] has been issued and @@ -689,8 +689,8 @@ private[akka] class ActorSystemImpl( new Thread.UncaughtExceptionHandler() { def uncaughtException(thread: Thread, cause: Throwable): Unit = { cause match { - case NonFatal(_) | _: InterruptedException | _: NotImplementedError | _: ControlThrowable ⇒ log.error(cause, "Uncaught error from thread [{}]", thread.getName) - case _ ⇒ + case NonFatal(_) | _: InterruptedException | _: NotImplementedError | _: ControlThrowable => log.error(cause, "Uncaught error from thread [{}]", thread.getName) + case _ => if (cause.isInstanceOf[IncompatibleClassChangeError] && cause.getMessage.startsWith("akka")) System.err.println( s"""Detected ${cause.getClass.getName} error, which MAY be caused by incompatible Akka versions on the classpath. @@ -763,9 +763,9 @@ private[akka] class ActorSystemImpl( val guard = guardian.path val sys = systemGuardian.path path.parent match { - case `guard` ⇒ guardian ! StopChild(actor) - case `sys` ⇒ systemGuardian ! StopChild(actor) - case _ ⇒ actor.asInstanceOf[InternalActorRef].stop() + case `guard` => guardian ! StopChild(actor) + case `sys` => systemGuardian ! StopChild(actor) + case _ => actor.asInstanceOf[InternalActorRef].stop() } } @@ -776,7 +776,7 @@ private[akka] class ActorSystemImpl( eventStream.startStdoutLogger(settings) val logFilter: LoggingFilter = { - val arguments = Vector(classOf[Settings] → settings, classOf[EventStream] → eventStream) + val arguments = Vector(classOf[Settings] -> settings, classOf[EventStream] -> eventStream) dynamicAccess.createInstanceFor[LoggingFilter](LoggingFilter, arguments).get } @@ -787,14 +787,14 @@ private[akka] class ActorSystemImpl( val provider: ActorRefProvider = try { val arguments = Vector( - classOf[String] → name, - classOf[Settings] → settings, - classOf[EventStream] → eventStream, - classOf[DynamicAccess] → dynamicAccess) + classOf[String] -> name, + classOf[Settings] -> settings, + classOf[EventStream] -> eventStream, + classOf[DynamicAccess] -> dynamicAccess) dynamicAccess.createInstanceFor[ActorRefProvider](ProviderClass, arguments).get } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => Try(stopScheduler()) throw e } @@ -883,13 +883,13 @@ private[akka] class ActorSystemImpl( if (LogConfigOnStart) logConfiguration() this } catch { - case NonFatal(e) ⇒ - try terminate() catch { case NonFatal(_) ⇒ Try(stopScheduler()) } + case NonFatal(e) => + try terminate() catch { case NonFatal(_) => Try(stopScheduler()) } throw e } def start(): this.type = _start - def registerOnTermination[T](code: ⇒ T): Unit = { registerOnTermination(new Runnable { def run = code }) } + def registerOnTermination[T](code: => T): Unit = { registerOnTermination(new Runnable { def run = code }) } def registerOnTermination(code: Runnable): Unit = { terminationCallbacks.add(code) } override def terminate(): Future[Terminated] = { @@ -923,9 +923,9 @@ private[akka] class ActorSystemImpl( */ protected def createScheduler(): Scheduler = dynamicAccess.createInstanceFor[Scheduler](settings.SchedulerClass, immutable.Seq( - classOf[Config] → settings.config, - classOf[LoggingAdapter] → log, - classOf[ThreadFactory] → threadFactory.withName(threadFactory.name + "-scheduler"))).get + classOf[Config] -> settings.config, + classOf[LoggingAdapter] -> log, + classOf[ThreadFactory] -> threadFactory.withName(threadFactory.name + "-scheduler"))).get //#create-scheduler /* @@ -934,8 +934,8 @@ private[akka] class ActorSystemImpl( * action. */ protected def stopScheduler(): Unit = scheduler match { - case x: Closeable ⇒ x.close() - case _ ⇒ + case x: Closeable => x.close() + case _ => } private val extensions = new ConcurrentHashMap[ExtensionId[_], AnyRef] @@ -945,42 +945,42 @@ private[akka] class ActorSystemImpl( */ @tailrec private def findExtension[T <: Extension](ext: ExtensionId[T]): T = extensions.get(ext) match { - case c: CountDownLatch ⇒ + case c: CountDownLatch => c.await(); findExtension(ext) //Registration in process, await completion and retry - case t: Throwable ⇒ throw t //Initialization failed, throw same again - case other ⇒ + case t: Throwable => throw t //Initialization failed, throw same again + case other => other.asInstanceOf[T] //could be a T or null, in which case we return the null as T } @tailrec final def registerExtension[T <: Extension](ext: ExtensionId[T]): T = { findExtension(ext) match { - case null ⇒ //Doesn't already exist, commence registration + case null => //Doesn't already exist, commence registration val inProcessOfRegistration = new CountDownLatch(1) extensions.putIfAbsent(ext, inProcessOfRegistration) match { // Signal that registration is in process - case null ⇒ try { // Signal was successfully sent + case null => try { // Signal was successfully sent ext.createExtension(this) match { // Create and initialize the extension - case null ⇒ throw new IllegalStateException(s"Extension instance created as 'null' for extension [$ext]") - case instance ⇒ + case null => throw new IllegalStateException(s"Extension instance created as 'null' for extension [$ext]") + case instance => extensions.replace(ext, inProcessOfRegistration, instance) //Replace our in process signal with the initialized extension instance //Profit! } } catch { - case t: Throwable ⇒ + case t: Throwable => extensions.replace(ext, inProcessOfRegistration, t) //In case shit hits the fan, remove the inProcess signal throw t //Escalate to caller } finally { inProcessOfRegistration.countDown //Always notify listeners of the inProcess signal } - case _ ⇒ registerExtension(ext) //Someone else is in process of registering an extension for this Extension, retry + case _ => registerExtension(ext) //Someone else is in process of registering an extension for this Extension, retry } - case existing ⇒ existing.asInstanceOf[T] + case existing => existing.asInstanceOf[T] } } def extension[T <: Extension](ext: ExtensionId[T]): T = findExtension(ext) match { - case null ⇒ throw new IllegalArgumentException(s"Trying to get non-registered extension [$ext]") - case some ⇒ some.asInstanceOf[T] + case null => throw new IllegalArgumentException(s"Trying to get non-registered extension [$ext]") + case some => some.asInstanceOf[T] } def hasExtension(ext: ExtensionId[_ <: Extension]): Boolean = findExtension(ext) != null @@ -990,14 +990,14 @@ private[akka] class ActorSystemImpl( * @param throwOnLoadFail Throw exception when an extension fails to load (needed for backwards compatibility) */ def loadExtensions(key: String, throwOnLoadFail: Boolean): Unit = { - immutableSeq(settings.config.getStringList(key)) foreach { fqcn ⇒ - dynamicAccess.getObjectFor[AnyRef](fqcn) recoverWith { case _ ⇒ dynamicAccess.createInstanceFor[AnyRef](fqcn, Nil) } match { - case Success(p: ExtensionIdProvider) ⇒ registerExtension(p.lookup()) - case Success(p: ExtensionId[_]) ⇒ registerExtension(p) - case Success(_) ⇒ + immutableSeq(settings.config.getStringList(key)) foreach { fqcn => + dynamicAccess.getObjectFor[AnyRef](fqcn) recoverWith { case _ => dynamicAccess.createInstanceFor[AnyRef](fqcn, Nil) } match { + case Success(p: ExtensionIdProvider) => registerExtension(p.lookup()) + case Success(p: ExtensionId[_]) => registerExtension(p) + case Success(_) => if (!throwOnLoadFail) log.error("[{}] is not an 'ExtensionIdProvider' or 'ExtensionId', skipping...", fqcn) else throw new RuntimeException(s"[$fqcn] is not an 'ExtensionIdProvider' or 'ExtensionId'") - case Failure(problem) ⇒ + case Failure(problem) => if (!throwOnLoadFail) log.error(problem, "While trying to load extension [{}], skipping...", fqcn) else throw new RuntimeException(s"While trying to load extension [$fqcn]", problem) } @@ -1013,25 +1013,25 @@ private[akka] class ActorSystemImpl( override def printTree: String = { def printNode(node: ActorRef, indent: String): String = { node match { - case wc: ActorRefWithCell ⇒ + case wc: ActorRefWithCell => val cell = wc.underlying (if (indent.isEmpty) "-> " else indent.dropRight(1) + "⌊-> ") + node.path.name + " " + Logging.simpleName(node) + " " + (cell match { - case real: ActorCell ⇒ if (real.actor ne null) real.actor.getClass else "null" - case _ ⇒ Logging.simpleName(cell) + case real: ActorCell => if (real.actor ne null) real.actor.getClass else "null" + case _ => Logging.simpleName(cell) }) + (cell match { - case real: ActorCell ⇒ " status=" + real.mailbox.currentStatus - case _ ⇒ "" + case real: ActorCell => " status=" + real.mailbox.currentStatus + case _ => "" }) + " " + (cell.childrenRefs match { - case ChildrenContainer.TerminatingChildrenContainer(_, toDie, reason) ⇒ + case ChildrenContainer.TerminatingChildrenContainer(_, toDie, reason) => "Terminating(" + reason + ")" + (toDie.toSeq.sorted mkString ("\n" + indent + " | toDie: ", "\n" + indent + " | ", "")) - case x @ (ChildrenContainer.TerminatedChildrenContainer | ChildrenContainer.EmptyChildrenContainer) ⇒ x.toString - case n: ChildrenContainer.NormalChildrenContainer ⇒ n.c.size + " children" - case x ⇒ Logging.simpleName(x) + case x @ (ChildrenContainer.TerminatedChildrenContainer | ChildrenContainer.EmptyChildrenContainer) => x.toString + case n: ChildrenContainer.NormalChildrenContainer => n.c.size + " children" + case x => Logging.simpleName(x) }) + (if (cell.childrenRefs.children.isEmpty) "" else "\n") + ({ @@ -1039,7 +1039,7 @@ private[akka] class ActorSystemImpl( val bulk = children.dropRight(1) map (printNode(_, indent + " |")) bulk ++ (children.lastOption map (printNode(_, indent + " "))) } mkString ("\n")) - case _ ⇒ + case _ => indent + node.path.name + " " + Logging.simpleName(node) } } @@ -1052,7 +1052,7 @@ private[akka] class ActorSystemImpl( // onComplete never fires twice so safe to avoid null check upStreamTerminated onComplete { - t ⇒ ref.getAndSet(null).complete(t) + t => ref.getAndSet(null).complete(t) } /** @@ -1064,9 +1064,9 @@ private[akka] class ActorSystemImpl( */ final def add(r: Runnable): Unit = { @tailrec def addRec(r: Runnable, p: Promise[T]): Unit = ref.get match { - case null ⇒ throw new RejectedExecutionException("ActorSystem already terminated.") - case some if ref.compareAndSet(some, p) ⇒ some.completeWith(p.future.andThen { case _ ⇒ r.run() }) - case _ ⇒ addRec(r, p) + case null => throw new RejectedExecutionException("ActorSystem already terminated.") + case some if ref.compareAndSet(some, p) => some.completeWith(p.future.andThen { case _ => r.run() }) + case _ => addRec(r, p) } addRec(r, Promise[T]()) } diff --git a/akka-actor/src/main/scala/akka/actor/Address.scala b/akka-actor/src/main/scala/akka/actor/Address.scala index bd16abfc20..08f7e62692 100644 --- a/akka-actor/src/main/scala/akka/actor/Address.scala +++ b/akka-actor/src/main/scala/akka/actor/Address.scala @@ -81,7 +81,7 @@ object Address { /** * `Address` ordering type class, sorts addresses by protocol, name, host and port. */ - implicit val addressOrdering: Ordering[Address] = Ordering.fromLessThan[Address] { (a, b) ⇒ + implicit val addressOrdering: Ordering[Address] = Ordering.fromLessThan[Address] { (a, b) => if (a eq b) false else if (a.protocol != b.protocol) a.system.compareTo(b.protocol) < 0 else if (a.system != b.system) a.system.compareTo(b.system) < 0 @@ -120,7 +120,7 @@ object RelativeActorPath extends PathUtils { if (uri.isAbsolute) None else Some(split(uri.getRawPath, uri.getRawFragment)) } catch { - case _: URISyntaxException ⇒ None + case _: URISyntaxException => None } } } @@ -129,7 +129,7 @@ object RelativeActorPath extends PathUtils { * This object serves as extractor for Scala and as address parser for Java. */ object AddressFromURIString { - def unapply(addr: String): Option[Address] = try unapply(new URI(addr)) catch { case _: URISyntaxException ⇒ None } + def unapply(addr: String): Option[Address] = try unapply(new URI(addr)) catch { case _: URISyntaxException => None } def unapply(uri: URI): Option[Address] = if (uri eq null) None @@ -148,8 +148,8 @@ object AddressFromURIString { * Try to construct an Address from the given String or throw a java.net.MalformedURLException. */ def apply(addr: String): Address = addr match { - case AddressFromURIString(address) ⇒ address - case _ ⇒ throw new MalformedURLException(addr) + case AddressFromURIString(address) => address + case _ => throw new MalformedURLException(addr) } /** @@ -166,10 +166,10 @@ object ActorPathExtractor extends PathUtils { try { val uri = new URI(addr) uri.getRawPath match { - case null ⇒ None - case path ⇒ AddressFromURIString.unapply(uri).map((_, split(path, uri.getRawFragment).drop(1))) + case null => None + case path => AddressFromURIString.unapply(uri).map((_, split(path, uri.getRawFragment).drop(1))) } } catch { - case _: URISyntaxException ⇒ None + case _: URISyntaxException => None } } diff --git a/akka-actor/src/main/scala/akka/actor/CoordinatedShutdown.scala b/akka-actor/src/main/scala/akka/actor/CoordinatedShutdown.scala index 892897e9ac..72d91e5320 100644 --- a/akka-actor/src/main/scala/akka/actor/CoordinatedShutdown.scala +++ b/akka-actor/src/main/scala/akka/actor/CoordinatedShutdown.scala @@ -166,22 +166,22 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi // is started but it might be a race between (failing?) startup and shutdown. def cleanupActorSystemJvmHook(): Unit = { coord.actorSystemJvmHook match { - case OptionVal.Some(cancellable) if !runningJvmHook && !cancellable.isCancelled ⇒ + case OptionVal.Some(cancellable) if !runningJvmHook && !cancellable.isCancelled => cancellable.cancel() coord.actorSystemJvmHook = OptionVal.None - case _ ⇒ + case _ => } } try system.registerOnTermination(cleanupActorSystemJvmHook()) catch { - case _: RejectedExecutionException ⇒ cleanupActorSystemJvmHook() + case _: RejectedExecutionException => cleanupActorSystemJvmHook() } coord } // locate reason-specific overrides and merge with defaults. @InternalApi private[akka] def confWithOverrides(conf: Config, reason: Option[Reason]): Config = { - reason.flatMap { r ⇒ + reason.flatMap { r => val basePath = s"""reason-overrides."${r.getClass.getName}"""" if (conf.hasPath(basePath)) Some(conf.getConfig(basePath).withFallback(conf)) else None }.getOrElse( @@ -190,7 +190,7 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi } private def initPhaseActorSystemTerminate(system: ActorSystem, conf: Config, coord: CoordinatedShutdown): Unit = { - coord.addTask(PhaseActorSystemTerminate, "terminate-system") { () ⇒ + coord.addTask(PhaseActorSystemTerminate, "terminate-system") { () => val confForReason = confWithOverrides(conf, coord.shutdownReason()) val terminateActorSystem = confForReason.getBoolean("terminate-actor-system") val exitJvm = confForReason.getBoolean("exit-jvm") @@ -213,7 +213,7 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi } if (terminateActorSystem) { - system.terminate().map { _ ⇒ + system.terminate().map { _ => if (exitJvm && !runningJvmHook) System.exit(exitCode) Done }(ExecutionContexts.sameThreadExecutionContext) @@ -237,7 +237,7 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi val totalTimeout = coord.totalTimeout().max(3.seconds) Await.ready(coord.run(JvmExitReason), totalTimeout) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => coord.log.warning( "CoordinatedShutdown from JVM shutdown failed: {}", e.getMessage) @@ -266,14 +266,14 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi depends-on = [] """) phasesConf.root.unwrapped.asScala.toMap.map { - case (k, _: java.util.Map[_, _]) ⇒ + case (k, _: java.util.Map[_, _]) => val c = phasesConf.getConfig(k).withFallback(defaultPhaseConfig) val dependsOn = c.getStringList("depends-on").asScala.toSet val timeout = c.getDuration("timeout", MILLISECONDS).millis val recover = c.getBoolean("recover") val enabled = c.getBoolean("enabled") - k → Phase(dependsOn, timeout, recover, enabled) - case (k, v) ⇒ + k -> Phase(dependsOn, timeout, recover, enabled) + case (k, v) => throw new IllegalArgumentException(s"Expected object value for [$k], got [$v]") } } @@ -297,8 +297,8 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi if (unmarked(u)) { tempMark += u phases.get(u) match { - case Some(p) ⇒ p.dependsOn.foreach(depthFirstSearch) - case None ⇒ + case Some(p) => p.dependsOn.foreach(depthFirstSearch) + case None => } unmarked -= u // permanent mark tempMark -= u @@ -322,7 +322,7 @@ final class CoordinatedShutdown private[akka] ( private val knownPhases = phases.keySet ++ phases.values.flatMap(_.dependsOn) /** INTERNAL API */ private[akka] val orderedPhases = CoordinatedShutdown.topologicalSort(phases) - private val tasks = new ConcurrentHashMap[String, Vector[(String, () ⇒ Future[Done])]] + private val tasks = new ConcurrentHashMap[String, Vector[(String, () => Future[Done])]] private val runStarted = new AtomicReference[Option[Reason]](None) private val runPromise = Promise[Done]() @@ -346,7 +346,7 @@ final class CoordinatedShutdown private[akka] ( * It is possible to add a task to a later phase by a task in an earlier phase * and it will be performed. */ - @tailrec def addTask(phase: String, taskName: String)(task: () ⇒ Future[Done]): Unit = { + @tailrec def addTask(phase: String, taskName: String)(task: () => Future[Done]): Unit = { require( knownPhases(phase), s"Unknown phase [$phase], known phases [$knownPhases]. " + @@ -355,10 +355,10 @@ final class CoordinatedShutdown private[akka] ( "Try to use unique, self-explanatory names.") val current = tasks.get(phase) if (current == null) { - if (tasks.putIfAbsent(phase, Vector(taskName → task)) != null) + if (tasks.putIfAbsent(phase, Vector(taskName -> task)) != null) addTask(phase, taskName)(task) // CAS failed, retry } else { - if (!tasks.replace(phase, current, current :+ (taskName → task))) + if (!tasks.replace(phase, current, current :+ (taskName -> task))) addTask(phase, taskName)(task) // CAS failed, retry } } @@ -376,7 +376,7 @@ final class CoordinatedShutdown private[akka] ( * and it will be performed. */ def addTask(phase: String, taskName: String, task: Supplier[CompletionStage[Done]]): Unit = - addTask(phase, taskName)(() ⇒ task.get().toScala) + addTask(phase, taskName)(() => task.get().toScala) /** * The `Reason` for the shutdown as passed to the `run` method. `None` if the shutdown @@ -427,36 +427,36 @@ final class CoordinatedShutdown private[akka] ( val debugEnabled = log.isDebugEnabled def loop(remainingPhases: List[String]): Future[Done] = { remainingPhases match { - case Nil ⇒ Future.successful(Done) - case phase :: remaining if !phases(phase).enabled ⇒ + case Nil => Future.successful(Done) + case phase :: remaining if !phases(phase).enabled => tasks.get(phase) match { - case null ⇒ // This pretty much is ok as there are no tasks - case tasks ⇒ log.info("Phase [{}] disabled through configuration, skipping [{}] tasks", phase, tasks.size) + case null => // This pretty much is ok as there are no tasks + case tasks => log.info("Phase [{}] disabled through configuration, skipping [{}] tasks", phase, tasks.size) } loop(remaining) - case phase :: remaining ⇒ + case phase :: remaining => val phaseResult = tasks.get(phase) match { - case null ⇒ + case null => if (debugEnabled) log.debug("Performing phase [{}] with [0] tasks", phase) Future.successful(Done) - case tasks ⇒ + case tasks => if (debugEnabled) log.debug( "Performing phase [{}] with [{}] tasks: [{}]", - phase, tasks.size, tasks.map { case (taskName, _) ⇒ taskName }.mkString(", ")) + phase, tasks.size, tasks.map { case (taskName, _) => taskName }.mkString(", ")) // note that tasks within same phase are performed in parallel val recoverEnabled = phases(phase).recover val result = Future.sequence(tasks.map { - case (taskName, task) ⇒ + case (taskName, task) => try { val r = task.apply() if (recoverEnabled) r.recover { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning("Task [{}] failed in phase [{}]: {}", taskName, phase, e.getMessage) Done } else r } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // in case task.apply throws if (recoverEnabled) { log.warning("Task [{}] failed in phase [{}]: {}", taskName, phase, e.getMessage) @@ -464,7 +464,7 @@ final class CoordinatedShutdown private[akka] ( } else Future.failed(e) } - }).map(_ ⇒ Done)(ExecutionContexts.sameThreadExecutionContext) + }).map(_ => Done)(ExecutionContexts.sameThreadExecutionContext) val timeout = phases(phase).timeout val deadline = Deadline.now + timeout val timeoutFut = try { @@ -482,7 +482,7 @@ final class CoordinatedShutdown private[akka] ( new TimeoutException(s"Coordinated shutdown phase [$phase] timed out after $timeout")) } } catch { - case _: IllegalStateException ⇒ + case _: IllegalStateException => // The call to `after` threw IllegalStateException, triggered by system termination result } @@ -491,13 +491,13 @@ final class CoordinatedShutdown private[akka] ( if (remaining.isEmpty) phaseResult // avoid flatMap when system terminated in last phase else - phaseResult.flatMap(_ ⇒ loop(remaining)) + phaseResult.flatMap(_ => loop(remaining)) } } val remainingPhases = fromPhase match { - case None ⇒ orderedPhases // all - case Some(p) ⇒ orderedPhases.dropWhile(_ != p) + case None => orderedPhases // all + case Some(p) => orderedPhases.dropWhile(_ != p) } val done = loop(remainingPhases) runPromise.completeWith(done) @@ -530,8 +530,8 @@ final class CoordinatedShutdown private[akka] ( */ def timeout(phase: String): FiniteDuration = phases.get(phase) match { - case Some(p) ⇒ p.timeout - case None ⇒ + case Some(p) => p.timeout + case None => throw new IllegalArgumentException(s"Unknown phase [$phase]. All phases must be defined in configuration") } @@ -541,7 +541,7 @@ final class CoordinatedShutdown private[akka] ( def totalTimeout(): FiniteDuration = { import scala.collection.JavaConverters._ tasks.keySet.asScala.foldLeft(Duration.Zero) { - case (acc, phase) ⇒ acc + timeout(phase) + case (acc, phase) => acc + timeout(phase) } } @@ -551,7 +551,7 @@ final class CoordinatedShutdown private[akka] ( * concurrently, but they are running before Akka internal shutdown * hooks, e.g. those shutting down Artery. */ - def addJvmShutdownHook[T](hook: ⇒ T): Unit = addCancellableJvmShutdownHook(hook) + def addJvmShutdownHook[T](hook: => T): Unit = addCancellableJvmShutdownHook(hook) /** * Scala API: Add a JVM shutdown hook that will be run when the JVM process @@ -565,7 +565,7 @@ final class CoordinatedShutdown private[akka] ( * For shutdown hooks that does not have any requirements on running before the Akka * shutdown hooks the standard library JVM shutdown hooks APIs are better suited. */ - @tailrec def addCancellableJvmShutdownHook[T](hook: ⇒ T): Cancellable = { + @tailrec def addCancellableJvmShutdownHook[T](hook: => T): Cancellable = { if (runStarted.get == None) { val currentLatch = _jvmHooksLatch.get val newLatch = new CountDownLatch(currentLatch.getCount.toInt + 1) @@ -590,7 +590,7 @@ final class CoordinatedShutdown private[akka] ( false } } catch { - case _: IllegalStateException ⇒ + case _: IllegalStateException => // shutdown already in progress false } @@ -598,7 +598,7 @@ final class CoordinatedShutdown private[akka] ( def isCancelled: Boolean = cancelled } } catch { - case e: IllegalStateException ⇒ + case e: IllegalStateException => // Shutdown in progress, if CoordinatedShutdown is created via a JVM shutdown hook (Artery) log.warning("Could not addJvmShutdownHook, due to: {}", e.getMessage) _jvmHooksLatch.get.countDown() diff --git a/akka-actor/src/main/scala/akka/actor/Deployer.scala b/akka-actor/src/main/scala/akka/actor/Deployer.scala index fca632206b..1196a26799 100644 --- a/akka-actor/src/main/scala/akka/actor/Deployer.scala +++ b/akka-actor/src/main/scala/akka/actor/Deployer.scala @@ -137,13 +137,13 @@ private[akka] class Deployer(val settings: ActorSystem.Settings, val dynamicAcce protected val default = config.getConfig("default") val routerTypeMapping: Map[String, String] = settings.config.getConfig("akka.actor.router.type-mapping").root.unwrapped.asScala.collect { - case (key, value: String) ⇒ (key → value) + case (key, value: String) => (key -> value) }.toMap config.root.asScala.map { - case ("default", _) ⇒ None - case (key, value: ConfigObject) ⇒ parseConfig(key, value.toConfig) - case _ ⇒ None + case ("default", _) => None + case (key, value: ConfigObject) => parseConfig(key, value.toConfig) + case _ => None }.flatten foreach deploy def lookup(path: ActorPath): Option[Deploy] = lookup(path.elements.drop(1)) @@ -152,9 +152,9 @@ private[akka] class Deployer(val settings: ActorSystem.Settings, val dynamicAcce def deploy(d: Deploy): Unit = { @tailrec def add(path: Array[String], d: Deploy, w: WildcardIndex[Deploy] = deployments.get): Unit = { - for (i ← path.indices) path(i) match { - case "" ⇒ throw InvalidActorNameException(s"Actor name in deployment [${d.path}] must not be empty") - case el ⇒ ActorPath.validatePathElement(el, fullPath = d.path) + for (i <- path.indices) path(i) match { + case "" => throw InvalidActorNameException(s"Actor name in deployment [${d.path}] must not be empty") + case el => ActorPath.validatePathElement(el, fullPath = d.path) } if (!deployments.compareAndSet(w, w.insert(path, d))) add(path, d) @@ -196,16 +196,16 @@ private[akka] class Deployer(val settings: ActorSystem.Settings, val dynamicAcce s"[${args(0)._1.getName}] and optional [${args(1)._1.getName}] parameter", cause) // first try with Config param, and then with Config and DynamicAccess parameters - val args1 = List(classOf[Config] → deployment2) - val args2 = List(classOf[Config] → deployment2, classOf[DynamicAccess] → dynamicAccess) + val args1 = List(classOf[Config] -> deployment2) + val args2 = List(classOf[Config] -> deployment2, classOf[DynamicAccess] -> dynamicAccess) dynamicAccess.createInstanceFor[RouterConfig](fqn, args1).recover({ - case e @ (_: IllegalArgumentException | _: ConfigException) ⇒ throw e - case e: NoSuchMethodException ⇒ + case e @ (_: IllegalArgumentException | _: ConfigException) => throw e + case e: NoSuchMethodException => dynamicAccess.createInstanceFor[RouterConfig](fqn, args2).recover({ - case e @ (_: IllegalArgumentException | _: ConfigException) ⇒ throw e - case _ ⇒ throwCannotInstantiateRouter(args2, e) + case e @ (_: IllegalArgumentException | _: ConfigException) => throw e + case _ => throwCannotInstantiateRouter(args2, e) }).get - case e ⇒ throwCannotInstantiateRouter(args2, e) + case e => throwCannotInstantiateRouter(args2, e) }).get } diff --git a/akka-actor/src/main/scala/akka/actor/Extension.scala b/akka-actor/src/main/scala/akka/actor/Extension.scala index ab3b6fe9bc..3ad666796c 100644 --- a/akka-actor/src/main/scala/akka/actor/Extension.scala +++ b/akka-actor/src/main/scala/akka/actor/Extension.scala @@ -152,5 +152,5 @@ abstract class ExtensionKey[T <: Extension](implicit m: ClassTag[T]) extends Ext def this(clazz: Class[T]) = this()(ClassTag(clazz)) override def lookup(): ExtensionId[T] = this - def createExtension(system: ExtendedActorSystem): T = system.dynamicAccess.createInstanceFor[T](m.runtimeClass, List(classOf[ExtendedActorSystem] → system)).get + def createExtension(system: ExtendedActorSystem): T = system.dynamicAccess.createInstanceFor[T](m.runtimeClass, List(classOf[ExtendedActorSystem] -> system)).get } diff --git a/akka-actor/src/main/scala/akka/actor/FSM.scala b/akka-actor/src/main/scala/akka/actor/FSM.scala index 57c712e4d6..9afbc98c59 100644 --- a/akka-actor/src/main/scala/akka/actor/FSM.scala +++ b/akka-actor/src/main/scala/akka/actor/FSM.scala @@ -12,7 +12,7 @@ import scala.concurrent.duration._ import akka.routing.{ Deafen, Listen, Listeners } import akka.annotation.InternalApi -import akka.util.{ JavaDurationConverters, unused } +import akka.util.{ unused, JavaDurationConverters } object FSM { @@ -92,17 +92,17 @@ object FSM { * INTERNAL API */ @InternalApi - private[akka] final case class Timer(name: String, msg: Any, repeat: Boolean, generation: Int, - owner: AnyRef)(context: ActorContext) - extends NoSerializationVerificationNeeded { + private[akka] final case class Timer(name: String, msg: Any, repeat: Boolean, generation: Int, owner: AnyRef)( + context: ActorContext) + extends NoSerializationVerificationNeeded { private var ref: Option[Cancellable] = _ private val scheduler = context.system.scheduler private implicit val executionContext = context.dispatcher def schedule(actor: ActorRef, timeout: FiniteDuration): Unit = { val timerMsg = msg match { - case m: AutoReceivedMessage ⇒ m - case _ ⇒ this + case m: AutoReceivedMessage => m + case _ => this } ref = Some( if (repeat) scheduler.schedule(timeout, timeout, actor, timerMsg) @@ -136,15 +136,23 @@ object FSM { * INTERNAL API * Using a subclass for binary compatibility reasons */ - private[akka] class SilentState[S, D](_stateName: S, _stateData: D, _timeout: Option[FiniteDuration], _stopReason: Option[Reason], _replies: List[Any]) - extends State[S, D](_stateName, _stateData, _timeout, _stopReason, _replies) { + private[akka] class SilentState[S, D](_stateName: S, + _stateData: D, + _timeout: Option[FiniteDuration], + _stopReason: Option[Reason], + _replies: List[Any]) + extends State[S, D](_stateName, _stateData, _timeout, _stopReason, _replies) { /** * INTERNAL API */ private[akka] override def notifies: Boolean = false - override def copy(stateName: S = stateName, stateData: D = stateData, timeout: Option[FiniteDuration] = timeout, stopReason: Option[Reason] = stopReason, replies: List[Any] = replies): State[S, D] = { + override def copy(stateName: S = stateName, + stateData: D = stateData, + timeout: Option[FiniteDuration] = timeout, + stopReason: Option[Reason] = stopReason, + replies: List[Any] = replies): State[S, D] = { new SilentState(stateName, stateData, timeout, stopReason, replies) } } @@ -154,7 +162,11 @@ object FSM { * name, the state data, possibly custom timeout, stop reason and replies * accumulated while processing the last message. */ - case class State[S, D](stateName: S, stateData: D, timeout: Option[FiniteDuration] = None, stopReason: Option[Reason] = None, replies: List[Any] = Nil) { + case class State[S, D](stateName: S, + stateData: D, + timeout: Option[FiniteDuration] = None, + stopReason: Option[Reason] = None, + replies: List[Any] = Nil) { /** * INTERNAL API @@ -162,7 +174,11 @@ object FSM { private[akka] def notifies: Boolean = true // defined here to be able to override it in SilentState - def copy(stateName: S = stateName, stateData: D = stateData, timeout: Option[FiniteDuration] = timeout, stopReason: Option[Reason] = stopReason, replies: List[Any] = replies): State[S, D] = { + def copy(stateName: S = stateName, + stateData: D = stateData, + timeout: Option[FiniteDuration] = timeout, + stopReason: Option[Reason] = stopReason, + replies: List[Any] = replies): State[S, D] = { new State(stateName, stateData, timeout, stopReason, replies) } @@ -174,9 +190,9 @@ object FSM { * Use Duration.Inf to deactivate an existing timeout. */ def forMax(timeout: Duration): State[S, D] = timeout match { - case f: FiniteDuration ⇒ copy(timeout = Some(f)) - case Duration.Inf ⇒ copy(timeout = SomeMaxFiniteDuration) // we map the Infinite duration to a special marker, - case _ ⇒ copy(timeout = None) // that means "cancel stateTimeout". This marker is needed + case f: FiniteDuration => copy(timeout = Some(f)) + case Duration.Inf => copy(timeout = SomeMaxFiniteDuration) // we map the Infinite duration to a special marker, + case _ => copy(timeout = None) // that means "cancel stateTimeout". This marker is needed } // so we do not have to break source/binary compat. // TODO: Can be removed once we can break State#timeout signature to `Option[Duration]` @@ -237,7 +253,8 @@ object FSM { * Case class representing the state of the [[akka.actor.FSM]] within the * `onTermination` block. */ - final case class StopEvent[S, D](reason: Reason, currentState: S, stateData: D) extends NoSerializationVerificationNeeded + final case class StopEvent[S, D](reason: Reason, currentState: S, stateData: D) + extends NoSerializationVerificationNeeded } @@ -354,7 +371,6 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * DSL * **************************************** */ - /** * Insert a new StateFunction at the end of the processing chain for the * given state. If the stateTimeout parameter is set, entering this state @@ -401,7 +417,9 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * * @return descriptor for staying in current state */ - final def stay(): State = goto(currentState.stateName).withNotification(false) // cannot directly use currentState because of the timeout field + final def stay(): State = + goto(currentState.stateName) + .withNotification(false) // cannot directly use currentState because of the timeout field /** * Produce change descriptor to stop this FSM actor with reason "Normal". @@ -416,11 +434,11 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { /** * Produce change descriptor to stop this FSM actor including specified reason. */ - final def stop(reason: Reason, stateData: D): State = stay using stateData withStopReason (reason) + final def stop(reason: Reason, stateData: D): State = stay.using(stateData).withStopReason(reason) final class TransformHelper(func: StateFunction) { def using(andThen: PartialFunction[State, State]): StateFunction = - func andThen (andThen orElse { case x ⇒ x }) + func.andThen(andThen.orElse { case x => x }) } final def transform(func: StateFunction): TransformHelper = new TransformHelper(func) @@ -507,7 +525,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * Convenience wrapper for using a total function instead of a partial * function literal. To be used with onTransition. */ - implicit final def total2pf(transitionHandler: (S, S) ⇒ Unit): TransitionHandler = + implicit final def total2pf(transitionHandler: (S, S) => Unit): TransitionHandler = new TransitionHandler { def isDefinedAt(in: (S, S)) = true def apply(in: (S, S)): Unit = { transitionHandler(in._1, in._2) } @@ -527,7 +545,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * The current state may be queried using ``stateName``. */ final def whenUnhandled(stateFunction: StateFunction): Unit = - handleEvent = stateFunction orElse handleEventDefault + handleEvent = stateFunction.orElse(handleEventDefault) /** * Verify existence of initial state and setup timers. This should be the @@ -561,8 +579,8 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * Return next state data (available in onTransition handlers) */ final def nextStateData = nextState match { - case null ⇒ throw new IllegalStateException("nextStateData is only available during onTransition") - case x ⇒ x.stateData + case null => throw new IllegalStateException("nextStateData is only available during onTransition") + case x => x.stateData } /* @@ -585,7 +603,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * Timer handling */ private val timers = mutable.Map[String, Timer]() - private val timerGen = Iterator from 0 + private val timerGen = Iterator.from(0) /* * State definitions @@ -595,8 +613,8 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { private def register(name: S, function: StateFunction, timeout: Timeout): Unit = { if (stateFunctions contains name) { - stateFunctions(name) = stateFunctions(name) orElse function - stateTimeouts(name) = timeout orElse stateTimeouts(name) + stateFunctions(name) = stateFunctions(name).orElse(function) + stateTimeouts(name) = timeout.orElse(stateTimeouts(name)) } else { stateFunctions(name) = function stateTimeouts(name) = timeout @@ -607,7 +625,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * unhandled event handler */ private val handleEventDefault: StateFunction = { - case Event(value, _) ⇒ + case Event(value, _) => log.warning("unhandled event " + value + " in state " + stateName) stay } @@ -624,7 +642,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { private var transitionEvent: List[TransitionHandler] = Nil private def handleTransition(prev: S, next: S): Unit = { val tuple = (prev, next) - for (te ← transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) } + for (te <- transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) } } /* @@ -633,11 +651,11 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * ******************************************* */ override def receive: Receive = { - case TimeoutMarker(gen) ⇒ + case TimeoutMarker(gen) => if (generation == gen) { processMsg(StateTimeout, "state timeout") } - case t @ Timer(name, msg, repeat, gen, owner) ⇒ + case t @ Timer(name, msg, repeat, gen, owner) => if ((owner eq this) && (timers contains name) && (timers(name).generation == gen)) { if (timeoutFuture.isDefined) { timeoutFuture.get.cancel() @@ -649,21 +667,21 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { } processMsg(msg, t) } - case SubscribeTransitionCallBack(actorRef) ⇒ + case SubscribeTransitionCallBack(actorRef) => // TODO Use context.watch(actor) and receive Terminated(actor) to clean up list listeners.add(actorRef) // send current state back as reference point actorRef ! CurrentState(self, currentState.stateName) - case Listen(actorRef) ⇒ + case Listen(actorRef) => // TODO Use context.watch(actor) and receive Terminated(actor) to clean up list listeners.add(actorRef) // send current state back as reference point actorRef ! CurrentState(self, currentState.stateName) - case UnsubscribeTransitionCallBack(actorRef) ⇒ + case UnsubscribeTransitionCallBack(actorRef) => listeners.remove(actorRef) - case Deafen(actorRef) ⇒ + case Deafen(actorRef) => listeners.remove(actorRef) - case value ⇒ { + case value => { if (timeoutFuture.isDefined) { timeoutFuture.get.cancel() timeoutFuture = None @@ -680,7 +698,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { private[akka] def processEvent(event: Event, @unused source: AnyRef): Unit = { val stateFunc = stateFunctions(currentState.stateName) - val nextState = if (stateFunc isDefinedAt event) { + val nextState = if (stateFunc.isDefinedAt(event)) { stateFunc(event) } else { // handleEventDefault ensures that this is always defined @@ -691,9 +709,11 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { private[akka] def applyState(nextState: State): Unit = { nextState.stopReason match { - case None ⇒ makeTransition(nextState) - case _ ⇒ - nextState.replies.reverse foreach { r ⇒ sender() ! r } + case None => makeTransition(nextState) + case _ => + nextState.replies.reverse.foreach { r => + sender() ! r + } terminate(nextState) context.stop(self) } @@ -701,9 +721,11 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { private[akka] def makeTransition(nextState: State): Unit = { if (!stateFunctions.contains(nextState.stateName)) { - terminate(stay withStopReason Failure("Next state %s does not exist".format(nextState.stateName))) + terminate(stay.withStopReason(Failure("Next state %s does not exist".format(nextState.stateName)))) } else { - nextState.replies.reverse foreach { r ⇒ sender() ! r } + nextState.replies.reverse.foreach { r => + sender() ! r + } if (currentState.stateName != nextState.stateName || nextState.notifies) { this.nextState = nextState handleTransition(currentState.stateName, nextState.stateName) @@ -718,9 +740,9 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { } currentState.timeout match { - case SomeMaxFiniteDuration ⇒ // effectively disable stateTimeout - case Some(d: FiniteDuration) if d.length >= 0 ⇒ timeoutFuture = scheduleTimeout(d) - case _ ⇒ + case SomeMaxFiniteDuration => // effectively disable stateTimeout + case Some(d: FiniteDuration) if d.length >= 0 => timeoutFuture = scheduleTimeout(d) + case _ => val timeout = stateTimeouts(currentState.stateName) if (timeout.isDefined) timeoutFuture = scheduleTimeout(timeout.get) } @@ -740,7 +762,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * setting this instance’s state to terminated does no harm during restart * since the new instance will initialize fresh using startWith() */ - terminate(stay withStopReason Shutdown) + terminate(stay.withStopReason(Shutdown)) super.postStop() } @@ -748,7 +770,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { if (currentState.stopReason.isEmpty) { val reason = nextState.stopReason.get logTermination(reason) - for (timer ← timers.values) timer.cancel() + for (timer <- timers.values) timer.cancel() timers.clear() timeoutFuture.foreach { _.cancel() } currentState = nextState @@ -764,9 +786,9 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * types are not logged. It is possible to override this behavior. */ protected def logTermination(reason: Reason): Unit = reason match { - case Failure(ex: Throwable) ⇒ log.error(ex, "terminating due to Failure") - case Failure(msg: AnyRef) ⇒ log.error(msg.toString) - case _ ⇒ + case Failure(ex: Throwable) => log.error(ex, "terminating due to Failure") + case Failure(msg: AnyRef) => log.error(msg.toString) + case _ => } } @@ -776,7 +798,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { * * @since 1.2 */ -trait LoggingFSM[S, D] extends FSM[S, D] { this: Actor ⇒ +trait LoggingFSM[S, D] extends FSM[S, D] { this: Actor => import FSM._ @@ -802,10 +824,10 @@ trait LoggingFSM[S, D] extends FSM[S, D] { this: Actor ⇒ private[akka] abstract override def processEvent(event: Event, source: AnyRef): Unit = { if (debugEvent) { val srcstr = source match { - case s: String ⇒ s - case Timer(name, _, _, _, _) ⇒ "timer " + name - case a: ActorRef ⇒ a.toString - case _ ⇒ "unknown" + case s: String => s + case Timer(name, _, _, _, _) => "timer " + name + case a: ActorRef => a.toString + case _ => "unknown" } log.debug("processing {} from {} in state {}", event, srcstr, stateName) } @@ -830,7 +852,8 @@ trait LoggingFSM[S, D] extends FSM[S, D] { this: Actor ⇒ * The log entries are lost when this actor is restarted. */ protected def getLog: IndexedSeq[LogEntry[S, D]] = { - val log = events zip states filter (_._1 ne null) map (x ⇒ LogEntry(x._2.asInstanceOf[S], x._1.stateData, x._1.event)) + val log = + events.zip(states).filter(_._1 ne null).map(x => LogEntry(x._2.asInstanceOf[S], x._1.stateData, x._1.event)) if (full) { IndexedSeq() ++ log.drop(pos) ++ log.take(pos) } else { diff --git a/akka-actor/src/main/scala/akka/actor/FaultHandling.scala b/akka-actor/src/main/scala/akka/actor/FaultHandling.scala index c97e381835..9442f8e071 100644 --- a/akka-actor/src/main/scala/akka/actor/FaultHandling.scala +++ b/akka-actor/src/main/scala/akka/actor/FaultHandling.scala @@ -6,7 +6,7 @@ package akka.actor import java.lang.reflect.InvocationTargetException import language.implicitConversions -import java.lang.{ Iterable ⇒ JIterable } +import java.lang.{ Iterable => JIterable } import java.util.concurrent.TimeUnit import akka.japi.Util.immutableSeq import akka.util.JavaDurationConverters._ @@ -41,10 +41,10 @@ final case class ChildRestartStats(child: ActorRef, var maxNrOfRetriesCount: Int //FIXME How about making ChildRestartStats immutable and then move these methods into the actual supervisor strategies? def requestRestartPermission(retriesWindow: (Option[Int], Option[Int])): Boolean = retriesWindow match { - case (Some(retries), _) if retries < 1 ⇒ false - case (Some(retries), None) ⇒ { maxNrOfRetriesCount += 1; maxNrOfRetriesCount <= retries } - case (x, Some(window)) ⇒ retriesInWindowOkay(if (x.isDefined) x.get else 1, window) - case (None, _) ⇒ true + case (Some(retries), _) if retries < 1 => false + case (Some(retries), None) => { maxNrOfRetriesCount += 1; maxNrOfRetriesCount <= retries } + case (x, Some(window)) => retriesInWindowOkay(if (x.isDefined) x.get else 1, window) + case (None, _) => true } private def retriesInWindowOkay(retries: Int, window: Int): Boolean = { @@ -89,7 +89,7 @@ final class StoppingSupervisorStrategy extends SupervisorStrategyConfigurator { override def create(): SupervisorStrategy = SupervisorStrategy.stoppingStrategy } -trait SupervisorStrategyLowPriorityImplicits { this: SupervisorStrategy.type ⇒ +trait SupervisorStrategyLowPriorityImplicits { this: SupervisorStrategy.type => /** * Implicit conversion from `Seq` of Cause-Directive pairs to a `Decider`. See makeDecider(causeDirective). @@ -156,10 +156,10 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits { * The error is escalated if it's a `Throwable`, i.e. `Error`. */ final val defaultDecider: Decider = { - case _: ActorInitializationException ⇒ Stop - case _: ActorKilledException ⇒ Stop - case _: DeathPactException ⇒ Stop - case _: Exception ⇒ Restart + case _: ActorInitializationException => Stop + case _: ActorKilledException => Stop + case _: DeathPactException => Stop + case _: Exception => Restart } /** @@ -177,7 +177,7 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits { */ final val stoppingStrategy: SupervisorStrategy = { def stoppingDecider: Decider = { - case _: Exception ⇒ Stop + case _: Exception => Stop } OneForOneStrategy()(stoppingDecider) } @@ -197,7 +197,7 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits { * the given Throwables matches the cause and restarts, otherwise escalates. */ def makeDecider(trapExit: immutable.Seq[Class[_ <: Throwable]]): Decider = { - case x ⇒ if (trapExit exists (_ isInstance x)) Restart else Escalate + case x => if (trapExit exists (_ isInstance x)) Restart else Escalate } /** @@ -215,13 +215,13 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits { def makeDecider(flat: Iterable[CauseDirective]): Decider = { val directives = sort(flat) - { case x ⇒ directives collectFirst { case (c, d) if c isInstance x ⇒ d } getOrElse Escalate } + { case x => directives collectFirst { case (c, d) if c isInstance x => d } getOrElse Escalate } } /** * Converts a Java Decider into a Scala Decider */ - def makeDecider(func: JDecider): Decider = { case x ⇒ func(x) } + def makeDecider(func: JDecider): Decider = { case x => func(x) } /** * Sort so that subtypes always precede their supertypes, but without @@ -230,10 +230,10 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits { * INTERNAL API */ private[akka] def sort(in: Iterable[CauseDirective]): immutable.Seq[CauseDirective] = - in.foldLeft(new ArrayBuffer[CauseDirective](in.size)) { (buf, ca) ⇒ + in.foldLeft(new ArrayBuffer[CauseDirective](in.size)) { (buf, ca) => buf.indexWhere(_._1 isAssignableFrom ca._1) match { - case -1 ⇒ buf append ca - case x ⇒ buf insert (x, ca) + case -1 => buf append ca + case x => buf insert (x, ca) } buf }.to(immutable.IndexedSeq) @@ -244,7 +244,7 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits { private[akka] def maxNrOfRetriesOption(maxNrOfRetries: Int): Option[Int] = if (maxNrOfRetries < 0) None else Some(maxNrOfRetries) - private[akka] val escalateDefault = (_: Any) ⇒ Escalate + private[akka] val escalateDefault = (_: Any) => Escalate } /** @@ -298,19 +298,19 @@ abstract class SupervisorStrategy { def handleFailure(context: ActorContext, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Boolean = { val directive = decider.applyOrElse(cause, escalateDefault) directive match { - case Resume ⇒ + case Resume => logFailure(context, child, cause, directive) resumeChild(child, cause) true - case Restart ⇒ + case Restart => logFailure(context, child, cause, directive) processFailure(context, true, child, cause, stats, children) true - case Stop ⇒ + case Stop => logFailure(context, child, cause, directive) processFailure(context, false, child, cause, stats, children) true - case Escalate ⇒ + case Escalate => logFailure(context, child, cause, directive) false } @@ -332,22 +332,22 @@ abstract class SupervisorStrategy { def logFailure(context: ActorContext, child: ActorRef, cause: Throwable, decision: Directive): Unit = if (loggingEnabled) { val logMessage = cause match { - case e: ActorInitializationException if e.getCause ne null ⇒ e.getCause match { - case ex: InvocationTargetException if ex.getCause ne null ⇒ ex.getCause.getMessage - case ex ⇒ ex.getMessage + case e: ActorInitializationException if e.getCause ne null => e.getCause match { + case ex: InvocationTargetException if ex.getCause ne null => ex.getCause.getMessage + case ex => ex.getMessage } - case e ⇒ e.getMessage + case e => e.getMessage } decision match { - case Resume ⇒ publish(context, Warning(child.path.toString, getClass, logMessage)) - case Escalate ⇒ // don't log here - case _ ⇒ publish(context, Error(cause, child.path.toString, getClass, logMessage)) + case Resume => publish(context, Warning(child.path.toString, getClass, logMessage)) + case Escalate => // don't log here + case _ => publish(context, Error(cause, child.path.toString, getClass, logMessage)) } } // logging is not the main purpose, and if it fails there’s nothing we can do private def publish(context: ActorContext, logEvent: LogEvent): Unit = - try context.system.eventStream.publish(logEvent) catch { case NonFatal(_) ⇒ } + try context.system.eventStream.publish(logEvent) catch { case NonFatal(_) => } /** * Resume the previously failed child: do never apply this to a child which @@ -466,9 +466,9 @@ case class AllForOneStrategy( def processFailure(context: ActorContext, restart: Boolean, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Unit = { if (children.nonEmpty) { if (restart && children.forall(_.requestRestartPermission(retriesWindow))) - children foreach (crs ⇒ restartChild(crs.child, cause, suspendFirst = (crs.child != child))) + children foreach (crs => restartChild(crs.child, cause, suspendFirst = (crs.child != child))) else - for (c ← children) context.stop(c.child) + for (c <- children) context.stop(c.child) } } } diff --git a/akka-actor/src/main/scala/akka/actor/IndirectActorProducer.scala b/akka-actor/src/main/scala/akka/actor/IndirectActorProducer.scala index f768336cb4..2fcc780dea 100644 --- a/akka-actor/src/main/scala/akka/actor/IndirectActorProducer.scala +++ b/akka-actor/src/main/scala/akka/actor/IndirectActorProducer.scala @@ -47,13 +47,13 @@ private[akka] object IndirectActorProducer { // The cost of doing reflection to create these for every props // is rather high, so we match on them and do new instead clazz match { - case TypedCreatorFunctionConsumerClass ⇒ + case TypedCreatorFunctionConsumerClass => new TypedCreatorFunctionConsumer(get1stArg, get2ndArg) - case CreatorFunctionConsumerClass ⇒ + case CreatorFunctionConsumerClass => new CreatorFunctionConsumer(get1stArg) - case CreatorConsumerClass ⇒ + case CreatorConsumerClass => new CreatorConsumer(get1stArg, get2ndArg) - case _ ⇒ + case _ => Reflect.instantiate(clazz, args).asInstanceOf[IndirectActorProducer] } } else if (classOf[Actor].isAssignableFrom(clazz)) { @@ -66,7 +66,7 @@ private[akka] object IndirectActorProducer { /** * INTERNAL API */ -private[akka] class CreatorFunctionConsumer(creator: () ⇒ Actor) extends IndirectActorProducer { +private[akka] class CreatorFunctionConsumer(creator: () => Actor) extends IndirectActorProducer { override def actorClass = classOf[Actor] override def produce() = creator() } @@ -82,7 +82,7 @@ private[akka] class CreatorConsumer(clazz: Class[_ <: Actor], creator: Creator[A /** * INTERNAL API */ -private[akka] class TypedCreatorFunctionConsumer(clz: Class[_ <: Actor], creator: () ⇒ Actor) extends IndirectActorProducer { +private[akka] class TypedCreatorFunctionConsumer(clz: Class[_ <: Actor], creator: () => Actor) extends IndirectActorProducer { override def actorClass = clz override def produce() = creator() } diff --git a/akka-actor/src/main/scala/akka/actor/LightArrayRevolverScheduler.scala b/akka-actor/src/main/scala/akka/actor/LightArrayRevolverScheduler.scala index 2a533246b7..86d7a00391 100644 --- a/akka-actor/src/main/scala/akka/actor/LightArrayRevolverScheduler.scala +++ b/akka-actor/src/main/scala/akka/actor/LightArrayRevolverScheduler.scala @@ -15,7 +15,7 @@ import scala.util.control.{ NonFatal } import com.typesafe.config.Config import akka.event.LoggingAdapter import akka.util.Helpers -import akka.util.Unsafe.{ instance ⇒ unsafe } +import akka.util.Unsafe.{ instance => unsafe } import akka.dispatch.AbstractNodeQueue /** @@ -45,7 +45,7 @@ class LightArrayRevolverScheduler( val WheelSize = config.getInt("akka.scheduler.ticks-per-wheel") - .requiring(ticks ⇒ (ticks & (ticks - 1)) == 0, "ticks-per-wheel must be a power of 2") + .requiring(ticks => (ticks & (ticks - 1)) == 0, "ticks-per-wheel must be a power of 2") val TickDuration = config.getMillisDuration("akka.scheduler.tick-duration") .requiring(_ >= 10.millis || !Helpers.isWindows, "minimum supported akka.scheduler.tick-duration on Windows is 10ms") @@ -83,7 +83,7 @@ class LightArrayRevolverScheduler( // see http://www.javamex.com/tutorials/threads/sleep_issues.shtml val sleepMs = if (Helpers.isWindows) (nanos + 4999999) / 10000000 * 10 else (nanos + 999999) / 1000000 try Thread.sleep(sleepMs) catch { - case _: InterruptedException ⇒ Thread.currentThread.interrupt() // we got woken up + case _: InterruptedException => Thread.currentThread.interrupt() // we got woken up } } @@ -92,7 +92,7 @@ class LightArrayRevolverScheduler( delay: FiniteDuration, runnable: Runnable)(implicit executor: ExecutionContext): Cancellable = { checkMaxDelay(roundUp(delay).toNanos) - try new AtomicReference[Cancellable](InitialRepeatMarker) with Cancellable { self ⇒ + try new AtomicReference[Cancellable](InitialRepeatMarker) with Cancellable { self => compareAndSet(InitialRepeatMarker, schedule( executor, new AtomicLong(clock() + initialDelay.toNanos) with Runnable { @@ -103,22 +103,22 @@ class LightArrayRevolverScheduler( if (self.get != null) swap(schedule(executor, this, Duration.fromNanos(Math.max(delay.toNanos - driftNanos, 1)))) } catch { - case _: SchedulerException ⇒ // ignore failure to enqueue or terminated target actor + case _: SchedulerException => // ignore failure to enqueue or terminated target actor } } }, roundUp(initialDelay))) @tailrec private def swap(c: Cancellable): Unit = { get match { - case null ⇒ if (c != null) c.cancel() - case old ⇒ if (!compareAndSet(old, c)) swap(c) + case null => if (c != null) c.cancel() + case old => if (!compareAndSet(old, c)) swap(c) } } @tailrec final def cancel(): Boolean = { get match { - case null ⇒ false - case c ⇒ + case null => false + case c => if (c.cancel()) compareAndSet(c, null) else compareAndSet(c, null) || cancel() } @@ -126,22 +126,22 @@ class LightArrayRevolverScheduler( override def isCancelled: Boolean = get == null } catch { - case SchedulerException(msg) ⇒ throw new IllegalStateException(msg) + case SchedulerException(msg) => throw new IllegalStateException(msg) } } override def scheduleOnce(delay: FiniteDuration, runnable: Runnable)(implicit executor: ExecutionContext): Cancellable = try schedule(executor, runnable, roundUp(delay)) catch { - case SchedulerException(msg) ⇒ throw new IllegalStateException(msg) + case SchedulerException(msg) => throw new IllegalStateException(msg) } override def close(): Unit = Await.result(stop(), getShutdownTimeout) foreach { - task ⇒ + task => try task.run() catch { - case e: InterruptedException ⇒ throw e - case _: SchedulerException ⇒ // ignore terminated actors - case NonFatal(e) ⇒ log.error(e, "exception while executing timer task") + case e: InterruptedException => throw e + case _: SchedulerException => // ignore terminated actors + case NonFatal(e) => log.error(e, "exception while executing timer task") } } @@ -202,20 +202,20 @@ class LightArrayRevolverScheduler( private def clearAll(): immutable.Seq[TimerTask] = { @tailrec def collect(q: TaskQueue, acc: Vector[TimerTask]): Vector[TimerTask] = { q.poll() match { - case null ⇒ acc - case x ⇒ collect(q, acc :+ x) + case null => acc + case x => collect(q, acc :+ x) } } - ((0 until WheelSize) flatMap (i ⇒ collect(wheel(i), Vector.empty))) ++ collect(queue, Vector.empty) + ((0 until WheelSize) flatMap (i => collect(wheel(i), Vector.empty))) ++ collect(queue, Vector.empty) } @tailrec private def checkQueue(time: Long): Unit = queue.pollNode() match { - case null ⇒ () - case node ⇒ + case null => () + case node => node.value.ticks match { - case 0 ⇒ node.value.executeTask() - case ticks ⇒ + case 0 => node.value.executeTask() + case ticks => val futureTick = (( time - start + // calculate the nanos since timer start (ticks * tickNanos) + // adding the desired delay @@ -234,21 +234,21 @@ class LightArrayRevolverScheduler( override final def run = try nextTick() catch { - case t: Throwable ⇒ + case t: Throwable => log.error(t, "exception on LARS’ timer thread") stopped.get match { - case null ⇒ + case null => val thread = threadFactory.newThread(this) log.info("starting new LARS thread") try thread.start() catch { - case e: Throwable ⇒ + case e: Throwable => log.error(e, "LARS cannot start new thread, ship’s going down!") stopped.set(Promise successful Nil) clearAll() } timerThread = thread - case p ⇒ + case p => assert(stopped.compareAndSet(p, Promise successful Nil), "Stop signal violated in LARS") p success clearAll() } @@ -269,8 +269,8 @@ class LightArrayRevolverScheduler( val putBack = new TaskQueue @tailrec def executeBucket(): Unit = tasks.pollNode() match { - case null ⇒ () - case node ⇒ + case null => () + case node => val task = node.value if (!task.isCancelled) { if (task.ticks >= WheelSize) { @@ -287,8 +287,8 @@ class LightArrayRevolverScheduler( totalTick += 1 } stopped.get match { - case null ⇒ nextTick() - case p ⇒ + case null => nextTick() + case p => assert(stopped.compareAndSet(p, Promise successful Nil), "Stop signal violated in LARS") p success clearAll() } @@ -317,19 +317,19 @@ object LightArrayRevolverScheduler { @tailrec private final def extractTask(replaceWith: Runnable): Runnable = task match { - case t @ (ExecutedTask | CancelledTask) ⇒ t - case x ⇒ if (unsafe.compareAndSwapObject(this, taskOffset, x, replaceWith)) x else extractTask(replaceWith) + case t @ (ExecutedTask | CancelledTask) => t + case x => if (unsafe.compareAndSwapObject(this, taskOffset, x, replaceWith)) x else extractTask(replaceWith) } private[akka] final def executeTask(): Boolean = extractTask(ExecutedTask) match { - case ExecutedTask | CancelledTask ⇒ false - case other ⇒ + case ExecutedTask | CancelledTask => false + case other => try { executionContext execute other true } catch { - case _: InterruptedException ⇒ { Thread.currentThread.interrupt(); false } - case NonFatal(e) ⇒ { executionContext.reportFailure(e); false } + case _: InterruptedException => { Thread.currentThread.interrupt(); false } + case NonFatal(e) => { executionContext.reportFailure(e); false } } } @@ -337,8 +337,8 @@ object LightArrayRevolverScheduler { override def run(): Unit = extractTask(ExecutedTask).run() override def cancel(): Boolean = extractTask(CancelledTask) match { - case ExecutedTask | CancelledTask ⇒ false - case _ ⇒ true + case ExecutedTask | CancelledTask => false + case _ => true } override def isCancelled: Boolean = task eq CancelledTask diff --git a/akka-actor/src/main/scala/akka/actor/Props.scala b/akka-actor/src/main/scala/akka/actor/Props.scala index b1d3f9df79..373b7a0e6d 100644 --- a/akka-actor/src/main/scala/akka/actor/Props.scala +++ b/akka-actor/src/main/scala/akka/actor/Props.scala @@ -23,7 +23,7 @@ object Props extends AbstractProps { /** * The defaultCreator, simply throws an UnsupportedOperationException when applied, which is used when creating a Props */ - final val defaultCreator: () ⇒ Actor = () ⇒ throw new UnsupportedOperationException("No actor creator specified!") + final val defaultCreator: () => Actor = () => throw new UnsupportedOperationException("No actor creator specified!") /** * The defaultRoutedProps is NoRouter which is used when creating a Props @@ -73,10 +73,10 @@ object Props extends AbstractProps { * Instead you must create a named class that mixin the trait, * e.g. `class MyActor extends Actor with Stash`. */ - def apply[T <: Actor: ClassTag](creator: ⇒ T): Props = - mkProps(implicitly[ClassTag[T]].runtimeClass, () ⇒ creator) + def apply[T <: Actor: ClassTag](creator: => T): Props = + mkProps(implicitly[ClassTag[T]].runtimeClass, () => creator) - private def mkProps(classOfActor: Class[_], ctor: () ⇒ Actor): Props = + private def mkProps(classOfActor: Class[_], ctor: () => Actor): Props = Props(classOf[TypedCreatorFunctionConsumer], classOfActor, ctor) /** @@ -147,8 +147,8 @@ final case class Props(deploy: Deploy, clazz: Class[_], args: immutable.Seq[Any] * contained [[Deploy]] instance. */ def dispatcher: String = deploy.dispatcher match { - case NoDispatcherGiven ⇒ Dispatchers.DefaultDispatcherId - case x ⇒ x + case NoDispatcherGiven => Dispatchers.DefaultDispatcherId + case x => x } /** @@ -156,8 +156,8 @@ final case class Props(deploy: Deploy, clazz: Class[_], args: immutable.Seq[Any] * contained [[Deploy]] instance. */ def mailbox: String = deploy.mailbox match { - case NoMailboxGiven ⇒ Mailboxes.DefaultMailboxId - case x ⇒ x + case NoMailboxGiven => Mailboxes.DefaultMailboxId + case x => x } /** @@ -170,16 +170,16 @@ final case class Props(deploy: Deploy, clazz: Class[_], args: immutable.Seq[Any] * Returns a new Props with the specified dispatcher set. */ def withDispatcher(d: String): Props = deploy.dispatcher match { - case NoDispatcherGiven ⇒ copy(deploy = deploy.copy(dispatcher = d)) - case x ⇒ if (x == d) this else copy(deploy = deploy.copy(dispatcher = d)) + case NoDispatcherGiven => copy(deploy = deploy.copy(dispatcher = d)) + case x => if (x == d) this else copy(deploy = deploy.copy(dispatcher = d)) } /** * Returns a new Props with the specified mailbox set. */ def withMailbox(m: String): Props = deploy.mailbox match { - case NoMailboxGiven ⇒ copy(deploy = deploy.copy(mailbox = m)) - case x ⇒ if (x == m) this else copy(deploy = deploy.copy(mailbox = m)) + case NoMailboxGiven => copy(deploy = deploy.copy(mailbox = m)) + case x => if (x == m) this else copy(deploy = deploy.copy(mailbox = m)) } /** diff --git a/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala b/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala index 4d9b844437..c7838f4dfe 100644 --- a/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala +++ b/akka-actor/src/main/scala/akka/actor/ReflectiveDynamicAccess.scala @@ -33,26 +33,26 @@ class ReflectiveDynamicAccess(val classLoader: ClassLoader) extends DynamicAcces val obj = constructor.newInstance(values: _*) val t = implicitly[ClassTag[T]].runtimeClass if (t.isInstance(obj)) obj.asInstanceOf[T] else throw new ClassCastException(clazz.getName + " is not a subtype of " + t) - } recover { case i: InvocationTargetException if i.getTargetException ne null ⇒ throw i.getTargetException } + } recover { case i: InvocationTargetException if i.getTargetException ne null => throw i.getTargetException } override def createInstanceFor[T: ClassTag](fqcn: String, args: immutable.Seq[(Class[_], AnyRef)]): Try[T] = - getClassFor(fqcn) flatMap { c ⇒ createInstanceFor(c, args) } + getClassFor(fqcn) flatMap { c => createInstanceFor(c, args) } override def getObjectFor[T: ClassTag](fqcn: String): Try[T] = { val classTry = if (fqcn.endsWith("$")) getClassFor(fqcn) - else getClassFor(fqcn + "$") recoverWith { case _ ⇒ getClassFor(fqcn) } - classTry flatMap { c ⇒ + else getClassFor(fqcn + "$") recoverWith { case _ => getClassFor(fqcn) } + classTry flatMap { c => Try { val module = c.getDeclaredField("MODULE$") module.setAccessible(true) val t = implicitly[ClassTag[T]].runtimeClass module.get(null) match { - case null ⇒ throw new NullPointerException - case x if !t.isInstance(x) ⇒ throw new ClassCastException(fqcn + " is not a subtype of " + t) - case x: T ⇒ x + case null => throw new NullPointerException + case x if !t.isInstance(x) => throw new ClassCastException(fqcn + " is not a subtype of " + t) + case x: T => x } - } recover { case i: InvocationTargetException if i.getTargetException ne null ⇒ throw i.getTargetException } + } recover { case i: InvocationTargetException if i.getTargetException ne null => throw i.getTargetException } } } } diff --git a/akka-actor/src/main/scala/akka/actor/RepointableActorRef.scala b/akka-actor/src/main/scala/akka/actor/RepointableActorRef.scala index 06163562ec..47704f6ce8 100644 --- a/akka-actor/src/main/scala/akka/actor/RepointableActorRef.scala +++ b/akka-actor/src/main/scala/akka/actor/RepointableActorRef.scala @@ -4,7 +4,7 @@ package akka.actor -import java.util.{ LinkedList ⇒ JLinkedList } +import java.util.{ LinkedList => JLinkedList } import java.util.concurrent.locks.ReentrantLock import scala.annotation.tailrec @@ -73,13 +73,13 @@ private[akka] class RepointableActorRef( */ def initialize(async: Boolean): this.type = underlying match { - case null ⇒ + case null => swapCell(new UnstartedCell(system, this, props, supervisor)) swapLookup(underlying) supervisor.sendSystemMessage(Supervise(this, async)) if (!async) point(false) this - case _ ⇒ throw new IllegalStateException("initialize called more than once!") + case _ => throw new IllegalStateException("initialize called more than once!") } /** @@ -90,11 +90,11 @@ private[akka] class RepointableActorRef( */ def point(catchFailures: Boolean): this.type = underlying match { - case u: UnstartedCell ⇒ + case u: UnstartedCell => val cell = try newCell(u) catch { - case NonFatal(ex) if catchFailures ⇒ + case NonFatal(ex) if catchFailures => val safeDispatcher = system.dispatchers.defaultGlobalDispatcher new ActorCell(system, this, props, safeDispatcher, supervisor).initWithFailure(ex) } @@ -109,8 +109,8 @@ private[akka] class RepointableActorRef( cell.start() u.replaceWith(cell) this - case null ⇒ throw new IllegalStateException("underlying cell is null") - case _ ⇒ this // this happens routinely for things which were created async=false + case null => throw new IllegalStateException("underlying cell is null") + case _ => this // this happens routinely for things which were created async=false } /** @@ -131,9 +131,9 @@ private[akka] class RepointableActorRef( def restart(cause: Throwable): Unit = underlying.restart(cause) def isStarted: Boolean = underlying match { - case _: UnstartedCell ⇒ false - case null ⇒ throw new IllegalStateException("isStarted called before initialized") - case _ ⇒ true + case _: UnstartedCell => false + case null => throw new IllegalStateException("isStarted called before initialized") + case _ => true } @deprecated("Use context.watch(actor) and receive Terminated(actor)", "2.2") def isTerminated: Boolean = underlying.isTerminated @@ -147,16 +147,16 @@ private[akka] class RepointableActorRef( def getChild(name: Iterator[String]): InternalActorRef = if (name.hasNext) { name.next match { - case ".." ⇒ getParent.getChild(name) - case "" ⇒ getChild(name) - case other ⇒ + case ".." => getParent.getChild(name) + case "" => getChild(name) + case other => val (childName, uid) = ActorCell.splitNameAndUid(other) lookup.getChildByName(childName) match { - case Some(crs: ChildRestartStats) if uid == ActorCell.undefinedUid || uid == crs.uid ⇒ + case Some(crs: ChildRestartStats) if uid == ActorCell.undefinedUid || uid == crs.uid => crs.child.asInstanceOf[InternalActorRef].getChild(name) - case _ ⇒ lookup match { - case ac: ActorCell ⇒ ac.getFunctionRefOrNobody(childName, uid) - case _ ⇒ Nobody + case _ => lookup match { + case ac: ActorCell => ac.getFunctionRefOrNobody(childName, uid) + case _ => Nobody } } } @@ -196,7 +196,7 @@ private[akka] class UnstartedCell( // ACCESS MUST BE PROTECTED BY THE LOCK private[this] var sysmsgQueue: LatestFirstSystemMessageList = SystemMessageList.LNil - import systemImpl.settings.UnstartedPushTimeout.{ duration ⇒ timeout } + import systemImpl.settings.UnstartedPushTimeout.{ duration => timeout } def replaceWith(cell: Cell): Unit = locked { try { @@ -285,7 +285,7 @@ private[akka] class UnstartedCell( if (cellIsReady(cell)) cell.numberOfMessages else queue.size } - private[this] final def locked[T](body: ⇒ T): T = { + private[this] final def locked[T](body: => T): T = { lock.lock() try body finally lock.unlock() } diff --git a/akka-actor/src/main/scala/akka/actor/Scheduler.scala b/akka-actor/src/main/scala/akka/actor/Scheduler.scala index 93005b15b5..1c8eed8a89 100644 --- a/akka-actor/src/main/scala/akka/actor/Scheduler.scala +++ b/akka-actor/src/main/scala/akka/actor/Scheduler.scala @@ -96,7 +96,7 @@ trait Scheduler { */ final def schedule( initialDelay: FiniteDuration, - interval: FiniteDuration)(f: ⇒ Unit)( + interval: FiniteDuration)(f: => Unit)( implicit executor: ExecutionContext): Cancellable = schedule(initialDelay, interval, new Runnable { override def run(): Unit = f }) @@ -199,7 +199,7 @@ trait Scheduler { * * Scala API */ - final def scheduleOnce(delay: FiniteDuration)(f: ⇒ Unit)( + final def scheduleOnce(delay: FiniteDuration)(f: => Unit)( implicit executor: ExecutionContext): Cancellable = scheduleOnce(delay, new Runnable { override def run(): Unit = f }) diff --git a/akka-actor/src/main/scala/akka/actor/Stash.scala b/akka-actor/src/main/scala/akka/actor/Stash.scala index 58a2a71f48..4360ddb987 100644 --- a/akka-actor/src/main/scala/akka/actor/Stash.scala +++ b/akka-actor/src/main/scala/akka/actor/Stash.scala @@ -19,17 +19,17 @@ import scala.util.control.NoStackTrace *
  *    class ActorWithProtocol extends Actor with Stash {
  *      def receive = {
- *        case "open" ⇒
+ *        case "open" =>
  *          unstashAll()
  *          context.become({
- *            case "write" ⇒ // do writing...
- *            case "close" ⇒
+ *            case "write" => // do writing...
+ *            case "close" =>
  *              unstashAll()
  *              context.unbecome()
- *            case msg ⇒ stash()
+ *            case msg => stash()
  *          }, discardOld = false)
- *        case "done" ⇒ // done
- *        case msg    ⇒ stash()
+ *        case "done" => // done
+ *        case msg    => stash()
  *      }
  *    }
  *  
@@ -88,7 +88,7 @@ trait UnrestrictedStash extends Actor with StashSupport { * * @see [[StashSupport]] */ -private[akka] trait StashFactory { this: Actor ⇒ +private[akka] trait StashFactory { this: Actor => private[akka] def createStash()(implicit ctx: ActorContext, ref: ActorRef): StashSupport = new StashSupport { def context: ActorContext = ctx def self: ActorRef = ref @@ -137,8 +137,8 @@ private[akka] trait StashSupport { */ private[akka] val mailbox: DequeBasedMessageQueueSemantics = { actorCell.mailbox.messageQueue match { - case queue: DequeBasedMessageQueueSemantics ⇒ queue - case other ⇒ throw ActorInitializationException(self, s"DequeBasedMailbox required, got: ${other.getClass.getName}\n" + + case queue: DequeBasedMessageQueueSemantics => queue + case other => throw ActorInitializationException(self, s"DequeBasedMailbox required, got: ${other.getClass.getName}\n" + """An (unbounded) deque-based mailbox can be configured as follows: | my-custom-mailbox { | mailbox-type = "akka.dispatch.UnboundedDequeBasedMailbox" @@ -168,7 +168,7 @@ private[akka] trait StashSupport { * small `others`. */ private[akka] def prepend(others: immutable.Seq[Envelope]): Unit = - theStash = others.foldRight(theStash)((e, s) ⇒ e +: s) + theStash = others.foldRight(theStash)((e, s) => e +: s) /** * Prepends the oldest message in the stash to the mailbox, and then removes that @@ -196,7 +196,7 @@ private[akka] trait StashSupport { * * The stash is guaranteed to be empty after calling `unstashAll()`. */ - def unstashAll(): Unit = unstashAll(_ ⇒ true) + def unstashAll(): Unit = unstashAll(_ => true) /** * INTERNAL API. @@ -213,9 +213,9 @@ private[akka] trait StashSupport { * @param filterPredicate only stashed messages selected by this predicate are * prepended to the mailbox. */ - private[akka] def unstashAll(filterPredicate: Any ⇒ Boolean): Unit = { + private[akka] def unstashAll(filterPredicate: Any => Boolean): Unit = { try { - val i = theStash.reverseIterator.filter(envelope ⇒ filterPredicate(envelope.message)) + val i = theStash.reverseIterator.filter(envelope => filterPredicate(envelope.message)) while (i.hasNext) enqueueFirst(i.next()) } finally { theStash = Vector.empty[Envelope] @@ -241,8 +241,8 @@ private[akka] trait StashSupport { private def enqueueFirst(envelope: Envelope): Unit = { mailbox.enqueueFirst(self, envelope) envelope.message match { - case Terminated(ref) ⇒ actorCell.terminatedQueuedFor(ref) - case _ ⇒ + case Terminated(ref) => actorCell.terminatedQueuedFor(ref) + case _ => } } } diff --git a/akka-actor/src/main/scala/akka/actor/Timers.scala b/akka-actor/src/main/scala/akka/actor/Timers.scala index 8e5c0d74b2..df003301b6 100644 --- a/akka-actor/src/main/scala/akka/actor/Timers.scala +++ b/akka-actor/src/main/scala/akka/actor/Timers.scala @@ -39,19 +39,19 @@ trait Timers extends Actor { override protected[akka] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = { msg match { - case timerMsg: TimerSchedulerImpl.TimerMsg ⇒ + case timerMsg: TimerSchedulerImpl.TimerMsg => _timers.interceptTimerMsg(timerMsg) match { - case OptionVal.Some(m: AutoReceivedMessage) ⇒ + case OptionVal.Some(m: AutoReceivedMessage) => context.asInstanceOf[ActorCell].autoReceiveMessage(Envelope(m, self)) - case OptionVal.Some(m) ⇒ + case OptionVal.Some(m) => if (this.isInstanceOf[Stash]) { // this is important for stash interaction, as stash will look directly at currentMessage #24557 actorCell.currentMessage = actorCell.currentMessage.copy(message = m) } super.aroundReceive(receive, m) - case OptionVal.None ⇒ // discard + case OptionVal.None => // discard } - case _ ⇒ + case _ => super.aroundReceive(receive, msg) } } diff --git a/akka-actor/src/main/scala/akka/actor/TypedActor.scala b/akka-actor/src/main/scala/akka/actor/TypedActor.scala index d378ad7fcc..51cc6febf2 100644 --- a/akka-actor/src/main/scala/akka/actor/TypedActor.scala +++ b/akka-actor/src/main/scala/akka/actor/TypedActor.scala @@ -10,13 +10,13 @@ import scala.collection.immutable import scala.concurrent.duration.FiniteDuration import scala.reflect.ClassTag import scala.concurrent.{ Await, Future } -import akka.japi.{ Creator, Option ⇒ JOption } +import akka.japi.{ Creator, Option => JOption } import akka.japi.Util.{ immutableSeq, immutableSingletonSeq } import akka.util.Timeout import akka.util.Reflect.instantiator import akka.serialization.{ JavaSerializer, SerializationExtension, Serializers } import akka.dispatch._ -import java.util.concurrent.atomic.{ AtomicReference ⇒ AtomVar } +import java.util.concurrent.atomic.{ AtomicReference => AtomVar } import java.util.concurrent.TimeoutException import java.io.ObjectStreamException import java.lang.reflect.{ InvocationHandler, InvocationTargetException, Method, Proxy } @@ -43,8 +43,8 @@ trait TypedActorFactory { * if any, returns whether it could find the find the ActorRef or not */ def stop(proxy: AnyRef): Boolean = getActorRefFor(proxy) match { - case null ⇒ false - case ref ⇒ ref.asInstanceOf[InternalActorRef].stop; true + case null => false + case ref => ref.asInstanceOf[InternalActorRef].stop; true } /** @@ -52,8 +52,8 @@ trait TypedActorFactory { * if any, returns whether it could find the find the ActorRef or not */ def poisonPill(proxy: AnyRef): Boolean = getActorRefFor(proxy) match { - case null ⇒ false - case ref ⇒ ref ! PoisonPill; true + case null => false + case ref => ref ! PoisonPill; true } /** @@ -140,19 +140,19 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi */ def apply(instance: AnyRef): AnyRef = try { parameters match { - case null ⇒ method.invoke(instance) - case args if args.length == 0 ⇒ method.invoke(instance) - case args ⇒ method.invoke(instance, args: _*) + case null => method.invoke(instance) + case args if args.length == 0 => method.invoke(instance) + case args => method.invoke(instance, args: _*) } - } catch { case i: InvocationTargetException ⇒ throw i.getTargetException } + } catch { case i: InvocationTargetException => throw i.getTargetException } @throws(classOf[ObjectStreamException]) private def writeReplace(): AnyRef = parameters match { - case null ⇒ SerializedMethodCall(method.getDeclaringClass, method.getName, method.getParameterTypes, null) - case ps if ps.length == 0 ⇒ SerializedMethodCall(method.getDeclaringClass, method.getName, method.getParameterTypes, Array()) - case ps ⇒ + case null => SerializedMethodCall(method.getDeclaringClass, method.getName, method.getParameterTypes, null) + case ps if ps.length == 0 => SerializedMethodCall(method.getDeclaringClass, method.getName, method.getParameterTypes, Array()) + case ps => val serialization = SerializationExtension(akka.serialization.JavaSerializer.currentSystem.value) val serializedParameters = new Array[(Int, String, Array[Byte])](ps.length) - for (i ← 0 until ps.length) { + for (i <- 0 until ps.length) { val p = ps(i) val s = serialization.findSerializerFor(p) val m = Serializers.manifestFor(s, p) @@ -179,11 +179,11 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi " Use akka.serialization.JavaSerializer.currentSystem.withValue(system) { ... }") val serialization = SerializationExtension(system) MethodCall(ownerType.getDeclaredMethod(methodName, parameterTypes: _*), serializedParameters match { - case null ⇒ null - case a if a.length == 0 ⇒ Array[AnyRef]() - case a ⇒ + case null => null + case a if a.length == 0 => Array[AnyRef]() + case a => val deserializedParameters: Array[AnyRef] = new Array[AnyRef](a.length) //Mutable for the sake of sanity - for (i ← 0 until a.length) { + for (i <- 0 until a.length) { val (sId, manifest, bytes) = a(i) deserializedParameters(i) = serialization.deserialize(bytes, sId, manifest).get } @@ -219,16 +219,16 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi * Throws ClassCastException if the supplied type T isn't the type of the proxy associated with this TypedActor. */ def self[T <: AnyRef] = selfReference.get.asInstanceOf[T] match { - case null ⇒ throw new IllegalStateException("Calling TypedActor.self outside of a TypedActor implementation method!") - case some ⇒ some + case null => throw new IllegalStateException("Calling TypedActor.self outside of a TypedActor implementation method!") + case some => some } /** * Returns the ActorContext (for a TypedActor) when inside a method call in a TypedActor. */ def context: ActorContext = currentContext.get match { - case null ⇒ throw new IllegalStateException("Calling TypedActor.context outside of a TypedActor implementation method!") - case some ⇒ some + case null => throw new IllegalStateException("Calling TypedActor.context outside of a TypedActor implementation method!") + case some => some } /** @@ -241,7 +241,7 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi * * Implementation of TypedActor as an Actor */ - private[akka] class TypedActor[R <: AnyRef, T <: R](val proxyVar: AtomVar[R], createInstance: ⇒ T, interfaces: immutable.Seq[Class[_]]) extends Actor { + private[akka] class TypedActor[R <: AnyRef, T <: R](val proxyVar: AtomVar[R], createInstance: => T, interfaces: immutable.Seq[Class[_]]) extends Actor { // if we were remote deployed we need to create a local proxy if (!context.parent.asInstanceOf[InternalActorRef].isLocal) TypedActor.get(context.system).createActorRefProxy( @@ -250,28 +250,28 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi private val me = withContext[T](createInstance) override def supervisorStrategy: SupervisorStrategy = me match { - case l: Supervisor ⇒ l.supervisorStrategy - case _ ⇒ super.supervisorStrategy + case l: Supervisor => l.supervisorStrategy + case _ => super.supervisorStrategy } override def preStart(): Unit = withContext { me match { - case l: PreStart ⇒ l.preStart() - case _ ⇒ super.preStart() + case l: PreStart => l.preStart() + case _ => super.preStart() } } override def postStop(): Unit = try { withContext { me match { - case l: PostStop ⇒ l.postStop() - case _ ⇒ super.postStop() + case l: PostStop => l.postStop() + case _ => super.postStop() } } } finally { TypedActor(context.system).invocationHandlerFor(proxyVar.get) match { - case null ⇒ - case some ⇒ + case null => + case some => some.actorVar.set(context.system.deadLetters) //Point it to the DLQ proxyVar.set(null.asInstanceOf[R]) } @@ -279,19 +279,19 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi override def preRestart(reason: Throwable, message: Option[Any]): Unit = withContext { me match { - case l: PreRestart ⇒ l.preRestart(reason, message) - case _ ⇒ context.children foreach context.stop //Can't be super.preRestart(reason, message) since that would invoke postStop which would set the actorVar to DL and proxyVar to null + case l: PreRestart => l.preRestart(reason, message) + case _ => context.children foreach context.stop //Can't be super.preRestart(reason, message) since that would invoke postStop which would set the actorVar to DL and proxyVar to null } } override def postRestart(reason: Throwable): Unit = withContext { me match { - case l: PostRestart ⇒ l.postRestart(reason) - case _ ⇒ super.postRestart(reason) + case l: PostRestart => l.postRestart(reason) + case _ => super.postRestart(reason) } } - protected def withContext[U](unitOfWork: ⇒ U): U = { + protected def withContext[U](unitOfWork: => U): U = { TypedActor.selfReference set proxyVar.get TypedActor.currentContext set context try unitOfWork finally { @@ -301,31 +301,31 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi } def receive = { - case m: MethodCall ⇒ withContext { + case m: MethodCall => withContext { if (m.isOneWay) m(me) else { try { val s = sender() m(me) match { - case f: Future[_] if m.returnsFuture ⇒ + case f: Future[_] if m.returnsFuture => implicit val dispatcher = context.dispatcher f onComplete { - case Success(null) ⇒ s ! NullResponse - case Success(result) ⇒ s ! result - case Failure(f) ⇒ s ! Status.Failure(f) + case Success(null) => s ! NullResponse + case Success(result) => s ! result + case Failure(f) => s ! Status.Failure(f) } - case null ⇒ s ! NullResponse - case result ⇒ s ! result + case null => s ! NullResponse + case result => s ! result } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => sender() ! Status.Failure(e) throw e } } } - case msg if me.isInstanceOf[Receiver] ⇒ withContext { + case msg if me.isInstanceOf[Receiver] => withContext { me.asInstanceOf[Receiver].onReceive(msg, sender()) } } @@ -407,30 +407,30 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi def actor = actorVar.get @throws(classOf[Throwable]) def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]): AnyRef = method.getName match { - case "toString" ⇒ actor.toString - case "equals" ⇒ (args.length == 1 && (proxy eq args(0)) || actor == extension.getActorRefFor(args(0))).asInstanceOf[AnyRef] //Force boxing of the boolean - case "hashCode" ⇒ actor.hashCode.asInstanceOf[AnyRef] - case _ ⇒ + case "toString" => actor.toString + case "equals" => (args.length == 1 && (proxy eq args(0)) || actor == extension.getActorRefFor(args(0))).asInstanceOf[AnyRef] //Force boxing of the boolean + case "hashCode" => actor.hashCode.asInstanceOf[AnyRef] + case _ => implicit val dispatcher = extension.system.dispatcher import akka.pattern.ask MethodCall(method, args) match { - case m if m.isOneWay ⇒ + case m if m.isOneWay => actor ! m; null //Null return value - case m if m.returnsFuture ⇒ ask(actor, m)(timeout) map { - case NullResponse ⇒ null - case other ⇒ other + case m if m.returnsFuture => ask(actor, m)(timeout) map { + case NullResponse => null + case other => other } - case m if m.returnsJOption || m.returnsOption ⇒ + case m if m.returnsJOption || m.returnsOption => val f = ask(actor, m)(timeout) - (try { Await.ready(f, timeout.duration).value } catch { case _: TimeoutException ⇒ None }) match { - case None | Some(Success(NullResponse)) | Some(Failure(_: AskTimeoutException)) ⇒ + (try { Await.ready(f, timeout.duration).value } catch { case _: TimeoutException => None }) match { + case None | Some(Success(NullResponse)) | Some(Failure(_: AskTimeoutException)) => if (m.returnsJOption) JOption.none[Any] else None - case Some(t: Try[_]) ⇒ + case Some(t: Try[_]) => t.get.asInstanceOf[AnyRef] } - case m ⇒ Await.result(ask(actor, m)(timeout), timeout.duration) match { - case NullResponse ⇒ null - case other ⇒ other.asInstanceOf[AnyRef] + case m => Await.result(ask(actor, m)(timeout), timeout.duration) match { + case NullResponse => null + case other => other.asInstanceOf[AnyRef] } } } @@ -442,9 +442,9 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi */ private[akka] final case class SerializedTypedActorInvocationHandler(val actor: ActorRef, val timeout: FiniteDuration) { @throws(classOf[ObjectStreamException]) private def readResolve(): AnyRef = JavaSerializer.currentSystem.value match { - case null ⇒ throw new IllegalStateException("SerializedTypedActorInvocationHandler.readResolve requires that " + + case null => throw new IllegalStateException("SerializedTypedActorInvocationHandler.readResolve requires that " + "JavaSerializer.currentSystem.value is set to a non-null value") - case some ⇒ toTypedActorInvocationHandler(some) + case some => toTypedActorInvocationHandler(some) } def toTypedActorInvocationHandler(system: ActorSystem): TypedActorInvocationHandler = @@ -497,8 +497,8 @@ object TypedProps { * * Scala API */ - def apply[T <: AnyRef](interface: Class[_ >: T], creator: ⇒ T): TypedProps[T] = - new TypedProps[T](extractInterfaces(interface), () ⇒ creator) + def apply[T <: AnyRef](interface: Class[_ >: T], creator: => T): TypedProps[T] = + new TypedProps[T](extractInterfaces(interface), () => creator) /** * Uses the supplied class as the factory for the TypedActor implementation, @@ -512,8 +512,8 @@ object TypedProps { /** * INTERNAL API */ - private[akka] def apply[T <: AnyRef](interfaces: immutable.Seq[Class[_]], creator: ⇒ T): TypedProps[T] = - new TypedProps[T](interfaces, () ⇒ creator) + private[akka] def apply[T <: AnyRef](interfaces: immutable.Seq[Class[_]], creator: => T): TypedProps[T] = + new TypedProps[T](interfaces, () => creator) } /** @@ -523,7 +523,7 @@ object TypedProps { @SerialVersionUID(1L) final case class TypedProps[T <: AnyRef] protected[TypedProps] ( interfaces: immutable.Seq[Class[_]], - creator: () ⇒ T, + creator: () => T, dispatcher: String = TypedProps.defaultDispatcherId, deploy: Deploy = Props.defaultDeploy, timeout: Option[Timeout] = TypedProps.defaultTimeout, @@ -650,8 +650,8 @@ class TypedActorExtension(val system: ExtendedActorSystem) extends TypedActorFac * Retrieves the underlying ActorRef for the supplied TypedActor proxy, or null if none found */ def getActorRefFor(proxy: AnyRef): ActorRef = invocationHandlerFor(proxy) match { - case null ⇒ null - case handler ⇒ handler.actor + case null => null + case handler => handler.actor } /** @@ -663,11 +663,11 @@ class TypedActorExtension(val system: ExtendedActorSystem) extends TypedActorFac /** * INTERNAL API */ - private[akka] def createActorRefProxy[R <: AnyRef, T <: R](props: TypedProps[T], proxyVar: AtomVar[R], actorRef: ⇒ ActorRef): R = { + private[akka] def createActorRefProxy[R <: AnyRef, T <: R](props: TypedProps[T], proxyVar: AtomVar[R], actorRef: => ActorRef): R = { //Warning, do not change order of the following statements, it's some elaborate chicken-n-egg handling val actorVar = new AtomVar[ActorRef](null) val proxy = Proxy.newProxyInstance( - (props.loader orElse props.interfaces.collectFirst { case any ⇒ any.getClassLoader }).orNull, //If we have no loader, we arbitrarily take the loader of the first interface + (props.loader orElse props.interfaces.collectFirst { case any => any.getClassLoader }).orNull, //If we have no loader, we arbitrarily take the loader of the first interface props.interfaces.toArray, new TypedActorInvocationHandler(this, actorVar, props.timeout getOrElse DefaultReturnTimeout)).asInstanceOf[R] @@ -686,11 +686,11 @@ class TypedActorExtension(val system: ExtendedActorSystem) extends TypedActorFac */ private[akka] def invocationHandlerFor(typedActor: AnyRef): TypedActorInvocationHandler = if ((typedActor ne null) && classOf[Proxy].isAssignableFrom(typedActor.getClass) && Proxy.isProxyClass(typedActor.getClass)) typedActor match { - case null ⇒ null - case other ⇒ Proxy.getInvocationHandler(other) match { - case null ⇒ null - case handler: TypedActorInvocationHandler ⇒ handler - case _ ⇒ null + case null => null + case other => Proxy.getInvocationHandler(other) match { + case null => null + case handler: TypedActorInvocationHandler => handler + case _ => null } } else null diff --git a/akka-actor/src/main/scala/akka/actor/UntypedActor.scala b/akka-actor/src/main/scala/akka/actor/UntypedActor.scala index a9c259e5c0..a86679049e 100644 --- a/akka-actor/src/main/scala/akka/actor/UntypedActor.scala +++ b/akka-actor/src/main/scala/akka/actor/UntypedActor.scala @@ -164,7 +164,7 @@ abstract class UntypedActor extends Actor { @throws(classOf[Exception]) override def postRestart(reason: Throwable): Unit = super.postRestart(reason) - final def receive = { case msg ⇒ onReceive(msg) } + final def receive = { case msg => onReceive(msg) } /** * Recommended convention is to call this method if the message diff --git a/akka-actor/src/main/scala/akka/actor/dsl/Creators.scala b/akka-actor/src/main/scala/akka/actor/dsl/Creators.scala index cb20452441..6fe9fe2360 100644 --- a/akka-actor/src/main/scala/akka/actor/dsl/Creators.scala +++ b/akka-actor/src/main/scala/akka/actor/dsl/Creators.scala @@ -7,7 +7,7 @@ package akka.actor.dsl import akka.actor._ import scala.reflect.ClassTag -trait Creators { this: ActorDSL.type ⇒ +trait Creators { this: ActorDSL.type => /** * This trait provides a DSL for writing the inner workings of an actor, e.g. @@ -33,10 +33,10 @@ trait Creators { this: ActorDSL.type ⇒ */ trait Act extends Actor { - private[this] var preStartFun: () ⇒ Unit = null - private[this] var postStopFun: () ⇒ Unit = null - private[this] var preRestartFun: (Throwable, Option[Any]) ⇒ Unit = null - private[this] var postRestartFun: Throwable ⇒ Unit = null + private[this] var preStartFun: () => Unit = null + private[this] var postStopFun: () => Unit = null + private[this] var preRestartFun: (Throwable, Option[Any]) => Unit = null + private[this] var postRestartFun: Throwable => Unit = null private[this] var strategy: SupervisorStrategy = null /** @@ -98,26 +98,26 @@ trait Creators { this: ActorDSL.type ⇒ * Replace the `preStart` action with the supplied thunk. Default action * is to call `super.preStart()` */ - def whenStarting(body: ⇒ Unit): Unit = preStartFun = () ⇒ body + def whenStarting(body: => Unit): Unit = preStartFun = () => body /** * Replace the `preRestart` action with the supplied function. Default * action is to call `super.preRestart()`, which will kill all children * and invoke `postStop()`. */ - def whenFailing(body: (Throwable, Option[Any]) ⇒ Unit): Unit = preRestartFun = body + def whenFailing(body: (Throwable, Option[Any]) => Unit): Unit = preRestartFun = body /** * Replace the `postRestart` action with the supplied function. Default * action is to call `super.postRestart` which will call `preStart()`. */ - def whenRestarted(body: Throwable ⇒ Unit): Unit = postRestartFun = body + def whenRestarted(body: Throwable => Unit): Unit = postRestartFun = body /** * Replace the `postStop` action with the supplied thunk. Default action * is to call `super.postStop`. */ - def whenStopping(body: ⇒ Unit): Unit = postStopFun = () ⇒ body + def whenStopping(body: => Unit): Unit = postStopFun = () => body override def preStart(): Unit = if (preStartFun != null) preStartFun() else super.preStart() override def preRestart(cause: Throwable, msg: Option[Any]): Unit = if (preRestartFun != null) preRestartFun(cause, msg) else super.preRestart(cause, msg) @@ -138,7 +138,7 @@ trait Creators { this: ActorDSL.type ⇒ */ trait ActWithStash extends Act with Stash - private def mkProps(classOfActor: Class[_], ctor: () ⇒ Actor): Props = + private def mkProps(classOfActor: Class[_], ctor: () => Actor): Props = Props(classOf[TypedCreatorFunctionConsumer], classOfActor, ctor) /** @@ -151,10 +151,10 @@ trait Creators { this: ActorDSL.type ⇒ * either be an [[akka.actor.ActorSystem]] or an [[akka.actor.ActorContext]], * where the latter is always implicitly available within an [[akka.actor.Actor]]. */ - def actor[T <: Actor: ClassTag](ctor: ⇒ T)(implicit factory: ActorRefFactory): ActorRef = { + def actor[T <: Actor: ClassTag](ctor: => T)(implicit factory: ActorRefFactory): ActorRef = { // configure dispatcher/mailbox based on runtime class val classOfActor = implicitly[ClassTag[T]].runtimeClass - val props = mkProps(classOfActor, () ⇒ ctor) + val props = mkProps(classOfActor, () => ctor) factory.actorOf(props) } @@ -170,10 +170,10 @@ trait Creators { this: ActorDSL.type ⇒ * either be an [[akka.actor.ActorSystem]] or an [[akka.actor.ActorContext]], * where the latter is always implicitly available within an [[akka.actor.Actor]]. */ - def actor[T <: Actor: ClassTag](name: String)(ctor: ⇒ T)(implicit factory: ActorRefFactory): ActorRef = { + def actor[T <: Actor: ClassTag](name: String)(ctor: => T)(implicit factory: ActorRefFactory): ActorRef = { // configure dispatcher/mailbox based on runtime class val classOfActor = implicitly[ClassTag[T]].runtimeClass - val props = mkProps(classOfActor, () ⇒ ctor) + val props = mkProps(classOfActor, () => ctor) if (name == null) factory.actorOf(props) else factory.actorOf(props, name) @@ -191,7 +191,7 @@ trait Creators { this: ActorDSL.type ⇒ * either be an [[akka.actor.ActorSystem]] or an [[akka.actor.ActorContext]], * where the latter is always implicitly available within an [[akka.actor.Actor]]. */ - def actor[T <: Actor: ClassTag](factory: ActorRefFactory, name: String)(ctor: ⇒ T): ActorRef = + def actor[T <: Actor: ClassTag](factory: ActorRefFactory, name: String)(ctor: => T): ActorRef = actor(name)(ctor)(implicitly[ClassTag[T]], factory) /** @@ -205,7 +205,7 @@ trait Creators { this: ActorDSL.type ⇒ * either be an [[akka.actor.ActorSystem]] or an [[akka.actor.ActorContext]], * where the latter is always implicitly available within an [[akka.actor.Actor]]. */ - def actor[T <: Actor: ClassTag](factory: ActorRefFactory)(ctor: ⇒ T): ActorRef = + def actor[T <: Actor: ClassTag](factory: ActorRefFactory)(ctor: => T): ActorRef = actor(null: String)(ctor)(implicitly[ClassTag[T]], factory) } diff --git a/akka-actor/src/main/scala/akka/actor/dsl/Inbox.scala b/akka-actor/src/main/scala/akka/actor/dsl/Inbox.scala index 773a28ba42..1517d1214a 100644 --- a/akka-actor/src/main/scala/akka/actor/dsl/Inbox.scala +++ b/akka-actor/src/main/scala/akka/actor/dsl/Inbox.scala @@ -42,11 +42,11 @@ private[akka] object Inbox { } -trait Inbox { this: ActorDSL.type ⇒ +trait Inbox { this: ActorDSL.type => import Inbox._ - protected trait InboxExtension { this: Extension ⇒ + protected trait InboxExtension { this: Extension => val DSLInboxQueueSize = config.getInt("inbox-size") val inboxNr = new AtomicInteger @@ -82,35 +82,35 @@ trait Inbox { this: ActorDSL.type ⇒ } var currentMsg: Any = _ - val clientPredicate: (Query) ⇒ Boolean = { - case _: Get ⇒ true - case Select(_, p, _) ⇒ p isDefinedAt currentMsg - case _ ⇒ false + val clientPredicate: (Query) => Boolean = { + case _: Get => true + case Select(_, p, _) => p isDefinedAt currentMsg + case _ => false } var currentSelect: Select = _ - val messagePredicate: (Any ⇒ Boolean) = (msg) ⇒ currentSelect.predicate.isDefinedAt(msg) + val messagePredicate: (Any => Boolean) = (msg) => currentSelect.predicate.isDefinedAt(msg) var currentDeadline: Option[(Deadline, Cancellable)] = None def receive = ({ - case g: Get ⇒ + case g: Get => if (messages.isEmpty) enqueueQuery(g) else sender() ! messages.dequeue() - case s: Select ⇒ + case s: Select => if (messages.isEmpty) enqueueQuery(s) else { currentSelect = s messages.dequeueFirst(messagePredicate) match { - case Some(msg) ⇒ sender() ! msg - case None ⇒ enqueueQuery(s) + case Some(msg) => sender() ! msg + case None => enqueueQuery(s) } currentSelect = null } - case StartWatch(target) ⇒ context watch target - case Kick ⇒ + case StartWatch(target) => context watch target + case Kick => val now = Deadline.now - val pred = (q: Query) ⇒ q.deadline.time < now.time + val pred = (q: Query) => q.deadline.time < now.time val overdue = clientsByTimeout.iterator.takeWhile(pred) while (overdue.hasNext) { val toKick = overdue.next() @@ -118,17 +118,17 @@ trait Inbox { this: ActorDSL.type ⇒ } clients = clients.filterNot(pred) clientsByTimeout = clientsByTimeout.from(Get(now)) - case msg ⇒ + case msg => if (clients.isEmpty) enqueueMessage(msg) else { currentMsg = msg clients.dequeueFirst(clientPredicate) match { - case Some(q) ⇒ { clientsByTimeout -= q; q.client ! msg } - case None ⇒ enqueueMessage(msg) + case Some(q) => { clientsByTimeout -= q; q.client ! msg } + case None => enqueueMessage(msg) } currentMsg = null } - }: Receive) andThen { _ ⇒ + }: Receive) andThen { _ => if (clients.isEmpty) { if (currentDeadline.isDefined) { currentDeadline.get._2.cancel() diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/Children.scala b/akka-actor/src/main/scala/akka/actor/dungeon/Children.scala index 60e9733195..c4941f5990 100644 --- a/akka-actor/src/main/scala/akka/actor/dungeon/Children.scala +++ b/akka-actor/src/main/scala/akka/actor/dungeon/Children.scala @@ -15,10 +15,10 @@ import akka.serialization.{ Serialization, SerializationExtension, Serializers } import akka.util.{ Helpers, Unsafe } private[akka] object Children { - val GetNobody = () ⇒ Nobody + val GetNobody = () => Nobody } -private[akka] trait Children { this: ActorCell ⇒ +private[akka] trait Children { this: ActorCell => import ChildrenContainer._ @@ -34,8 +34,8 @@ private[akka] trait Children { this: ActorCell ⇒ final def child(name: String): Option[ActorRef] = Option(getChild(name)) final def getChild(name: String): ActorRef = childrenRefs.getByName(name) match { - case Some(s: ChildRestartStats) ⇒ s.child - case _ ⇒ null + case Some(s: ChildRestartStats) => s.child + case _ => null } def findChild(name: String): Optional[ActorRef] = Optional.ofNullable(getChild(name)) @@ -54,13 +54,13 @@ private[akka] trait Children { this: ActorCell ⇒ private[akka] def getFunctionRefOrNobody(name: String, uid: Int = ActorCell.undefinedUid): InternalActorRef = functionRefs.getOrElse(name, Children.GetNobody()) match { - case f: FunctionRef ⇒ + case f: FunctionRef => if (uid == ActorCell.undefinedUid || f.path.uid == uid) f else Nobody - case other ⇒ + case other => other } - private[akka] def addFunctionRef(f: (ActorRef, Any) ⇒ Unit, name: String = ""): FunctionRef = { + private[akka] def addFunctionRef(f: (ActorRef, Any) => Unit, name: String = ""): FunctionRef = { val r = randomName(new java.lang.StringBuilder("$$")) val n = if (name != "") s"$r-$name" else r val childPath = new ChildActorPath(self.path, n, ActorCell.newUid()) @@ -117,8 +117,8 @@ private[akka] trait Children { this: ActorCell ⇒ } if (actor match { - case r: RepointableRef ⇒ r.isStarted - case _ ⇒ true + case r: RepointableRef => r.isStarted + case _ => true }) shallDie(actor) } actor.asInstanceOf[InternalActorRef].stop() @@ -143,20 +143,20 @@ private[akka] trait Children { this: ActorCell ⇒ @tailrec final def initChild(ref: ActorRef): Option[ChildRestartStats] = { val cc = childrenRefs cc.getByName(ref.path.name) match { - case old @ Some(_: ChildRestartStats) ⇒ old.asInstanceOf[Option[ChildRestartStats]] - case Some(ChildNameReserved) ⇒ + case old @ Some(_: ChildRestartStats) => old.asInstanceOf[Option[ChildRestartStats]] + case Some(ChildNameReserved) => val crs = ChildRestartStats(ref) val name = ref.path.name if (swapChildrenRefs(cc, cc.add(name, crs))) Some(crs) else initChild(ref) - case None ⇒ None + case None => None } } @tailrec final protected def setChildrenTerminationReason(reason: ChildrenContainer.SuspendReason): Boolean = { childrenRefs match { - case c: ChildrenContainer.TerminatingChildrenContainer ⇒ + case c: ChildrenContainer.TerminatingChildrenContainer => swapChildrenRefs(c, c.copy(reason = reason)) || setChildrenTerminationReason(reason) - case _ ⇒ false + case _ => false } } @@ -171,21 +171,21 @@ private[akka] trait Children { this: ActorCell ⇒ protected def isTerminating = childrenRefs.isTerminating protected def waitingForChildrenOrNull = childrenRefs match { - case TerminatingChildrenContainer(_, _, w: WaitingForChildren) ⇒ w - case _ ⇒ null + case TerminatingChildrenContainer(_, _, w: WaitingForChildren) => w + case _ => null } protected def suspendChildren(exceptFor: Set[ActorRef] = Set.empty): Unit = childrenRefs.stats foreach { - case ChildRestartStats(child, _, _) if !(exceptFor contains child) ⇒ child.asInstanceOf[InternalActorRef].suspend() - case _ ⇒ + case ChildRestartStats(child, _, _) if !(exceptFor contains child) => child.asInstanceOf[InternalActorRef].suspend() + case _ => } protected def resumeChildren(causedByFailure: Throwable, perp: ActorRef): Unit = childrenRefs.stats foreach { - case ChildRestartStats(child: InternalActorRef, _, _) ⇒ + case ChildRestartStats(child: InternalActorRef, _, _) => child.resume(if (perp == child) causedByFailure else null) - case stats ⇒ + case stats => throw new IllegalStateException(s"Unexpected child ActorRef: ${stats.child}") } @@ -199,15 +199,15 @@ private[akka] trait Children { this: ActorCell ⇒ if (name.indexOf('#') == -1) { // optimization for the non-uid case getChildByName(name) match { - case Some(crs: ChildRestartStats) ⇒ crs.child.asInstanceOf[InternalActorRef] - case _ ⇒ getFunctionRefOrNobody(name) + case Some(crs: ChildRestartStats) => crs.child.asInstanceOf[InternalActorRef] + case _ => getFunctionRefOrNobody(name) } } else { val (childName, uid) = ActorCell.splitNameAndUid(name) getChildByName(childName) match { - case Some(crs: ChildRestartStats) if uid == ActorCell.undefinedUid || uid == crs.uid ⇒ + case Some(crs: ChildRestartStats) if uid == ActorCell.undefinedUid || uid == crs.uid => crs.child.asInstanceOf[InternalActorRef] - case _ ⇒ getFunctionRefOrNobody(childName, uid) + case _ => getFunctionRefOrNobody(childName, uid) } } @@ -219,12 +219,12 @@ private[akka] trait Children { this: ActorCell ⇒ } childrenRefs match { // The match must be performed BEFORE the removeChild - case TerminatingChildrenContainer(_, _, reason) ⇒ + case TerminatingChildrenContainer(_, _, reason) => removeChild(child) match { - case _: TerminatingChildrenContainer ⇒ None - case _ ⇒ Some(reason) + case _: TerminatingChildrenContainer => None + case _ => Some(reason) } - case _ ⇒ + case _ => removeChild(child) None } @@ -236,9 +236,9 @@ private[akka] trait Children { this: ActorCell ⇒ private def checkName(name: String): String = { name match { - case null ⇒ throw InvalidActorNameException("actor name must not be null") - case "" ⇒ throw InvalidActorNameException("actor name must not be empty") - case _ ⇒ + case null => throw InvalidActorNameException("actor name must not be null") + case "" => throw InvalidActorNameException("actor name must not be empty") + case _ => ActorPath.validatePathElement(name) name } @@ -252,7 +252,7 @@ private[akka] trait Children { this: ActorCell ⇒ if (oldInfo eq null) Serialization.currentTransportInformation.value = system.provider.serializationInformation - props.args forall (arg ⇒ + props.args forall (arg => arg == null || arg.isInstanceOf[NoSerializationVerificationNeeded] || { val o = arg.asInstanceOf[AnyRef] @@ -262,7 +262,7 @@ private[akka] trait Children { this: ActorCell ⇒ ser.deserialize(bytes, serializer.identifier, ms).get != null }) } catch { - case NonFatal(e) ⇒ throw new IllegalArgumentException(s"pre-creation serialization check failed at [${cell.self.path}/$name]", e) + case NonFatal(e) => throw new IllegalArgumentException(s"pre-creation serialization check failed at [${cell.self.path}/$name]", e) } finally Serialization.currentTransportInformation.value = oldInfo } @@ -280,16 +280,16 @@ private[akka] trait Children { this: ActorCell ⇒ cell.provider.actorOf(cell.systemImpl, props, cell.self, childPath, systemService = systemService, deploy = None, lookupDeploy = true, async = async) } catch { - case e: InterruptedException ⇒ + case e: InterruptedException => unreserveChild(name) Thread.interrupted() // clear interrupted flag before throwing according to java convention throw e - case NonFatal(e) ⇒ + case NonFatal(e) => unreserveChild(name) throw e } // mailbox==null during RoutedActorCell constructor, where suspends are queued otherwise - if (mailbox ne null) for (_ ← 1 to mailbox.suspendCount) actor.suspend() + if (mailbox ne null) for (_ <- 1 to mailbox.suspendCount) actor.suspend() initChild(actor) actor.start() actor diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/ChildrenContainer.scala b/akka-actor/src/main/scala/akka/actor/dungeon/ChildrenContainer.scala index a4b125e2ec..ea41170086 100644 --- a/akka-actor/src/main/scala/akka/actor/dungeon/ChildrenContainer.scala +++ b/akka-actor/src/main/scala/akka/actor/dungeon/ChildrenContainer.scala @@ -112,8 +112,8 @@ private[akka] object ChildrenContainer { override def getByName(name: String): Option[ChildStats] = c.get(name) override def getByRef(actor: ActorRef): Option[ChildRestartStats] = c.get(actor.path.name) match { - case c @ Some(crs: ChildRestartStats) if (crs.child == actor) ⇒ c.asInstanceOf[Option[ChildRestartStats]] - case _ ⇒ None + case c @ Some(crs: ChildRestartStats) if (crs.child == actor) => c.asInstanceOf[Option[ChildRestartStats]] + case _ => None } override def children: immutable.Iterable[ActorRef] = @@ -130,8 +130,8 @@ private[akka] object ChildrenContainer { else new NormalChildrenContainer(c.updated(name, ChildNameReserved)) override def unreserve(name: String): ChildrenContainer = c.get(name) match { - case Some(ChildNameReserved) ⇒ NormalChildrenContainer(c - name) - case _ ⇒ this + case Some(ChildNameReserved) => NormalChildrenContainer(c - name) + case _ => this } override def toString = @@ -163,8 +163,8 @@ private[akka] object ChildrenContainer { override def remove(child: ActorRef): ChildrenContainer = { val t = toDie - child if (t.isEmpty) reason match { - case Termination ⇒ TerminatedChildrenContainer - case _ ⇒ NormalChildrenContainer(c - child.path.name) + case Termination => TerminatedChildrenContainer + case _ => NormalChildrenContainer(c - child.path.name) } else copy(c - child.path.name, t) } @@ -172,8 +172,8 @@ private[akka] object ChildrenContainer { override def getByName(name: String): Option[ChildStats] = c.get(name) override def getByRef(actor: ActorRef): Option[ChildRestartStats] = c.get(actor.path.name) match { - case c @ Some(crs: ChildRestartStats) if (crs.child == actor) ⇒ c.asInstanceOf[Option[ChildRestartStats]] - case _ ⇒ None + case c @ Some(crs: ChildRestartStats) if (crs.child == actor) => c.asInstanceOf[Option[ChildRestartStats]] + case _ => None } override def children: immutable.Iterable[ActorRef] = @@ -185,16 +185,16 @@ private[akka] object ChildrenContainer { override def shallDie(actor: ActorRef): ChildrenContainer = copy(toDie = toDie + actor) override def reserve(name: String): ChildrenContainer = reason match { - case Termination ⇒ throw new IllegalStateException("cannot reserve actor name '" + name + "': terminating") - case _ ⇒ + case Termination => throw new IllegalStateException("cannot reserve actor name '" + name + "': terminating") + case _ => if (c contains name) throw InvalidActorNameException(s"actor name [$name] is not unique!") else copy(c = c.updated(name, ChildNameReserved)) } override def unreserve(name: String): ChildrenContainer = c.get(name) match { - case Some(ChildNameReserved) ⇒ copy(c = c - name) - case _ ⇒ this + case Some(ChildNameReserved) => copy(c = c - name) + case _ => this } override def isTerminating: Boolean = reason == Termination diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/DeathWatch.scala b/akka-actor/src/main/scala/akka/actor/dungeon/DeathWatch.scala index fcfe36ebc7..0f6a542c0d 100644 --- a/akka-actor/src/main/scala/akka/actor/dungeon/DeathWatch.scala +++ b/akka-actor/src/main/scala/akka/actor/dungeon/DeathWatch.scala @@ -10,7 +10,7 @@ import akka.actor.{ Actor, ActorCell, ActorRef, ActorRefScope, Address, Internal import akka.event.AddressTerminatedTopic import akka.util.unused -private[akka] trait DeathWatch { this: ActorCell ⇒ +private[akka] trait DeathWatch { this: ActorCell => /** * This map holds a [[None]] for actors for which we send a [[Terminated]] notification on termination, @@ -23,7 +23,7 @@ private[akka] trait DeathWatch { this: ActorCell ⇒ def isWatching(ref: ActorRef): Boolean = watching contains ref override final def watch(subject: ActorRef): ActorRef = subject match { - case a: InternalActorRef ⇒ + case a: InternalActorRef => if (a != self) { if (!watchingContains(a)) maintainAddressTerminatedSubscription(a) { @@ -37,7 +37,7 @@ private[akka] trait DeathWatch { this: ActorCell ⇒ } override final def watchWith(subject: ActorRef, msg: Any): ActorRef = subject match { - case a: InternalActorRef ⇒ + case a: InternalActorRef => if (a != self) { if (!watchingContains(a)) maintainAddressTerminatedSubscription(a) { @@ -51,7 +51,7 @@ private[akka] trait DeathWatch { this: ActorCell ⇒ } override final def unwatch(subject: ActorRef): ActorRef = subject match { - case a: InternalActorRef ⇒ + case a: InternalActorRef => if (a != self && watchingContains(a)) { a.sendSystemMessage(Unwatch(a, self)) // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ maintainAddressTerminatedSubscription(a) { @@ -74,8 +74,8 @@ private[akka] trait DeathWatch { this: ActorCell ⇒ */ protected def watchedActorTerminated(actor: ActorRef, existenceConfirmed: Boolean, addressTerminated: Boolean): Unit = { watchingGet(actor) match { - case None ⇒ // We're apparently no longer watching this actor. - case Some(optionalMessage) ⇒ + case None => // We're apparently no longer watching this actor. + case Some(optionalMessage) => maintainAddressTerminatedSubscription(actor) { watching = removeFromMap(actor, watching) } @@ -165,8 +165,8 @@ private[akka] trait DeathWatch { this: ActorCell ⇒ maintainAddressTerminatedSubscription() { try { watching foreach { // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ - case (watchee: InternalActorRef, _) ⇒ watchee.sendSystemMessage(Unwatch(watchee, self)) - case (watchee, _) ⇒ + case (watchee: InternalActorRef, _) => watchee.sendSystemMessage(Unwatch(watchee, self)) + case (watchee, _) => // should never happen, suppress "match may not be exhaustive" compiler warning throw new IllegalStateException(s"Expected InternalActorRef, but got [${watchee.getClass.getName}]") } @@ -212,7 +212,7 @@ private[akka] trait DeathWatch { this: ActorCell ⇒ protected def addressTerminated(address: Address): Unit = { // cleanup watchedBy since we know they are dead maintainAddressTerminatedSubscription() { - for (a ← watchedBy; if a.path.address == address) watchedBy -= a + for (a <- watchedBy; if a.path.address == address) watchedBy -= a } // send DeathWatchNotification to self for all matching subjects @@ -221,7 +221,7 @@ private[akka] trait DeathWatch { this: ActorCell ⇒ // When a parent is watching a child and it terminates due to AddressTerminated // it is removed by sending DeathWatchNotification with existenceConfirmed = true to support // immediate creation of child with same name. - for ((a, _) ← watching; if a.path.address == address) { + for ((a, _) <- watching; if a.path.address == address) { self.sendSystemMessage(DeathWatchNotification(a, existenceConfirmed = childrenRefs.getByRef(a).isDefined, addressTerminated = true)) } } @@ -232,11 +232,11 @@ private[akka] trait DeathWatch { this: ActorCell ⇒ * Ends subscription to AddressTerminated if subscribing and the * block removes the last non-local ref from watching and watchedBy. */ - private def maintainAddressTerminatedSubscription[T](change: ActorRef = null)(block: ⇒ T): T = { + private def maintainAddressTerminatedSubscription[T](change: ActorRef = null)(block: => T): T = { def isNonLocal(ref: ActorRef) = ref match { - case null ⇒ true - case a: InternalActorRef if !a.isLocal ⇒ true - case _ ⇒ false + case null => true + case a: InternalActorRef if !a.isLocal => true + case _ => false } if (isNonLocal(change)) { diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/Dispatch.scala b/akka-actor/src/main/scala/akka/actor/dungeon/Dispatch.scala index 236050156b..44e04c9c3f 100644 --- a/akka-actor/src/main/scala/akka/actor/dungeon/Dispatch.scala +++ b/akka-actor/src/main/scala/akka/actor/dungeon/Dispatch.scala @@ -26,7 +26,7 @@ final case class SerializationCheckFailedException private (msg: Object, cause: extends AkkaException(s"Failed to serialize and deserialize message of type ${msg.getClass.getName} for testing. " + "To avoid this error, either disable 'akka.actor.serialize-messages', mark the message with 'akka.actor.NoSerializationVerificationNeeded', or configure serialization to support this message", cause) -private[akka] trait Dispatch { this: ActorCell ⇒ +private[akka] trait Dispatch { this: ActorCell => @volatile private var _mailboxDoNotCallMeDirectly: Mailbox = _ //This must be volatile since it isn't protected by the mailbox status @@ -65,7 +65,7 @@ private[akka] trait Dispatch { this: ActorCell ⇒ // it properly in the normal way val actorClass = props.actorClass val createMessage = mailboxType match { - case _: ProducesMessageQueue[_] if system.mailboxes.hasRequiredType(actorClass) ⇒ + case _: ProducesMessageQueue[_] if system.mailboxes.hasRequiredType(actorClass) => val req = system.mailboxes.getRequiredType(actorClass) if (req isInstance mbox.messageQueue) Create(None) else { @@ -74,7 +74,7 @@ private[akka] trait Dispatch { this: ActorCell ⇒ self, s"Actor [$self] requires mailbox type [$req] got [$gotType]"))) } - case _ ⇒ Create(None) + case _ => Create(None) } swapMailbox(mbox) @@ -110,13 +110,13 @@ private[akka] trait Dispatch { this: ActorCell ⇒ } private def handleException: Catcher[Unit] = { - case e: InterruptedException ⇒ + case e: InterruptedException => system.eventStream.publish(Error(e, self.path.toString, clazz(actor), "interrupted during message send")) Thread.currentThread.interrupt() - case NonFatal(e) ⇒ + case NonFatal(e) => val message = e match { - case n: NoStackTrace ⇒ "swallowing exception during message send: " + n.getMessage - case _ ⇒ "swallowing exception during message send" // stack trace includes message + case n: NoStackTrace => "swallowing exception during message send: " + n.getMessage + case _ => "swallowing exception during message send" // stack trace includes message } system.eventStream.publish(Error(e, self.path.toString, clazz(actor), message)) } @@ -146,21 +146,21 @@ private[akka] trait Dispatch { this: ActorCell ⇒ val unwrappedMessage = (envelope.message match { - case DeadLetter(wrapped, _, _) ⇒ wrapped - case other ⇒ other + case DeadLetter(wrapped, _, _) => wrapped + case other => other }).asInstanceOf[AnyRef] unwrappedMessage match { - case _: NoSerializationVerificationNeeded ⇒ envelope - case msg ⇒ + case _: NoSerializationVerificationNeeded => envelope + case msg => val deserializedMsg = try { serializeAndDeserializePayload(msg) } catch { - case NonFatal(e) ⇒ throw SerializationCheckFailedException(msg, e) + case NonFatal(e) => throw SerializationCheckFailedException(msg, e) } envelope.message match { - case dl: DeadLetter ⇒ envelope.copy(message = dl.copy(message = deserializedMsg)) - case _ ⇒ envelope.copy(message = deserializedMsg) + case dl: DeadLetter => envelope.copy(message = dl.copy(message = deserializedMsg)) + case _ => envelope.copy(message = deserializedMsg) } } } diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/FaultHandling.scala b/akka-actor/src/main/scala/akka/actor/dungeon/FaultHandling.scala index 08a8428a7b..3961bda251 100644 --- a/akka-actor/src/main/scala/akka/actor/dungeon/FaultHandling.scala +++ b/akka-actor/src/main/scala/akka/actor/dungeon/FaultHandling.scala @@ -18,7 +18,7 @@ import scala.util.control.Exception._ import scala.util.control.NonFatal import akka.actor.ActorRefScope -private[akka] trait FaultHandling { this: ActorCell ⇒ +private[akka] trait FaultHandling { this: ActorCell => /* ================= * T H E R U L E S @@ -65,7 +65,7 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ try { // if the actor fails in preRestart, we can do nothing but log it: it’s best-effort if (failedActor.context ne null) failedActor.aroundPreRestart(cause, optionalMessage) - } catch handleNonFatalOrInterruptedException { e ⇒ + } catch handleNonFatalOrInterruptedException { e => val ex = PreRestartException(self, e, cause, optionalMessage) publish(Error(ex, self.path.toString, clazz(failedActor), e.getMessage)) } finally { @@ -134,7 +134,7 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ try resumeNonRecursive() finally clearFailed() try create(None) - catch handleNonFatalOrInterruptedException { e ⇒ + catch handleNonFatalOrInterruptedException { e => handleInvokeFailure(Nil, e) } } @@ -152,8 +152,8 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ if (systemImpl.aborting) { // separate iteration because this is a very rare case that should not penalize normal operation children foreach { - case ref: ActorRefScope if !ref.isLocal ⇒ self.sendSystemMessage(DeathWatchNotification(ref, true, false)) - case _ ⇒ + case ref: ActorRefScope if !ref.isLocal => self.sendSystemMessage(DeathWatchNotification(ref, true, false)) + case _ => } } @@ -179,20 +179,20 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ suspendNonRecursive() // suspend children val skip: Set[ActorRef] = currentMessage match { - case Envelope(Failed(_, _, _), child) ⇒ { setFailed(child); Set(child) } - case _ ⇒ { setFailed(self); Set.empty } + case Envelope(Failed(_, _, _), child) => { setFailed(child); Set(child) } + case _ => { setFailed(self); Set.empty } } suspendChildren(exceptFor = skip ++ childrenNotToSuspend) t match { // tell supervisor - case _: InterruptedException ⇒ + case _: InterruptedException => // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ parent.sendSystemMessage(Failed(self, new ActorInterruptedException(t), uid)) - case _ ⇒ + case _ => // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ parent.sendSystemMessage(Failed(self, t, uid)) } - } catch handleNonFatalOrInterruptedException { e ⇒ + } catch handleNonFatalOrInterruptedException { e => publish(Error(e, self.path.toString, clazz(actor), "emergency stop: exception in failure handling for " + t.getClass + Logging.stackTraceFor(t))) try children foreach stop @@ -208,7 +208,7 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ * specific order. */ try if (a ne null) a.aroundPostStop() - catch handleNonFatalOrInterruptedException { e ⇒ publish(Error(e, self.path.toString, clazz(a), e.getMessage)) } + catch handleNonFatalOrInterruptedException { e => publish(Error(e, self.path.toString, clazz(a), e.getMessage)) } finally try dispatcher.detach(this) finally try parent.sendSystemMessage(DeathWatchNotification(self, existenceConfirmed = true, addressTerminated = false)) finally try stopFunctionRefs() @@ -240,12 +240,12 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ if (system.settings.DebugLifecycle) publish(Debug(self.path.toString, clazz(freshActor), "restarted")) // only after parent is up and running again do restart the children which were not stopped - survivors foreach (child ⇒ + survivors foreach (child => try child.asInstanceOf[InternalActorRef].restart(cause) - catch handleNonFatalOrInterruptedException { e ⇒ + catch handleNonFatalOrInterruptedException { e => publish(Error(e, self.path.toString, clazz(freshActor), "restarting " + child)) }) - } catch handleNonFatalOrInterruptedException { e ⇒ + } catch handleNonFatalOrInterruptedException { e => clearActorFields(actor, recreate = false) // in order to prevent preRestart() from happening again handleInvokeFailure(survivors, PostRestartException(self, e, cause)) } @@ -259,12 +259,12 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ * the UID protects against reception of a Failed from a child which was * killed in preRestart and re-created in postRestart */ - case Some(stats) if stats.uid == f.uid ⇒ + case Some(stats) if stats.uid == f.uid => if (!actor.supervisorStrategy.handleFailure(this, f.child, f.cause, stats, getAllChildStats)) throw f.cause - case Some(stats) ⇒ + case Some(stats) => publish(Debug(self.path.toString, clazz(actor), "dropping Failed(" + f.cause + ") from old child " + f.child + " (uid=" + stats.uid + " != " + f.uid + ")")) - case None ⇒ + case None => publish(Debug(self.path.toString, clazz(actor), "dropping Failed(" + f.cause + ") from unknown child " + f.child)) } } @@ -278,7 +278,7 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ */ if (actor != null) { try actor.supervisorStrategy.handleChildTerminated(this, child, children) - catch handleNonFatalOrInterruptedException { e ⇒ + catch handleNonFatalOrInterruptedException { e => publish(Error(e, self.path.toString, clazz(actor), "handleChildTerminated failed")) handleInvokeFailure(Nil, e) } @@ -288,18 +288,18 @@ private[akka] trait FaultHandling { this: ActorCell ⇒ * then we are continuing the previously suspended recreate/create/terminate action */ status match { - case Some(ChildrenContainer.Recreation(cause)) ⇒ finishRecreate(cause, actor) - case Some(ChildrenContainer.Creation()) ⇒ finishCreate() - case Some(ChildrenContainer.Termination) ⇒ finishTerminate() - case _ ⇒ + case Some(ChildrenContainer.Recreation(cause)) => finishRecreate(cause, actor) + case Some(ChildrenContainer.Creation()) => finishCreate() + case Some(ChildrenContainer.Termination) => finishTerminate() + case _ => } } - final protected def handleNonFatalOrInterruptedException(thunk: (Throwable) ⇒ Unit): Catcher[Unit] = { - case e: InterruptedException ⇒ + final protected def handleNonFatalOrInterruptedException(thunk: (Throwable) => Unit): Catcher[Unit] = { + case e: InterruptedException => thunk(e) Thread.currentThread().interrupt() - case NonFatal(e) ⇒ + case NonFatal(e) => thunk(e) } } diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/ReceiveTimeout.scala b/akka-actor/src/main/scala/akka/actor/dungeon/ReceiveTimeout.scala index e6a15ed7f0..f73190050f 100644 --- a/akka-actor/src/main/scala/akka/actor/dungeon/ReceiveTimeout.scala +++ b/akka-actor/src/main/scala/akka/actor/dungeon/ReceiveTimeout.scala @@ -13,7 +13,7 @@ private[akka] object ReceiveTimeout { final val emptyReceiveTimeoutData: (Duration, Cancellable) = (Duration.Undefined, ActorCell.emptyCancellable) } -private[akka] trait ReceiveTimeout { this: ActorCell ⇒ +private[akka] trait ReceiveTimeout { this: ActorCell => import ReceiveTimeout._ import ActorCell._ @@ -27,7 +27,7 @@ private[akka] trait ReceiveTimeout { this: ActorCell ⇒ final def checkReceiveTimeout(reschedule: Boolean = true): Unit = { val (recvtimeout, task) = receiveTimeoutData recvtimeout match { - case f: FiniteDuration ⇒ + case f: FiniteDuration => // The fact that timeout is FiniteDuration and task is emptyCancellable // means that a user called `context.setReceiveTimeout(...)` // while sending the ReceiveTimeout message is not scheduled yet. @@ -36,7 +36,7 @@ private[akka] trait ReceiveTimeout { this: ActorCell ⇒ if (reschedule || (task eq emptyCancellable)) rescheduleReceiveTimeout(f) - case _ ⇒ cancelReceiveTimeout() + case _ => cancelReceiveTimeout() } } diff --git a/akka-actor/src/main/scala/akka/actor/dungeon/TimerSchedulerImpl.scala b/akka-actor/src/main/scala/akka/actor/dungeon/TimerSchedulerImpl.scala index 8d6e2da357..e6ac315eaa 100644 --- a/akka-actor/src/main/scala/akka/actor/dungeon/TimerSchedulerImpl.scala +++ b/akka-actor/src/main/scala/akka/actor/dungeon/TimerSchedulerImpl.scala @@ -49,8 +49,8 @@ import akka.util.OptionVal private def startTimer(key: Any, msg: Any, timeout: FiniteDuration, repeat: Boolean): Unit = { timers.get(key) match { - case Some(t) ⇒ cancelTimer(t) - case None ⇒ + case Some(t) => cancelTimer(t) + case None => } val nextGen = nextTimerGen() @@ -76,8 +76,8 @@ import akka.util.OptionVal override def cancel(key: Any): Unit = { timers.get(key) match { - case None ⇒ // already removed/canceled - case Some(t) ⇒ cancelTimer(t) + case None => // already removed/canceled + case Some(t) => cancelTimer(t) } } @@ -89,7 +89,7 @@ import akka.util.OptionVal override def cancelAll(): Unit = { log.debug("Cancel all timers") - timers.valuesIterator.foreach { timer ⇒ + timers.valuesIterator.foreach { timer => timer.task.cancel() } timers = Map.empty @@ -97,11 +97,11 @@ import akka.util.OptionVal def interceptTimerMsg(timerMsg: TimerMsg): OptionVal[AnyRef] = { timers.get(timerMsg.key) match { - case None ⇒ + case None => // it was from canceled timer that was already enqueued in mailbox log.debug("Received timer [{}] that has been removed, discarding", timerMsg.key) OptionVal.None // message should be ignored - case Some(t) ⇒ + case Some(t) => if (timerMsg.owner ne this) { // after restart, it was from an old instance that was enqueued in mailbox before canceled log.debug("Received timer [{}] from old restarted instance, discarding", timerMsg.key) diff --git a/akka-actor/src/main/scala/akka/actor/setup/ActorSystemSetup.scala b/akka-actor/src/main/scala/akka/actor/setup/ActorSystemSetup.scala index f867529f88..3f3e0b4b4d 100644 --- a/akka-actor/src/main/scala/akka/actor/setup/ActorSystemSetup.scala +++ b/akka-actor/src/main/scala/akka/actor/setup/ActorSystemSetup.scala @@ -36,7 +36,7 @@ object ActorSystemSetup { * Scala API: Create an [[ActorSystemSetup]] containing all the provided settings */ def apply(settings: Setup*): ActorSystemSetup = - new ActorSystemSetup(settings.map(s ⇒ s.getClass → s).toMap) + new ActorSystemSetup(settings.map(s => s.getClass -> s).toMap) /** * Java API: Create an [[ActorSystemSetup]] containing all the provided settings @@ -73,7 +73,7 @@ final class ActorSystemSetup private[akka] (@InternalApi private[akka] val setup * present it will be replaced. */ def withSetup[T <: Setup](t: T): ActorSystemSetup = { - new ActorSystemSetup(setups + (t.getClass → t)) + new ActorSystemSetup(setups + (t.getClass -> t)) } /** diff --git a/akka-actor/src/main/scala/akka/dispatch/AbstractDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/AbstractDispatcher.scala index 4b0b585fb7..8e7309cc9d 100644 --- a/akka-actor/src/main/scala/akka/dispatch/AbstractDispatcher.scala +++ b/akka-actor/src/main/scala/akka/dispatch/AbstractDispatcher.scala @@ -5,7 +5,7 @@ package akka.dispatch import java.util.concurrent._ -import java.{ util ⇒ ju } +import java.{ util => ju } import akka.actor._ import akka.dispatch.affinity.AffinityPoolConfigurator @@ -29,23 +29,23 @@ object Envelope { } } -final case class TaskInvocation(eventStream: EventStream, runnable: Runnable, cleanup: () ⇒ Unit) extends Batchable { +final case class TaskInvocation(eventStream: EventStream, runnable: Runnable, cleanup: () => Unit) extends Batchable { final override def isBatchable: Boolean = runnable match { - case b: Batchable ⇒ b.isBatchable - case _: scala.concurrent.OnCompleteRunnable ⇒ true - case _ ⇒ false + case b: Batchable => b.isBatchable + case _: scala.concurrent.OnCompleteRunnable => true + case _ => false } def run(): Unit = try runnable.run() catch { - case NonFatal(e) ⇒ eventStream.publish(Error(e, "TaskInvocation", this.getClass, e.getMessage)) + case NonFatal(e) => eventStream.publish(Error(e, "TaskInvocation", this.getClass, e.getMessage)) } finally cleanup() } /** * INTERNAL API */ -private[akka] trait LoadMetrics { self: Executor ⇒ +private[akka] trait LoadMetrics { self: Executor => def atFullThrottle(): Boolean } @@ -66,17 +66,17 @@ private[akka] object MessageDispatcher { def printActors(): Unit = if (debug) { for { - d ← actors.keys - a ← { println(d + " inhabitants: " + d.inhabitants); actors.valueIterator(d) } + d <- actors.keys + a <- { println(d + " inhabitants: " + d.inhabitants); actors.valueIterator(d) } } { val status = if (a.isTerminated) " (terminated)" else " (alive)" val messages = a match { - case r: ActorRefWithCell ⇒ " " + r.underlying.numberOfMessages + " messages" - case _ ⇒ " " + a.getClass + case r: ActorRefWithCell => " " + r.underlying.numberOfMessages + " messages" + case _ => " " + a.getClass } val parent = a match { - case i: InternalActorRef ⇒ ", parent: " + i.getParent - case _ ⇒ "" + case i: InternalActorRef => ", parent: " + i.getParent + case _ => "" } println(" -> " + a + status + messages + parent) } @@ -145,27 +145,27 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator try { executeTask(invocation) } catch { - case t: Throwable ⇒ + case t: Throwable => addInhabitants(-1) throw t } } override def reportFailure(t: Throwable): Unit = t match { - case e: LogEventException ⇒ eventStream.publish(e.event) - case _ ⇒ eventStream.publish(Error(t, getClass.getName, getClass, t.getMessage)) + case e: LogEventException => eventStream.publish(e.event) + case _ => eventStream.publish(Error(t, getClass.getName, getClass, t.getMessage)) } @tailrec private final def ifSensibleToDoSoThenScheduleShutdown(): Unit = { if (inhabitants <= 0) shutdownSchedule match { - case UNSCHEDULED ⇒ + case UNSCHEDULED => if (updateShutdownSchedule(UNSCHEDULED, SCHEDULED)) scheduleShutdownAction() else ifSensibleToDoSoThenScheduleShutdown() - case SCHEDULED ⇒ + case SCHEDULED => if (updateShutdownSchedule(SCHEDULED, RESCHEDULED)) () else ifSensibleToDoSoThenScheduleShutdown() - case RESCHEDULED ⇒ + case RESCHEDULED => } } @@ -175,7 +175,7 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator override def execute(runnable: Runnable): Unit = runnable.run() override def reportFailure(t: Throwable): Unit = MessageDispatcher.this.reportFailure(t) }) catch { - case _: IllegalStateException ⇒ + case _: IllegalStateException => shutdown() // Since there is no scheduler anymore, restore the state to UNSCHEDULED. // When this dispatcher is used again, @@ -185,7 +185,7 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator } } - private final val taskCleanup: () ⇒ Unit = () ⇒ if (addInhabitants(-1) == 0) ifSensibleToDoSoThenScheduleShutdown() + private final val taskCleanup: () => Unit = () => if (addInhabitants(-1) == 0) ifSensibleToDoSoThenScheduleShutdown() /** * If you override it, you must call it. But only ever once. See "attach" for only invocation. @@ -214,16 +214,16 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator @tailrec final def run(): Unit = { shutdownSchedule match { - case SCHEDULED ⇒ + case SCHEDULED => try { if (inhabitants == 0) shutdown() //Warning, racy } finally { while (!updateShutdownSchedule(shutdownSchedule, UNSCHEDULED)) {} } - case RESCHEDULED ⇒ + case RESCHEDULED => if (updateShutdownSchedule(RESCHEDULED, SCHEDULED)) scheduleShutdownAction() else run() - case UNSCHEDULED ⇒ + case UNSCHEDULED => } } } @@ -327,16 +327,16 @@ abstract class MessageDispatcherConfigurator(_config: Config, val prerequisites: def configureExecutor(): ExecutorServiceConfigurator = { def configurator(executor: String): ExecutorServiceConfigurator = executor match { - case null | "" | "fork-join-executor" ⇒ new ForkJoinExecutorConfigurator(config.getConfig("fork-join-executor"), prerequisites) - case "thread-pool-executor" ⇒ new ThreadPoolExecutorConfigurator(config.getConfig("thread-pool-executor"), prerequisites) - case "affinity-pool-executor" ⇒ new AffinityPoolConfigurator(config.getConfig("affinity-pool-executor"), prerequisites) + case null | "" | "fork-join-executor" => new ForkJoinExecutorConfigurator(config.getConfig("fork-join-executor"), prerequisites) + case "thread-pool-executor" => new ThreadPoolExecutorConfigurator(config.getConfig("thread-pool-executor"), prerequisites) + case "affinity-pool-executor" => new AffinityPoolConfigurator(config.getConfig("affinity-pool-executor"), prerequisites) - case fqcn ⇒ + case fqcn => val args = List( - classOf[Config] → config, - classOf[DispatcherPrerequisites] → prerequisites) + classOf[Config] -> config, + classOf[DispatcherPrerequisites] -> prerequisites) prerequisites.dynamicAccess.createInstanceFor[ExecutorServiceConfigurator](fqcn, args).recover({ - case exception ⇒ throw new IllegalArgumentException( + case exception => throw new IllegalArgumentException( ("""Cannot instantiate ExecutorServiceConfigurator ("executor = [%s]"), defined in [%s], make sure it has an accessible constructor with a [%s,%s] signature""") .format(fqcn, config.getString("id"), classOf[Config], classOf[DispatcherPrerequisites]), exception) @@ -344,8 +344,8 @@ abstract class MessageDispatcherConfigurator(_config: Config, val prerequisites: } config.getString("executor") match { - case "default-executor" ⇒ new DefaultExecutorServiceConfigurator(config.getConfig("default-executor"), prerequisites, configurator(config.getString("default-executor.fallback"))) - case other ⇒ configurator(other) + case "default-executor" => new DefaultExecutorServiceConfigurator(config.getConfig("default-executor"), prerequisites, configurator(config.getString("default-executor.fallback"))) + case other => configurator(other) } } } @@ -362,13 +362,13 @@ class ThreadPoolExecutorConfigurator(config: Config, prerequisites: DispatcherPr .setAllowCoreThreadTimeout(config getBoolean "allow-core-timeout") .configure( Some(config getInt "task-queue-size") flatMap { - case size if size > 0 ⇒ + case size if size > 0 => Some(config getString "task-queue-type") map { - case "array" ⇒ ThreadPoolConfig.arrayBlockingQueue(size, false) //TODO config fairness? - case "" | "linked" ⇒ ThreadPoolConfig.linkedBlockingQueue(size) - case x ⇒ throw new IllegalArgumentException("[%s] is not a valid task-queue-type [array|linked]!" format x) - } map { qf ⇒ (q: ThreadPoolConfigBuilder) ⇒ q.setQueueFactory(qf) } - case _ ⇒ None + case "array" => ThreadPoolConfig.arrayBlockingQueue(size, false) //TODO config fairness? + case "" | "linked" => ThreadPoolConfig.linkedBlockingQueue(size) + case x => throw new IllegalArgumentException("[%s] is not a valid task-queue-type [array|linked]!" format x) + } map { qf => (q: ThreadPoolConfigBuilder) => q.setQueueFactory(qf) } + case _ => None }) if (config.getString("fixed-pool-size") == "off") @@ -386,7 +386,7 @@ class ThreadPoolExecutorConfigurator(config: Config, prerequisites: DispatcherPr class DefaultExecutorServiceConfigurator(config: Config, prerequisites: DispatcherPrerequisites, fallback: ExecutorServiceConfigurator) extends ExecutorServiceConfigurator(config, prerequisites) { val provider: ExecutorServiceFactoryProvider = prerequisites.defaultExecutionContext match { - case Some(ec) ⇒ + case Some(ec) => prerequisites.eventStream.publish(Debug("DefaultExecutorServiceConfigurator", this.getClass, s"Using passed in ExecutionContext as default executor for this ActorSystem. If you want to use a different executor, please specify one in akka.actor.default-dispatcher.default-executor.")) new AbstractExecutorService with ExecutorServiceFactory with ExecutorServiceFactoryProvider { @@ -399,7 +399,7 @@ class DefaultExecutorServiceConfigurator(config: Config, prerequisites: Dispatch def execute(command: Runnable): Unit = ec.execute(command) def isShutdown: Boolean = false } - case None ⇒ fallback + case None => fallback } def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory = diff --git a/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala index fe0e0921b5..e239b5b8d6 100644 --- a/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala +++ b/akka-actor/src/main/scala/akka/dispatch/BalancingDispatcher.scala @@ -96,8 +96,8 @@ private[akka] class BalancingDispatcher( if (messageQueue.hasMessages && i.hasNext && (executorService.executor match { - case lm: LoadMetrics ⇒ lm.atFullThrottle == false - case _ ⇒ true + case lm: LoadMetrics => lm.atFullThrottle == false + case _ => true }) && !registerForExecution(i.next.mailbox, false, false)) scheduleOne(i) diff --git a/akka-actor/src/main/scala/akka/dispatch/BatchingExecutor.scala b/akka-actor/src/main/scala/akka/dispatch/BatchingExecutor.scala index f37b1f5c0f..dd21963c64 100644 --- a/akka-actor/src/main/scala/akka/dispatch/BatchingExecutor.scala +++ b/akka-actor/src/main/scala/akka/dispatch/BatchingExecutor.scala @@ -71,7 +71,7 @@ private[akka] trait BatchingExecutor extends Executor { require(_tasksLocal.get eq null) _tasksLocal set this // Install ourselves as the current batch try processBatch(this) catch { - case t: Throwable ⇒ + case t: Throwable => resubmitUnbatched() throw t } finally _tasksLocal.remove() @@ -89,7 +89,7 @@ private[akka] trait BatchingExecutor extends Executor { if (firstInvocation) _blockContext.set(BlockContext.current) BlockContext.withBlockContext(this) { try processBatch(this) catch { - case t: Throwable ⇒ + case t: Throwable => resubmitUnbatched() throw t } finally { @@ -99,7 +99,7 @@ private[akka] trait BatchingExecutor extends Executor { } } - override def blockOn[T](thunk: ⇒ T)(implicit permission: CanAwait): T = { + override def blockOn[T](thunk: => T)(implicit permission: CanAwait): T = { // if we know there will be blocking, we don't want to keep tasks queued up because it could deadlock. resubmitUnbatched() // now delegate the blocking to the previous BC @@ -114,19 +114,19 @@ private[akka] trait BatchingExecutor extends Executor { override def execute(runnable: Runnable): Unit = { if (batchable(runnable)) { // If we can batch the runnable _tasksLocal.get match { - case null ⇒ + case null => val newBatch: AbstractBatch = if (resubmitOnBlock) new BlockableBatch() else new Batch() newBatch.add(runnable) unbatchedExecute(newBatch) // If we aren't in batching mode yet, enqueue batch - case batch ⇒ batch.add(runnable) // If we are already in batching mode, add to batch + case batch => batch.add(runnable) // If we are already in batching mode, add to batch } } else unbatchedExecute(runnable) // If not batchable, just delegate to underlying } /** Override this to define which runnables will be batched. */ def batchable(runnable: Runnable): Boolean = runnable match { - case b: Batchable ⇒ b.isBatchable - case _: scala.concurrent.OnCompleteRunnable ⇒ true - case _ ⇒ false + case b: Batchable => b.isBatchable + case _: scala.concurrent.OnCompleteRunnable => true + case _ => false } } diff --git a/akka-actor/src/main/scala/akka/dispatch/CachingConfig.scala b/akka-actor/src/main/scala/akka/dispatch/CachingConfig.scala index 3ed6fccfd1..467849fc49 100644 --- a/akka-actor/src/main/scala/akka/dispatch/CachingConfig.scala +++ b/akka-actor/src/main/scala/akka/dispatch/CachingConfig.scala @@ -44,20 +44,20 @@ private[akka] class CachingConfig(_config: Config) extends Config { import CachingConfig._ private val (config: Config, entryMap: ConcurrentHashMap[String, PathEntry]) = _config match { - case cc: CachingConfig ⇒ (cc.config, cc.entryMap) - case _ ⇒ (_config, new ConcurrentHashMap[String, PathEntry]) + case cc: CachingConfig => (cc.config, cc.entryMap) + case _ => (_config, new ConcurrentHashMap[String, PathEntry]) } private def getPathEntry(path: String): PathEntry = entryMap.get(path) match { - case null ⇒ + case null => val ne = Try { config.hasPath(path) } match { - case Failure(_) ⇒ invalidPathEntry - case Success(false) ⇒ nonExistingPathEntry - case _ ⇒ + case Failure(_) => invalidPathEntry + case Success(false) => nonExistingPathEntry + case _ => Try { config.getValue(path) } match { - case Failure(_) ⇒ + case Failure(_) => emptyPathEntry - case Success(v) ⇒ + case Success(v) => if (v.valueType() == ConfigValueType.STRING) StringPathEntry(true, true, v.atKey("cached"), v.unwrapped().asInstanceOf[String]) else @@ -66,11 +66,11 @@ private[akka] class CachingConfig(_config: Config) extends Config { } entryMap.putIfAbsent(path, ne) match { - case null ⇒ ne - case e ⇒ e + case null => ne + case e => e } - case e ⇒ e + case e => e } def checkValid(reference: Config, restrictToPaths: String*): Unit = { @@ -117,9 +117,9 @@ private[akka] class CachingConfig(_config: Config) extends Config { def getString(path: String) = { getPathEntry(path) match { - case StringPathEntry(_, _, _, string) ⇒ + case StringPathEntry(_, _, _, string) => string - case e ⇒ e.config.getString("cached") + case e => e.config.getString("cached") } } diff --git a/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala b/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala index a89b6d2379..1942640ba9 100644 --- a/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala +++ b/akka-actor/src/main/scala/akka/dispatch/Dispatcher.scala @@ -71,11 +71,11 @@ class Dispatcher( try { executorService execute invocation } catch { - case e: RejectedExecutionException ⇒ + case e: RejectedExecutionException => try { executorService execute invocation } catch { - case e2: RejectedExecutionException ⇒ + case e2: RejectedExecutionException => eventStream.publish(Error(e, getClass.getName, getClass, "executeTask was rejected twice!")) throw e2 } @@ -115,12 +115,12 @@ class Dispatcher( executorService execute mbox true } catch { - case _: RejectedExecutionException ⇒ + case _: RejectedExecutionException => try { executorService execute mbox true } catch { //Retry once - case e: RejectedExecutionException ⇒ + case e: RejectedExecutionException => mbox.setAsIdle() eventStream.publish(Error(e, getClass.getName, getClass, "registerForExecution was rejected twice!")) throw e @@ -137,7 +137,7 @@ object PriorityGenerator { /** * Creates a PriorityGenerator that uses the supplied function as priority generator */ - def apply(priorityFunction: Any ⇒ Int): PriorityGenerator = new PriorityGenerator { + def apply(priorityFunction: Any => Int): PriorityGenerator = new PriorityGenerator { def gen(message: Any): Int = priorityFunction(message) } } diff --git a/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala b/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala index 0e4fb88c85..09faa89b92 100644 --- a/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala +++ b/akka-actor/src/main/scala/akka/dispatch/Dispatchers.scala @@ -88,7 +88,7 @@ class Dispatchers(val settings: ActorSystem.Settings, val prerequisites: Dispatc private def lookupConfigurator(id: String): MessageDispatcherConfigurator = { dispatcherConfigurators.get(id) match { - case null ⇒ + case null => // It doesn't matter if we create a dispatcher configurator that isn't used due to concurrent lookup. // That shouldn't happen often and in case it does the actual ExecutorService isn't // created until used, i.e. cheap. @@ -97,11 +97,11 @@ class Dispatchers(val settings: ActorSystem.Settings, val prerequisites: Dispatc else throw new ConfigurationException(s"Dispatcher [$id] not configured") dispatcherConfigurators.putIfAbsent(id, newConfigurator) match { - case null ⇒ newConfigurator - case existing ⇒ existing + case null => newConfigurator + case existing => existing } - case existing ⇒ existing + case existing => existing } } @@ -135,13 +135,13 @@ class Dispatchers(val settings: ActorSystem.Settings, val prerequisites: Dispatc def simpleName = id.substring(id.lastIndexOf('.') + 1) idConfig(id) .withFallback(appConfig) - .withFallback(ConfigFactory.parseMap(Map("name" → simpleName).asJava)) + .withFallback(ConfigFactory.parseMap(Map("name" -> simpleName).asJava)) .withFallback(defaultDispatcherConfig) } private def idConfig(id: String): Config = { import scala.collection.JavaConverters._ - ConfigFactory.parseMap(Map("id" → id).asJava) + ConfigFactory.parseMap(Map("id" -> id).asJava) } /** @@ -172,17 +172,17 @@ class Dispatchers(val settings: ActorSystem.Settings, val prerequisites: Dispatc if (!cfg.hasPath("id")) throw new ConfigurationException("Missing dispatcher 'id' property in config: " + cfg.root.render) cfg.getString("type") match { - case "Dispatcher" ⇒ new DispatcherConfigurator(cfg, prerequisites) - case "BalancingDispatcher" ⇒ + case "Dispatcher" => new DispatcherConfigurator(cfg, prerequisites) + case "BalancingDispatcher" => // FIXME remove this case in 2.4 throw new IllegalArgumentException("BalancingDispatcher is deprecated, use a BalancingPool instead. " + "During a migration period you can still use BalancingDispatcher by specifying the full class name: " + classOf[BalancingDispatcherConfigurator].getName) - case "PinnedDispatcher" ⇒ new PinnedDispatcherConfigurator(cfg, prerequisites) - case fqn ⇒ - val args = List(classOf[Config] → cfg, classOf[DispatcherPrerequisites] → prerequisites) + case "PinnedDispatcher" => new PinnedDispatcherConfigurator(cfg, prerequisites) + case fqn => + val args = List(classOf[Config] -> cfg, classOf[DispatcherPrerequisites] -> prerequisites) prerequisites.dynamicAccess.createInstanceFor[MessageDispatcherConfigurator](fqn, args).recover({ - case exception ⇒ + case exception => throw new ConfigurationException( ("Cannot instantiate MessageDispatcherConfigurator type [%s], defined in [%s], " + "make sure it has constructor with [com.typesafe.config.Config] and " + @@ -285,8 +285,8 @@ class PinnedDispatcherConfigurator(config: Config, prerequisites: DispatcherPrer extends MessageDispatcherConfigurator(config, prerequisites) { private val threadPoolConfig: ThreadPoolConfig = configureExecutor() match { - case e: ThreadPoolExecutorConfigurator ⇒ e.threadPoolConfig - case _ ⇒ + case e: ThreadPoolExecutorConfigurator => e.threadPoolConfig + case _ => prerequisites.eventStream.publish( Warning( "PinnedDispatcherConfigurator", diff --git a/akka-actor/src/main/scala/akka/dispatch/ForkJoinExecutorConfigurator.scala b/akka-actor/src/main/scala/akka/dispatch/ForkJoinExecutorConfigurator.scala index 71426ff62c..25c37bc6eb 100644 --- a/akka-actor/src/main/scala/akka/dispatch/ForkJoinExecutorConfigurator.scala +++ b/akka-actor/src/main/scala/akka/dispatch/ForkJoinExecutorConfigurator.scala @@ -42,14 +42,14 @@ object ForkJoinExecutorConfigurator { override def getRawResult(): Unit = () override def setRawResult(unit: Unit): Unit = () final override def exec(): Boolean = try { runnable.run(); true } catch { - case _: InterruptedException ⇒ + case _: InterruptedException => Thread.currentThread.interrupt() false - case anything: Throwable ⇒ + case anything: Throwable => val t = Thread.currentThread t.getUncaughtExceptionHandler match { - case null ⇒ - case some ⇒ some.uncaughtException(t, anything) + case null => + case some => some.uncaughtException(t, anything) } throw anything } @@ -60,8 +60,8 @@ class ForkJoinExecutorConfigurator(config: Config, prerequisites: DispatcherPrer import ForkJoinExecutorConfigurator._ def validate(t: ThreadFactory): ForkJoinPool.ForkJoinWorkerThreadFactory = t match { - case correct: ForkJoinPool.ForkJoinWorkerThreadFactory ⇒ correct - case _ ⇒ throw new IllegalStateException("The prerequisites for the ForkJoinExecutorConfigurator is a ForkJoinPool.ForkJoinWorkerThreadFactory!") + case correct: ForkJoinPool.ForkJoinWorkerThreadFactory => correct + case _ => throw new IllegalStateException("The prerequisites for the ForkJoinExecutorConfigurator is a ForkJoinPool.ForkJoinWorkerThreadFactory!") } class ForkJoinExecutorServiceFactory( @@ -74,16 +74,16 @@ class ForkJoinExecutorConfigurator(config: Config, prerequisites: DispatcherPrer final def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory = { val tf = threadFactory match { - case m: MonitorableThreadFactory ⇒ + case m: MonitorableThreadFactory => // add the dispatcher id to the thread names m.withName(m.name + "-" + id) - case other ⇒ other + case other => other } val asyncMode = config.getString("task-peeking-mode") match { - case "FIFO" ⇒ true - case "LIFO" ⇒ false - case _ ⇒ throw new IllegalArgumentException("Cannot instantiate ForkJoinExecutorServiceFactory. " + + case "FIFO" => true + case "LIFO" => false + case _ => throw new IllegalArgumentException("Cannot instantiate ForkJoinExecutorServiceFactory. " + """"task-peeking-mode" in "fork-join-executor" section could only set to "FIFO" or "LIFO".""") } diff --git a/akka-actor/src/main/scala/akka/dispatch/Future.scala b/akka-actor/src/main/scala/akka/dispatch/Future.scala index 08b82e8a9a..1464894219 100644 --- a/akka-actor/src/main/scala/akka/dispatch/Future.scala +++ b/akka-actor/src/main/scala/akka/dispatch/Future.scala @@ -5,11 +5,11 @@ package akka.dispatch import scala.runtime.{ AbstractPartialFunction, BoxedUnit } -import akka.japi.{ Procedure, Function ⇒ JFunc, Option ⇒ JOption } +import akka.japi.{ Procedure, Function => JFunc, Option => JOption } import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor, ExecutionContextExecutorService, Future, Promise } -import java.lang.{ Iterable ⇒ JIterable } -import java.util.{ LinkedList ⇒ JLinkedList } +import java.lang.{ Iterable => JIterable } +import java.util.{ LinkedList => JLinkedList } import java.util.concurrent.{ Callable, Executor, ExecutorService } import scala.util.{ Failure, Success, Try } @@ -162,19 +162,19 @@ object Futures { */ def sequence[A](in: JIterable[Future[A]], executor: ExecutionContext): Future[JIterable[A]] = { implicit val d = executor - in.asScala.foldLeft(Future(new JLinkedList[A]())) { (fr, fa) ⇒ for (r ← fr; a ← fa) yield { r add a; r } } + in.asScala.foldLeft(Future(new JLinkedList[A]())) { (fr, fa) => for (r <- fr; a <- fa) yield { r add a; r } } } /** - * Transforms a JIterable[A] into a Future[JIterable[B]] using the provided Function A ⇒ Future[B]. + * Transforms a JIterable[A] into a Future[JIterable[B]] using the provided Function A => Future[B]. * This is useful for performing a parallel map. For example, to apply a function to all items of a list * in parallel. */ def traverse[A, B](in: JIterable[A], fn: JFunc[A, Future[B]], executor: ExecutionContext): Future[JIterable[B]] = { implicit val d = executor - in.asScala.foldLeft(Future(new JLinkedList[B]())) { (fr, a) ⇒ + in.asScala.foldLeft(Future(new JLinkedList[B]())) { (fr, a) => val fb = fn(a) - for (r ← fr; b ← fb) yield { r add b; r } + for (r <- fr; b <- fb) yield { r add b; r } } } } @@ -208,7 +208,7 @@ object japi { } @deprecated("Do not use this directly, use subclasses of this", "2.0") - class UnitFunctionBridge[-T] extends (T ⇒ BoxedUnit) { + class UnitFunctionBridge[-T] extends (T => BoxedUnit) { final def apply$mcLJ$sp(l: Long): BoxedUnit = { internal(l.asInstanceOf[T]); BoxedUnit.UNIT } final def apply$mcLI$sp(i: Int): BoxedUnit = { internal(i.asInstanceOf[T]); BoxedUnit.UNIT } final def apply$mcLF$sp(f: Float): BoxedUnit = { internal(f.asInstanceOf[T]); BoxedUnit.UNIT } @@ -260,8 +260,8 @@ abstract class OnFailure extends japi.CallbackBridge[Throwable] { */ abstract class OnComplete[-T] extends japi.CallbackBridge[Try[T]] { protected final override def internal(value: Try[T]): Unit = value match { - case Failure(t) ⇒ onComplete(t, null.asInstanceOf[T]) - case Success(r) ⇒ onComplete(null, r) + case Failure(t) => onComplete(t, null.asInstanceOf[T]) + case Success(r) => onComplete(null, r) } /** @@ -321,7 +321,7 @@ abstract class Recover[+T] extends japi.RecoverBridge[T] { * to failure cases. */ object Filter { - def filterOf[T](f: akka.japi.Function[T, java.lang.Boolean]): (T ⇒ Boolean) = + def filterOf[T](f: akka.japi.Function[T, java.lang.Boolean]): (T => Boolean) = new Function1[T, Boolean] { def apply(result: T): Boolean = f(result).booleanValue() } } diff --git a/akka-actor/src/main/scala/akka/dispatch/Mailbox.scala b/akka-actor/src/main/scala/akka/dispatch/Mailbox.scala index cffccad4f6..7387fcaa57 100644 --- a/akka-actor/src/main/scala/akka/dispatch/Mailbox.scala +++ b/akka-actor/src/main/scala/akka/dispatch/Mailbox.scala @@ -142,9 +142,9 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue) */ @tailrec final def resume(): Boolean = currentStatus match { - case Closed ⇒ + case Closed => setStatus(Closed); false - case s ⇒ + case s => val next = if (s < suspendUnit) s else s - suspendUnit if (updateStatus(s, next)) next < suspendUnit else resume() @@ -158,9 +158,9 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue) */ @tailrec final def suspend(): Boolean = currentStatus match { - case Closed ⇒ + case Closed => setStatus(Closed); false - case s ⇒ + case s => if (updateStatus(s, s + suspendUnit)) s < suspendUnit else suspend() } @@ -171,9 +171,9 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue) */ @tailrec final def becomeClosed(): Boolean = currentStatus match { - case Closed ⇒ + case Closed => setStatus(Closed); false - case s ⇒ updateStatus(s, Closed) || becomeClosed() + case s => updateStatus(s, Closed) || becomeClosed() } /** @@ -213,9 +213,9 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue) Unsafe.instance.compareAndSwapObject(this, AbstractMailbox.systemMessageOffset, _old.head, _new.head) final def canBeScheduledForExecution(hasMessageHint: Boolean, hasSystemMessageHint: Boolean): Boolean = currentStatus match { - case Open | Scheduled ⇒ hasMessageHint || hasSystemMessageHint || hasSystemMessages || hasMessages - case Closed ⇒ false - case _ ⇒ hasSystemMessageHint || hasSystemMessages + case Open | Scheduled => hasMessageHint || hasSystemMessageHint || hasSystemMessages || hasMessages + case Closed => false + case _ => hasSystemMessageHint || hasSystemMessages } override final def run(): Unit = { @@ -233,14 +233,14 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue) override final def getRawResult(): Unit = () override final def setRawResult(unit: Unit): Unit = () final override def exec(): Boolean = try { run(); false } catch { - case _: InterruptedException ⇒ + case _: InterruptedException => Thread.currentThread.interrupt() false - case anything: Throwable ⇒ + case anything: Throwable => val t = Thread.currentThread t.getUncaughtExceptionHandler match { - case null ⇒ - case some ⇒ some.uncaughtException(t, anything) + case null => + case some => some.uncaughtException(t, anything) } throw anything } @@ -300,8 +300,8 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue) msg.unlink() try dlm.systemEnqueue(actor.self, msg) catch { - case e: InterruptedException ⇒ interruption = e - case NonFatal(e) ⇒ actor.system.eventStream.publish( + case e: InterruptedException => interruption = e + case NonFatal(e) => actor.system.eventStream.publish( Error(e, actor.self.path.toString, this.getClass, "error while enqueuing " + msg + " to deadLetters: " + e.getMessage)) } } @@ -438,7 +438,7 @@ private[akka] trait SystemMessageQueue { /** * INTERNAL API */ -private[akka] trait DefaultSystemMessageQueue { self: Mailbox ⇒ +private[akka] trait DefaultSystemMessageQueue { self: Mailbox => @tailrec final def systemEnqueue(receiver: ActorRef, message: SystemMessage): Unit = { @@ -464,8 +464,8 @@ private[akka] trait DefaultSystemMessageQueue { self: Mailbox ⇒ } def hasSystemMessages: Boolean = systemQueueGet.head match { - case null | NoMessage ⇒ false - case _ ⇒ true + case null | NoMessage => false + case _ => true } } @@ -813,8 +813,8 @@ trait ControlAwareMessageQueueSemantics extends QueueBasedMessageQueue { def queue: Queue[Envelope] def enqueue(receiver: ActorRef, handle: Envelope): Unit = handle match { - case envelope @ Envelope(_: ControlMessage, _) ⇒ controlQueue add envelope - case envelope ⇒ queue add envelope + case envelope @ Envelope(_: ControlMessage, _) => controlQueue add envelope + case envelope => queue add envelope } def dequeue(): Envelope = { @@ -883,8 +883,8 @@ object BoundedControlAwareMailbox { val queue = new ConcurrentLinkedQueue[Envelope]() override def enqueue(receiver: ActorRef, handle: Envelope): Unit = handle match { - case envelope @ Envelope(_: ControlMessage, _) ⇒ enqueueWithTimeout(controlQueue, receiver, envelope) - case envelope ⇒ enqueueWithTimeout(queue, receiver, envelope) + case envelope @ Envelope(_: ControlMessage, _) => enqueueWithTimeout(controlQueue, receiver, envelope) + case envelope => enqueueWithTimeout(queue, receiver, envelope) } override def numberOfMessages: Int = size.get() diff --git a/akka-actor/src/main/scala/akka/dispatch/Mailboxes.scala b/akka-actor/src/main/scala/akka/dispatch/Mailboxes.scala index 436a05de5f..c42399dbca 100644 --- a/akka-actor/src/main/scala/akka/dispatch/Mailboxes.scala +++ b/akka-actor/src/main/scala/akka/dispatch/Mailboxes.scala @@ -32,8 +32,8 @@ private[akka] class Mailboxes( val deadLetterMailbox: Mailbox = new Mailbox(new MessageQueue { def enqueue(receiver: ActorRef, envelope: Envelope): Unit = envelope.message match { - case _: DeadLetter ⇒ // actor subscribing to DeadLetter, drop it - case msg ⇒ deadLetters.tell(DeadLetter(msg, envelope.sender, receiver), envelope.sender) + case _: DeadLetter => // actor subscribing to DeadLetter, drop it + case msg => deadLetters.tell(DeadLetter(msg, envelope.sender, receiver), envelope.sender) } def dequeue() = null def hasMessages = false @@ -53,11 +53,11 @@ private[akka] class Mailboxes( import scala.collection.JavaConverters._ settings.config.getConfig("akka.actor.mailbox.requirements").root.unwrapped.asScala .toMap.foldLeft(Map.empty[Class[_ <: Any], String]) { - case (m, (k, v)) ⇒ + case (m, (k, v)) => dynamicAccess.getClassFor[Any](k).map { - case x ⇒ m.updated(x, v.toString) + case x => m.updated(x, v.toString) }.recover { - case e ⇒ + case e => throw new ConfigurationException(s"Type [${k}] specified as akka.actor.mailbox.requirement " + s"[${v}] in config can't be loaded due to [${e.getMessage}]", e) }.get @@ -80,9 +80,9 @@ private[akka] class Mailboxes( */ def getRequiredType(actorClass: Class[_ <: Actor]): Class[_] = Reflect.findMarker(actorClass, rmqClass) match { - case t: ParameterizedType ⇒ t.getActualTypeArguments.head match { - case c: Class[_] ⇒ c - case x ⇒ throw new IllegalArgumentException(s"no wildcard type allowed in RequireMessageQueue argument (was [$x])") + case t: ParameterizedType => t.getActualTypeArguments.head match { + case c: Class[_] => c + case x => throw new IllegalArgumentException(s"no wildcard type allowed in RequireMessageQueue argument (was [$x])") } } @@ -91,18 +91,18 @@ private[akka] class Mailboxes( private var mailboxNonZeroPushTimeoutWarningIssued = false def getMailboxRequirement(config: Config) = config.getString("mailbox-requirement") match { - case NoMailboxRequirement ⇒ classOf[MessageQueue] - case x ⇒ dynamicAccess.getClassFor[AnyRef](x).get + case NoMailboxRequirement => classOf[MessageQueue] + case x => dynamicAccess.getClassFor[AnyRef](x).get } def getProducedMessageQueueType(mailboxType: MailboxType): Class[_] = { val pmqClass = classOf[ProducesMessageQueue[_]] if (!pmqClass.isAssignableFrom(mailboxType.getClass)) classOf[MessageQueue] else Reflect.findMarker(mailboxType.getClass, pmqClass) match { - case t: ParameterizedType ⇒ + case t: ParameterizedType => t.getActualTypeArguments.head match { - case c: Class[_] ⇒ c - case x ⇒ throw new IllegalArgumentException( + case c: Class[_] => c + case x => throw new IllegalArgumentException( s"no wildcard type allowed in ProducesMessageQueue argument (was [$x])") } } @@ -152,7 +152,7 @@ private[akka] class Mailboxes( } else if (hasRequiredType(actorClass)) { try verifyRequirements(lookupByQueueType(getRequiredType(actorClass))) catch { - case NonFatal(_) if (hasMailboxRequirement) ⇒ verifyRequirements(lookupByQueueType(mailboxRequirement)) + case NonFatal(_) if (hasMailboxRequirement) => verifyRequirements(lookupByQueueType(mailboxRequirement)) } } else if (hasMailboxRequirement) { verifyRequirements(lookupByQueueType(mailboxRequirement)) @@ -168,28 +168,28 @@ private[akka] class Mailboxes( private def lookupId(queueType: Class[_]): String = mailboxBindings.get(queueType) match { - case None ⇒ throw new ConfigurationException(s"Mailbox Mapping for [${queueType}] not configured") - case Some(s) ⇒ s + case None => throw new ConfigurationException(s"Mailbox Mapping for [${queueType}] not configured") + case Some(s) => s } private def lookupConfigurator(id: String): MailboxType = { mailboxTypeConfigurators.get(id) match { - case null ⇒ + case null => // It doesn't matter if we create a mailbox type configurator that isn't used due to concurrent lookup. val newConfigurator = id match { // TODO RK remove these two for Akka 2.3 - case "unbounded" ⇒ UnboundedMailbox() - case "bounded" ⇒ new BoundedMailbox(settings, config(id)) - case _ ⇒ + case "unbounded" => UnboundedMailbox() + case "bounded" => new BoundedMailbox(settings, config(id)) + case _ => if (!settings.config.hasPath(id)) throw new ConfigurationException(s"Mailbox Type [${id}] not configured") val conf = config(id) val mailboxType = conf.getString("mailbox-type") match { - case "" ⇒ throw new ConfigurationException(s"The setting mailbox-type, defined in [$id] is empty") - case fqcn ⇒ - val args = List(classOf[ActorSystem.Settings] → settings, classOf[Config] → conf) + case "" => throw new ConfigurationException(s"The setting mailbox-type, defined in [$id] is empty") + case fqcn => + val args = List(classOf[ActorSystem.Settings] -> settings, classOf[Config] -> conf) dynamicAccess.createInstanceFor[MailboxType](fqcn, args).recover({ - case exception ⇒ + case exception => throw new IllegalArgumentException( s"Cannot instantiate MailboxType [$fqcn], defined in [$id], make sure it has a public" + " constructor with [akka.actor.ActorSystem.Settings, com.typesafe.config.Config] parameters", @@ -199,12 +199,12 @@ private[akka] class Mailboxes( if (!mailboxNonZeroPushTimeoutWarningIssued) { mailboxType match { - case m: ProducesPushTimeoutSemanticsMailbox if m.pushTimeOut.toNanos > 0L ⇒ + case m: ProducesPushTimeoutSemanticsMailbox if m.pushTimeOut.toNanos > 0L => warn(s"Configured potentially-blocking mailbox [$id] configured with non-zero pushTimeOut (${m.pushTimeOut}), " + s"which can lead to blocking behavior when sending messages to this mailbox. " + s"Avoid this by setting `$id.mailbox-push-timeout-time` to `0`.") mailboxNonZeroPushTimeoutWarningIssued = true - case _ ⇒ // good; nothing to see here, move along, sir. + case _ => // good; nothing to see here, move along, sir. } } @@ -212,11 +212,11 @@ private[akka] class Mailboxes( } mailboxTypeConfigurators.putIfAbsent(id, newConfigurator) match { - case null ⇒ newConfigurator - case existing ⇒ existing + case null => newConfigurator + case existing => existing } - case existing ⇒ existing + case existing => existing } } @@ -228,7 +228,7 @@ private[akka] class Mailboxes( //INTERNAL API private def config(id: String): Config = { import scala.collection.JavaConverters._ - ConfigFactory.parseMap(Map("id" → id).asJava) + ConfigFactory.parseMap(Map("id" -> id).asJava) .withFallback(settings.config.getConfig(id)) .withFallback(defaultMailboxConfig) } @@ -253,8 +253,8 @@ private[akka] class Mailboxes( val cache = stashCapacityCache.get val key = dispatcher + "-" + mailbox cache.get(key) match { - case Some(value) ⇒ value - case None ⇒ + case Some(value) => value + case None => val value = stashCapacityFromConfig(dispatcher, mailbox) updateCache(cache, key, value) value diff --git a/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala b/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala index b9867b2202..073197e19e 100644 --- a/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala +++ b/akka-actor/src/main/scala/akka/dispatch/ThreadPoolBuilder.scala @@ -24,7 +24,7 @@ import java.util.concurrent.{ import java.util.concurrent.atomic.{ AtomicReference, AtomicLong } object ThreadPoolConfig { - type QueueFactory = () ⇒ BlockingQueue[Runnable] + type QueueFactory = () => BlockingQueue[Runnable] val defaultAllowCoreThreadTimeout: Boolean = false val defaultCorePoolSize: Int = 16 @@ -35,15 +35,15 @@ object ThreadPoolConfig { def scaledPoolSize(floor: Int, multiplier: Double, ceiling: Int): Int = math.min(math.max((Runtime.getRuntime.availableProcessors * multiplier).ceil.toInt, floor), ceiling) - def arrayBlockingQueue(capacity: Int, fair: Boolean): QueueFactory = () ⇒ new ArrayBlockingQueue[Runnable](capacity, fair) + def arrayBlockingQueue(capacity: Int, fair: Boolean): QueueFactory = () => new ArrayBlockingQueue[Runnable](capacity, fair) - def synchronousQueue(fair: Boolean): QueueFactory = () ⇒ new SynchronousQueue[Runnable](fair) + def synchronousQueue(fair: Boolean): QueueFactory = () => new SynchronousQueue[Runnable](fair) - def linkedBlockingQueue(): QueueFactory = () ⇒ new LinkedBlockingQueue[Runnable]() + def linkedBlockingQueue(): QueueFactory = () => new LinkedBlockingQueue[Runnable]() - def linkedBlockingQueue(capacity: Int): QueueFactory = () ⇒ new LinkedBlockingQueue[Runnable](capacity) + def linkedBlockingQueue(capacity: Int): QueueFactory = () => new LinkedBlockingQueue[Runnable](capacity) - def reusableQueue(queue: BlockingQueue[Runnable]): QueueFactory = () ⇒ queue + def reusableQueue(queue: BlockingQueue[Runnable]): QueueFactory = () => queue def reusableQueue(queueFactory: QueueFactory): QueueFactory = reusableQueue(queueFactory()) } @@ -91,10 +91,10 @@ final case class ThreadPoolConfig( } final def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory = { val tf = threadFactory match { - case m: MonitorableThreadFactory ⇒ + case m: MonitorableThreadFactory => // add the dispatcher id to the thread names m.withName(m.name + "-" + id) - case other ⇒ other + case other => other } new ThreadPoolExecutorServiceFactory(tf) } @@ -152,7 +152,7 @@ final case class ThreadPoolConfigBuilder(config: ThreadPoolConfig) { this.copy(config = config.copy(queueFactory = newQueueFactory)) def configure(fs: Option[Function[ThreadPoolConfigBuilder, ThreadPoolConfigBuilder]]*): ThreadPoolConfigBuilder = - fs.foldLeft(this)((c, f) ⇒ f.map(_(c)).getOrElse(c)) + fs.foldLeft(this)((c, f) => f.map(_(c)).getOrElse(c)) } object MonitorableThreadFactory { @@ -160,7 +160,7 @@ object MonitorableThreadFactory { new Thread.UncaughtExceptionHandler() { def uncaughtException(thread: Thread, cause: Throwable) = () } private[akka] class AkkaForkJoinWorkerThread(_pool: ForkJoinPool) extends ForkJoinWorkerThread(_pool) with BlockContext { - override def blockOn[T](thunk: ⇒ T)(implicit permission: CanAwait): T = { + override def blockOn[T](thunk: => T)(implicit permission: CanAwait): T = { val result = new AtomicReference[Option[T]](None) ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker { def block(): Boolean = { diff --git a/akka-actor/src/main/scala/akka/dispatch/affinity/AffinityPool.scala b/akka-actor/src/main/scala/akka/dispatch/affinity/AffinityPool.scala index 704b15b300..49c1aca1c0 100644 --- a/akka-actor/src/main/scala/akka/dispatch/affinity/AffinityPool.scala +++ b/akka-actor/src/main/scala/akka/dispatch/affinity/AffinityPool.scala @@ -47,7 +47,7 @@ private[affinity] object AffinityPool { try OptionVal.Some(MethodHandles.lookup.findStatic(classOf[Thread], "onSpinWait", methodType(classOf[Void]))) catch { - case NonFatal(_) ⇒ OptionVal.None + case NonFatal(_) => OptionVal.None } type IdleState = Int @@ -82,24 +82,24 @@ private[affinity] object AffinityPool { final def idle(): Unit = { (state: @switch) match { - case Initial ⇒ + case Initial => idling = true transitionTo(Spinning) - case Spinning ⇒ + case Spinning => onSpinWaitMethodHandle match { - case OptionVal.Some(m) ⇒ m.invokeExact() - case OptionVal.None ⇒ + case OptionVal.Some(m) => m.invokeExact() + case OptionVal.None => } turns += 1 if (turns > maxSpins) transitionTo(Yielding) - case Yielding ⇒ + case Yielding => turns += 1 if (turns > maxYields) { parkPeriodNs = minParkPeriodNs transitionTo(Parking) } else Thread.`yield`() - case Parking ⇒ + case Parking => LockSupport.parkNanos(parkPeriodNs) parkPeriodNs = Math.min(parkPeriodNs << 1, maxParkPeriodNs) } @@ -159,7 +159,7 @@ private[akka] class AffinityPool( bookKeepingLock.withGuard { if (poolState == Uninitialized) { poolState = Initializing - workQueues.foreach(q ⇒ addWorker(workers, q)) + workQueues.foreach(q => addWorker(workers, q)) poolState = Running } this @@ -278,14 +278,14 @@ private[akka] class AffinityPool( @tailrec def runLoop(): Unit = if (!Thread.interrupted()) { (poolState: @switch) match { - case Uninitialized ⇒ () - case Initializing | Running ⇒ + case Uninitialized => () + case Initializing | Running => executeNext() runLoop() - case ShuttingDown ⇒ + case ShuttingDown => if (executeNext()) runLoop() else () - case ShutDown | Terminated ⇒ () + case ShutDown | Terminated => () } } @@ -318,31 +318,31 @@ private[akka] final class AffinityPoolConfigurator(config: Config, prerequisites config.getInt("parallelism-max")) private val taskQueueSize = config.getInt("task-queue-size") - private val idleCpuLevel = config.getInt("idle-cpu-level").requiring(level ⇒ + private val idleCpuLevel = config.getInt("idle-cpu-level").requiring(level => 1 <= level && level <= 10, "idle-cpu-level must be between 1 and 10") private val queueSelectorFactoryFQCN = config.getString("queue-selector") private val queueSelectorFactory: QueueSelectorFactory = - prerequisites.dynamicAccess.createInstanceFor[QueueSelectorFactory](queueSelectorFactoryFQCN, immutable.Seq(classOf[Config] → config)) + prerequisites.dynamicAccess.createInstanceFor[QueueSelectorFactory](queueSelectorFactoryFQCN, immutable.Seq(classOf[Config] -> config)) .recover({ - case _ ⇒ throw new IllegalArgumentException( + case _ => throw new IllegalArgumentException( s"Cannot instantiate QueueSelectorFactory(queueSelector = $queueSelectorFactoryFQCN), make sure it has an accessible constructor which accepts a Config parameter") }).get private val rejectionHandlerFactoryFCQN = config.getString("rejection-handler") private val rejectionHandlerFactory = prerequisites.dynamicAccess .createInstanceFor[RejectionHandlerFactory](rejectionHandlerFactoryFCQN, Nil).recover({ - case exception ⇒ throw new IllegalArgumentException( + case exception => throw new IllegalArgumentException( s"Cannot instantiate RejectionHandlerFactory(rejection-handler = $rejectionHandlerFactoryFCQN), make sure it has an accessible empty constructor", exception) }).get override def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory = { val tf = threadFactory match { - case m: MonitorableThreadFactory ⇒ + case m: MonitorableThreadFactory => // add the dispatcher id to the thread names m.withName(m.name + "-" + id) - case other ⇒ other + case other => other } new ExecutorServiceFactory { @@ -396,7 +396,7 @@ private[akka] final class ThrowOnOverflowRejectionHandler extends RejectionHandl private[akka] final class FairDistributionHashCache( final val config: Config) extends QueueSelectorFactory { private final val MaxFairDistributionThreshold = 2048 - private[this] final val fairDistributionThreshold = config.getInt("fair-work-distribution.threshold").requiring(thr ⇒ + private[this] final val fairDistributionThreshold = config.getInt("fair-work-distribution.threshold").requiring(thr => 0 <= thr && thr <= MaxFairDistributionThreshold, s"fair-work-distribution.threshold must be between 0 and $MaxFairDistributionThreshold") override final def create(): QueueSelector = new AtomicReference[ImmutableIntMap](ImmutableIntMap.empty) with QueueSelector { diff --git a/akka-actor/src/main/scala/akka/event/ActorClassificationUnsubscriber.scala b/akka-actor/src/main/scala/akka/event/ActorClassificationUnsubscriber.scala index 86b48f09fc..1eb86455cd 100644 --- a/akka-actor/src/main/scala/akka/event/ActorClassificationUnsubscriber.scala +++ b/akka-actor/src/main/scala/akka/event/ActorClassificationUnsubscriber.scala @@ -28,25 +28,25 @@ protected[akka] class ActorClassificationUnsubscriber(bus: ManagedActorClassific } def receive = { - case Register(actor, seq) if seq == nextSeq ⇒ + case Register(actor, seq) if seq == nextSeq => if (debug) context.system.eventStream.publish(Logging.Debug(simpleName(getClass), getClass, s"registered watch for $actor in $bus")) context watch actor atSeq = nextSeq unstashAll() - case _: Register ⇒ + case _: Register => stash() - case Unregister(actor, seq) if seq == nextSeq ⇒ + case Unregister(actor, seq) if seq == nextSeq => if (debug) context.system.eventStream.publish(Logging.Debug(simpleName(getClass), getClass, s"unregistered watch of $actor in $bus")) context unwatch actor atSeq = nextSeq unstashAll() - case _: Unregister ⇒ + case _: Unregister => stash() - case Terminated(actor) ⇒ + case Terminated(actor) => if (debug) context.system.eventStream.publish(Logging.Debug(simpleName(getClass), getClass, s"actor $actor has terminated, unsubscribing it from $bus")) // the `unsubscribe` will trigger another `Unregister(actor, _)` message to this unsubscriber; // but since that actor is terminated, there cannot be any harm in processing an Unregister for it. diff --git a/akka-actor/src/main/scala/akka/event/DeadLetterListener.scala b/akka-actor/src/main/scala/akka/event/DeadLetterListener.scala index 8880b77ab7..bdf8d67e79 100644 --- a/akka-actor/src/main/scala/akka/event/DeadLetterListener.scala +++ b/akka-actor/src/main/scala/akka/event/DeadLetterListener.scala @@ -27,7 +27,7 @@ class DeadLetterListener extends Actor { eventStream.unsubscribe(self) def receive = { - case DeadLetter(message, snd, rcp) ⇒ + case DeadLetter(message, snd, rcp) => count += 1 val origin = if (snd eq context.system.deadLetters) "without sender" else s"from $snd" val done = maxCount != Int.MaxValue && count >= maxCount diff --git a/akka-actor/src/main/scala/akka/event/EventBus.scala b/akka-actor/src/main/scala/akka/event/EventBus.scala index ff3b6f16f4..a5210fc1ac 100644 --- a/akka-actor/src/main/scala/akka/event/EventBus.scala +++ b/akka-actor/src/main/scala/akka/event/EventBus.scala @@ -61,15 +61,15 @@ trait ActorEventBus extends EventBus { /** * Can be mixed into an EventBus to specify that the Classifier type is ActorRef */ -trait ActorClassifier { this: EventBus ⇒ +trait ActorClassifier { this: EventBus => type Classifier = ActorRef } /** * Can be mixed into an EventBus to specify that the Classifier type is a Function from Event to Boolean (predicate) */ -trait PredicateClassifier { this: EventBus ⇒ - type Classifier = Event ⇒ Boolean +trait PredicateClassifier { this: EventBus => + type Classifier = Event => Boolean } /** @@ -78,7 +78,7 @@ trait PredicateClassifier { this: EventBus ⇒ * * The compareSubscribers need to provide a total ordering of the Subscribers */ -trait LookupClassification { this: EventBus ⇒ +trait LookupClassification { this: EventBus => protected final val subscribers = new Index[Classifier, Subscriber](mapSize(), new Comparator[Subscriber] { def compare(a: Subscriber, b: Subscriber): Int = compareSubscribers(a, b) @@ -120,7 +120,7 @@ trait LookupClassification { this: EventBus ⇒ * Classification which respects relationships between channels: subscribing * to one channel automatically and idempotently subscribes to all sub-channels. */ -trait SubchannelClassification { this: EventBus ⇒ +trait SubchannelClassification { this: EventBus => /** * The logic to form sub-class hierarchy @@ -186,12 +186,12 @@ trait SubchannelClassification { this: EventBus ⇒ private def removeFromCache(changes: immutable.Seq[(Classifier, Set[Subscriber])]): Unit = cache = changes.foldLeft(cache) { - case (m, (c, cs)) ⇒ m.updated(c, m.getOrElse(c, Set.empty[Subscriber]) diff cs) + case (m, (c, cs)) => m.updated(c, m.getOrElse(c, Set.empty[Subscriber]) diff cs) } private def addToCache(changes: immutable.Seq[(Classifier, Set[Subscriber])]): Unit = cache = changes.foldLeft(cache) { - case (m, (c, cs)) ⇒ m.updated(c, m.getOrElse(c, Set.empty[Subscriber]) union cs) + case (m, (c, cs)) => m.updated(c, m.getOrElse(c, Set.empty[Subscriber]) union cs) } } @@ -202,11 +202,11 @@ trait SubchannelClassification { this: EventBus ⇒ * * Note: the compareClassifiers and compareSubscribers must together form an absolute ordering (think java.util.Comparator.compare) */ -trait ScanningClassification { self: EventBus ⇒ +trait ScanningClassification { self: EventBus => protected final val subscribers = new ConcurrentSkipListSet[(Classifier, Subscriber)](new Comparator[(Classifier, Subscriber)] { def compare(a: (Classifier, Subscriber), b: (Classifier, Subscriber)): Int = compareClassifiers(a._1, b._1) match { - case 0 ⇒ compareSubscribers(a._2, b._2) - case other ⇒ other + case 0 => compareSubscribers(a._2, b._2) + case other => other } }) @@ -258,7 +258,7 @@ trait ScanningClassification { self: EventBus ⇒ * All subscribers will be watched by an `akka.event.ActorClassificationUnsubscriber` and unsubscribed when they terminate. * The unsubscriber actor will not be stopped automatically, and if you want to stop using the bus you should stop it yourself. */ -trait ManagedActorClassification { this: ActorEventBus with ActorClassifier ⇒ +trait ManagedActorClassification { this: ActorEventBus with ActorClassifier => import scala.annotation.tailrec protected def system: ActorSystem @@ -296,13 +296,13 @@ trait ManagedActorClassification { this: ActorEventBus with ActorClassifier ⇒ val current = mappings.get current.backing.get(monitored) match { - case None ⇒ + case None => val added = current.add(monitored, monitor) if (mappings.compareAndSet(current, added)) registerWithUnsubscriber(monitor, added.seqNr) else associate(monitored, monitor) - case Some(monitors) ⇒ + case Some(monitors) => if (monitors.contains(monitored)) false else { val added = current.add(monitored, monitor) @@ -332,10 +332,10 @@ trait ManagedActorClassification { this: ActorEventBus with ActorClassifier ⇒ while (i.hasNext) { val (key, value) = i.next() value match { - case null ⇒ + case null => // do nothing - case monitors ⇒ + case monitors => if (monitors.contains(monitor)) dissociate(key, monitor) } @@ -350,8 +350,8 @@ trait ManagedActorClassification { this: ActorEventBus with ActorClassifier ⇒ val current = mappings.get current.backing.get(monitored) match { - case None ⇒ false - case Some(monitors) ⇒ + case None => false + case Some(monitors) => val removed = current.remove(monitored, monitor) val removedMonitors = removed.get(monitored) @@ -376,8 +376,8 @@ trait ManagedActorClassification { this: ActorEventBus with ActorClassifier ⇒ def publish(event: Event): Unit = { mappings.get.backing.get(classify(event)) match { - case None ⇒ () - case Some(refs) ⇒ refs.foreach { _ ! event } + case None => () + case Some(refs) => refs.foreach { _ ! event } } } diff --git a/akka-actor/src/main/scala/akka/event/EventStream.scala b/akka-actor/src/main/scala/akka/event/EventStream.scala index b1fc156014..9b04a44002 100644 --- a/akka-actor/src/main/scala/akka/event/EventStream.scala +++ b/akka-actor/src/main/scala/akka/event/EventStream.scala @@ -79,7 +79,7 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB // sys may be null for backwards compatibility reasons if (sys eq null) false else initiallySubscribedOrUnsubscriber.get match { - case value @ Left(subscribers) ⇒ + case value @ Left(subscribers) => if (initiallySubscribedOrUnsubscriber.compareAndSet(value, Right(unsubscriber))) { if (debug) publish(Logging.Debug(simpleName(this), this.getClass, "initialized unsubscriber to: " + unsubscriber + ", registering " + subscribers.size + " initial subscribers with it")) subscribers foreach registerWithUnsubscriber @@ -90,7 +90,7 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB initUnsubscriber(unsubscriber) } - case Right(presentUnsubscriber) ⇒ + case Right(presentUnsubscriber) => if (debug) publish(Logging.Debug(simpleName(this), this.getClass, s"not using unsubscriber $unsubscriber, because already initialized with $presentUnsubscriber")) false } @@ -103,11 +103,11 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB private def registerWithUnsubscriber(subscriber: ActorRef): Unit = { // sys may be null for backwards compatibility reasons if (sys ne null) initiallySubscribedOrUnsubscriber.get match { - case value @ Left(subscribers) ⇒ + case value @ Left(subscribers) => if (!initiallySubscribedOrUnsubscriber.compareAndSet(value, Left(subscribers + subscriber))) registerWithUnsubscriber(subscriber) - case Right(unsubscriber) ⇒ + case Right(unsubscriber) => unsubscriber ! EventStreamUnsubscriber.Register(subscriber) } } @@ -123,11 +123,11 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB private def unregisterIfNoMoreSubscribedChannels(subscriber: ActorRef): Unit = { // sys may be null for backwards compatibility reasons if (sys ne null) initiallySubscribedOrUnsubscriber.get match { - case value @ Left(subscribers) ⇒ + case value @ Left(subscribers) => if (!initiallySubscribedOrUnsubscriber.compareAndSet(value, Left(subscribers - subscriber))) unregisterIfNoMoreSubscribedChannels(subscriber) - case Right(unsubscriber) ⇒ + case Right(unsubscriber) => unsubscriber ! EventStreamUnsubscriber.UnregisterIfNoMoreSubscribedChannels(subscriber) } } diff --git a/akka-actor/src/main/scala/akka/event/EventStreamUnsubscriber.scala b/akka-actor/src/main/scala/akka/event/EventStreamUnsubscriber.scala index ddd85f5396..90f9483ccb 100644 --- a/akka-actor/src/main/scala/akka/event/EventStreamUnsubscriber.scala +++ b/akka-actor/src/main/scala/akka/event/EventStreamUnsubscriber.scala @@ -30,19 +30,19 @@ protected[akka] class EventStreamUnsubscriber(eventStream: EventStream, debug: B } def receive = { - case Register(actor) ⇒ + case Register(actor) => if (debug) eventStream.publish(Logging.Debug(simpleName(getClass), getClass, s"watching $actor in order to unsubscribe from EventStream when it terminates")) context watch actor - case UnregisterIfNoMoreSubscribedChannels(actor) if eventStream.hasSubscriptions(actor) ⇒ + case UnregisterIfNoMoreSubscribedChannels(actor) if eventStream.hasSubscriptions(actor) => // do nothing // hasSubscriptions can be slow, but it's better for this actor to take the hit than the EventStream - case UnregisterIfNoMoreSubscribedChannels(actor) ⇒ + case UnregisterIfNoMoreSubscribedChannels(actor) => if (debug) eventStream.publish(Logging.Debug(simpleName(getClass), getClass, s"unwatching $actor, since has no subscriptions")) context unwatch actor - case Terminated(actor) ⇒ + case Terminated(actor) => if (debug) eventStream.publish(Logging.Debug(simpleName(getClass), getClass, s"unsubscribe $actor from $eventStream, because it was terminated")) eventStream unsubscribe actor } diff --git a/akka-actor/src/main/scala/akka/event/LoggerMailbox.scala b/akka-actor/src/main/scala/akka/event/LoggerMailbox.scala index cb077a8f33..bcd0efa1e1 100644 --- a/akka-actor/src/main/scala/akka/event/LoggerMailbox.scala +++ b/akka-actor/src/main/scala/akka/event/LoggerMailbox.scala @@ -23,8 +23,8 @@ private[akka] class LoggerMailboxType(@unused settings: ActorSystem.Settings, @u with ProducesMessageQueue[LoggerMailbox] { override def create(owner: Option[ActorRef], system: Option[ActorSystem]) = (owner, system) match { - case (Some(o), Some(s)) ⇒ new LoggerMailbox(o, s) - case _ ⇒ throw new IllegalArgumentException("no mailbox owner or system given") + case (Some(o), Some(s)) => new LoggerMailbox(o, s) + case _ => throw new IllegalArgumentException("no mailbox owner or system given") } } @@ -46,10 +46,10 @@ private[akka] class LoggerMailbox(@unused owner: ActorRef, system: ActorSystem) // skip logging if level is OFF if (loggingEnabled) envelope.message match { - case e: LogEvent if e.level <= logLevel ⇒ + case e: LogEvent if e.level <= logLevel => // Logging.StandardOutLogger is a MinimalActorRef, i.e. not a "real" actor Logging.StandardOutLogger.tell(envelope.message, envelope.sender) - case _ ⇒ // skip + case _ => // skip } envelope = dequeue diff --git a/akka-actor/src/main/scala/akka/event/Logging.scala b/akka-actor/src/main/scala/akka/event/Logging.scala index 6e763abb8e..82e5fedc80 100644 --- a/akka-actor/src/main/scala/akka/event/Logging.scala +++ b/akka-actor/src/main/scala/akka/event/Logging.scala @@ -58,16 +58,16 @@ trait LoggingBus extends ActorEventBus { def setLogLevel(level: LogLevel): Unit = guard.withGuard { val logLvl = _logLevel // saves (2 * AllLogLevel.size - 1) volatile reads (because of the loops below) for { - l ← AllLogLevels + l <- AllLogLevels // subscribe if previously ignored and now requested if l > logLvl && l <= level - log ← loggers + log <- loggers } subscribe(log, classFor(l)) for { - l ← AllLogLevels + l <- AllLogLevels // unsubscribe if previously registered and now ignored if l <= logLvl && l > level - log ← loggers + log <- loggers } unsubscribe(log, classFor(l)) _logLevel = level } @@ -78,7 +78,7 @@ trait LoggingBus extends ActorEventBus { StandardOutLogger.print(Error(new LoggerException, simpleName(this), this.getClass, "unknown akka.stdout-loglevel " + config.StdoutLogLevel)) ErrorLevel } - AllLogLevels filter (level >= _) foreach (l ⇒ subscribe(StandardOutLogger, classFor(l))) + AllLogLevels filter (level >= _) foreach (l => subscribe(StandardOutLogger, classFor(l))) guard.withGuard { loggers :+= StandardOutLogger _logLevel = level @@ -105,18 +105,18 @@ trait LoggingBus extends ActorEventBus { } try { val defaultLoggers = system.settings.Loggers match { - case Nil ⇒ classOf[DefaultLogger].getName :: Nil - case loggers ⇒ loggers + case Nil => classOf[DefaultLogger].getName :: Nil + case loggers => loggers } val myloggers = for { - loggerName ← defaultLoggers + loggerName <- defaultLoggers if loggerName != StandardOutLogger.getClass.getName } yield { system.dynamicAccess.getClassFor[Actor](loggerName).map({ - case actorClass ⇒ addLogger(system, actorClass, level, logName) + case actorClass => addLogger(system, actorClass, level, logName) }).recover({ - case e ⇒ throw new ConfigurationException( + case e => throw new ConfigurationException( "Logger specified in config can't be loaded [" + loggerName + "] due to [" + e.toString + "]", e) }).get @@ -129,19 +129,19 @@ trait LoggingBus extends ActorEventBus { if (system.settings.DebugUnhandledMessage) subscribe(system.systemActorOf(Props(new Actor { def receive = { - case UnhandledMessage(msg, sender, rcp) ⇒ + case UnhandledMessage(msg, sender, rcp) => publish(Debug(rcp.path.toString, rcp.getClass, "unhandled message from " + sender + ": " + msg)) } }), "UnhandledMessageForwarder"), classOf[UnhandledMessage]) } catch { - case _: InvalidActorNameException ⇒ // ignore if it is already running + case _: InvalidActorNameException => // ignore if it is already running } publish(Debug(logName, this.getClass, "Default Loggers started")) if (!(defaultLoggers contains StandardOutLogger.getClass.getName)) { unsubscribe(StandardOutLogger) } } catch { - case e: Exception ⇒ + case e: Exception => System.err.println("error while starting up loggers") e.printStackTrace() throw new ConfigurationException("Could not start logger due to [" + e.toString + "]") @@ -158,14 +158,14 @@ trait LoggingBus extends ActorEventBus { publish(Debug(simpleName(this), this.getClass, "shutting down: StandardOutLogger")) } for { - logger ← loggers + logger <- loggers if logger != StandardOutLogger } { // this is very necessary, else you get infinite loop with DeadLetter unsubscribe(logger) logger match { - case ref: InternalActorRef ⇒ ref.stop() - case _ ⇒ + case ref: InternalActorRef => ref.stop() + case _ => } } publish(Debug(simpleName(this), this.getClass, "all default loggers stopped")) @@ -180,13 +180,13 @@ trait LoggingBus extends ActorEventBus { implicit def timeout = system.settings.LoggerStartTimeout import akka.pattern.ask val response = try Await.result(actor ? InitializeLogger(this), timeout.duration) catch { - case _: TimeoutException ⇒ + case _: TimeoutException => publish(Warning(logName, this.getClass, "Logger " + name + " did not respond within " + timeout + " to InitializeLogger(bus)")) "[TIMEOUT]" } if (response != LoggerInitialized) throw new LoggerInitializationException("Logger " + name + " did not respond with LoggerInitialized, sent instead " + response) - AllLogLevels filter (level >= _) foreach (l ⇒ subscribe(actor, classFor(l))) + AllLogLevels filter (level >= _) foreach (l => subscribe(actor, classFor(l))) publish(Debug(logName, this.getClass, "logger " + name + " started")) actor } @@ -285,7 +285,7 @@ object LogSource { a.path.toStringWithAddress(system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress) } catch { // it can fail if the ActorSystem (remoting) is not completely started yet - case NonFatal(_) ⇒ a.path.toString + case NonFatal(_) => a.path.toString } } @@ -322,11 +322,11 @@ object LogSource { */ def fromAnyRef(o: AnyRef): (String, Class[_]) = o match { - case c: Class[_] ⇒ apply(c) - case a: Actor ⇒ apply(a) - case a: ActorRef ⇒ apply(a) - case s: String ⇒ apply(s) - case x ⇒ (Logging.simpleName(x), x.getClass) + case c: Class[_] => apply(c) + case a: Actor => apply(a) + case a: ActorRef => apply(a) + case s: String => apply(s) + case x => (Logging.simpleName(x), x.getClass) } /** @@ -336,11 +336,11 @@ object LogSource { */ def fromAnyRef(o: AnyRef, system: ActorSystem): (String, Class[_]) = o match { - case c: Class[_] ⇒ apply(c) - case a: Actor ⇒ apply(a) - case a: ActorRef ⇒ apply(a) - case s: String ⇒ apply(s) - case x ⇒ (Logging.simpleName(x) + "(" + system + ")", x.getClass) + case c: Class[_] => apply(c) + case a: Actor => apply(a) + case a: ActorRef => apply(a) + case s: String => apply(s) + case x => (Logging.simpleName(x) + "(" + system + ")", x.getClass) } } @@ -401,9 +401,9 @@ object Logging { * wrapped message. */ def messageClassName(message: Any): String = message match { - case null ⇒ "null" - case ActorSelectionMessage(m, _, _) ⇒ s"ActorSelectionMessage(${m.getClass.getName})" - case m ⇒ m.getClass.getName + case null => "null" + case ActorSelectionMessage(m, _, _) => s"ActorSelectionMessage(${m.getClass.getName})" + case m => m.getClass.getName } /** @@ -458,12 +458,12 @@ object Logging { * "error", "warning", "info" and "debug" */ def levelFor(s: String): Option[LogLevel] = Helpers.toRootLowerCase(s) match { - case "off" ⇒ Some(OffLevel) - case "error" ⇒ Some(ErrorLevel) - case "warning" ⇒ Some(WarningLevel) - case "info" ⇒ Some(InfoLevel) - case "debug" ⇒ Some(DebugLevel) - case _ ⇒ None + case "off" => Some(OffLevel) + case "error" => Some(ErrorLevel) + case "warning" => Some(WarningLevel) + case "info" => Some(InfoLevel) + case "debug" => Some(DebugLevel) + case _ => None } /** @@ -482,11 +482,11 @@ object Logging { * Returns the event class associated with the given LogLevel */ def classFor(level: LogLevel): Class[_ <: LogEvent] = level match { - case ErrorLevel ⇒ classOf[Error] - case WarningLevel ⇒ classOf[Warning] - case InfoLevel ⇒ classOf[Info] - case DebugLevel ⇒ classOf[Debug] - case level ⇒ throw new IllegalArgumentException(s"Unsupported log level [$level]") + case ErrorLevel => classOf[Error] + case WarningLevel => classOf[Warning] + case InfoLevel => classOf[Info] + case DebugLevel => classOf[Debug] + case level => throw new IllegalArgumentException(s"Unsupported log level [$level]") } // these type ascriptions/casts are necessary to avoid CCEs during construction while retaining correct type @@ -719,27 +719,27 @@ object Logging { object LogEvent { def apply(level: LogLevel, logSource: String, logClass: Class[_], message: Any): LogEvent = level match { - case ErrorLevel ⇒ Error(logSource, logClass, message) - case WarningLevel ⇒ Warning(logSource, logClass, message) - case InfoLevel ⇒ Info(logSource, logClass, message) - case DebugLevel ⇒ Debug(logSource, logClass, message) - case level ⇒ throw new IllegalArgumentException(s"Unsupported log level [$level]") + case ErrorLevel => Error(logSource, logClass, message) + case WarningLevel => Warning(logSource, logClass, message) + case InfoLevel => Info(logSource, logClass, message) + case DebugLevel => Debug(logSource, logClass, message) + case level => throw new IllegalArgumentException(s"Unsupported log level [$level]") } def apply(level: LogLevel, logSource: String, logClass: Class[_], message: Any, mdc: MDC): LogEvent = level match { - case ErrorLevel ⇒ Error(logSource, logClass, message, mdc) - case WarningLevel ⇒ Warning(logSource, logClass, message, mdc) - case InfoLevel ⇒ Info(logSource, logClass, message, mdc) - case DebugLevel ⇒ Debug(logSource, logClass, message, mdc) - case level ⇒ throw new IllegalArgumentException(s"Unsupported log level [$level]") + case ErrorLevel => Error(logSource, logClass, message, mdc) + case WarningLevel => Warning(logSource, logClass, message, mdc) + case InfoLevel => Info(logSource, logClass, message, mdc) + case DebugLevel => Debug(logSource, logClass, message, mdc) + case level => throw new IllegalArgumentException(s"Unsupported log level [$level]") } def apply(level: LogLevel, logSource: String, logClass: Class[_], message: Any, mdc: MDC, marker: LogMarker): LogEvent = level match { - case ErrorLevel ⇒ Error(logSource, logClass, message, mdc, marker) - case WarningLevel ⇒ Warning(logSource, logClass, message, mdc, marker) - case InfoLevel ⇒ Info(logSource, logClass, message, mdc, marker) - case DebugLevel ⇒ Debug(logSource, logClass, message, mdc, marker) - case level ⇒ throw new IllegalArgumentException(s"Unsupported log level [$level]") + case ErrorLevel => Error(logSource, logClass, message, mdc, marker) + case WarningLevel => Warning(logSource, logClass, message, mdc, marker) + case InfoLevel => Info(logSource, logClass, message, mdc, marker) + case DebugLevel => Debug(logSource, logClass, message, mdc, marker) + case level => throw new IllegalArgumentException(s"Unsupported log level [$level]") } } @@ -884,15 +884,15 @@ object Logging { def timestamp(event: LogEvent): String = Helpers.timestamp(event.timestamp) def print(event: Any): Unit = event match { - case e: Error ⇒ error(e) - case e: Warning ⇒ warning(e) - case e: Info ⇒ info(e) - case e: Debug ⇒ debug(e) - case e ⇒ warning(Warning(simpleName(this), this.getClass, "received unexpected event of class " + e.getClass + ": " + e)) + case e: Error => error(e) + case e: Warning => warning(e) + case e: Info => info(e) + case e: Debug => debug(e) + case e => warning(Warning(simpleName(this), this.getClass, "received unexpected event of class " + e.getClass + ": " + e)) } def error(event: Error): Unit = event match { - case e: Error3 ⇒ // has marker + case e: Error3 => // has marker val f = if (event.cause == Error.NoCause) ErrorWithoutCauseWithMarkerFormat else ErrorFormatWithMarker println(f.format( e.marker.name, @@ -902,7 +902,7 @@ object Logging { formatMDC(event.mdc), event.message, stackTraceFor(event.cause))) - case _ ⇒ + case _ => val f = if (event.cause == Error.NoCause) ErrorFormatWithoutCause else ErrorFormat println(f.format( timestamp(event), @@ -914,7 +914,7 @@ object Logging { } def warning(event: Warning): Unit = event match { - case e: Warning3 ⇒ // has marker + case e: Warning3 => // has marker println(WarningWithMarkerFormat.format( e.marker.name, timestamp(event), @@ -922,7 +922,7 @@ object Logging { event.logSource, formatMDC(event.mdc), event.message)) - case _ ⇒ + case _ => println(WarningFormat.format( timestamp(event), event.thread.getName, @@ -932,7 +932,7 @@ object Logging { } def info(event: Info): Unit = event match { - case e: Info3 ⇒ // has marker + case e: Info3 => // has marker println(InfoWithMarkerFormat.format( e.marker.name, timestamp(event), @@ -940,7 +940,7 @@ object Logging { event.logSource, formatMDC(event.mdc), event.message)) - case _ ⇒ + case _ => println(InfoFormat.format( timestamp(event), event.thread.getName, @@ -950,7 +950,7 @@ object Logging { } def debug(event: Debug): Unit = event match { - case e: Debug3 ⇒ // has marker + case e: Debug3 => // has marker println(DebugWithMarkerFormat.format( e.marker.name, timestamp(event), @@ -958,7 +958,7 @@ object Logging { event.logSource, formatMDC(event.mdc), event.message)) - case _ ⇒ + case _ => println(DebugFormat.format( timestamp(event), event.thread.getName, @@ -971,7 +971,7 @@ object Logging { val size = mdc.size if (size == 0) "" else if (size == 1) s"[${mdc.head._1}:${mdc.head._2}]" - else mdc.map({ case (k, v) ⇒ s"$k:$v" }).mkString("[", "][", "]") + else mdc.map({ case (k, v) => s"$k:$v" }).mkString("[", "][", "]") } } object StdOutLogger { @@ -1032,8 +1032,8 @@ object Logging { */ class DefaultLogger extends Actor with StdOutLogger with RequiresMessageQueue[LoggerMessageQueueSemantics] { override def receive: Receive = { - case InitializeLogger(_) ⇒ sender() ! LoggerInitialized - case event: LogEvent ⇒ print(event) + case InitializeLogger(_) => sender() ! LoggerInitialized + case event: LogEvent => print(event) } } @@ -1041,9 +1041,9 @@ object Logging { * Returns the StackTrace for the given Throwable as a String */ def stackTraceFor(e: Throwable): String = e match { - case null | Error.NoCause ⇒ "" - case _: NoStackTrace ⇒ s" (${e.getClass.getName}: ${e.getMessage})" - case other ⇒ + case null | Error.NoCause => "" + case _: NoStackTrace => s" (${e.getClass.getName}: ${e.getMessage})" + case other => val sw = new java.io.StringWriter val pw = new java.io.PrintWriter(sw) pw.append('\n') @@ -1280,19 +1280,19 @@ trait LoggingAdapter { * @return true if the specified log level is enabled */ final def isEnabled(level: Logging.LogLevel): Boolean = level match { - case Logging.ErrorLevel ⇒ isErrorEnabled - case Logging.WarningLevel ⇒ isWarningEnabled - case Logging.InfoLevel ⇒ isInfoEnabled - case Logging.DebugLevel ⇒ isDebugEnabled - case _ ⇒ false + case Logging.ErrorLevel => isErrorEnabled + case Logging.WarningLevel => isWarningEnabled + case Logging.InfoLevel => isInfoEnabled + case Logging.DebugLevel => isDebugEnabled + case _ => false } final def notifyLog(level: Logging.LogLevel, message: String): Unit = level match { - case Logging.ErrorLevel ⇒ if (isErrorEnabled) notifyError(message) - case Logging.WarningLevel ⇒ if (isWarningEnabled) notifyWarning(message) - case Logging.InfoLevel ⇒ if (isInfoEnabled) notifyInfo(message) - case Logging.DebugLevel ⇒ if (isDebugEnabled) notifyDebug(message) - case level ⇒ throw new IllegalArgumentException(s"Unsupported log level [$level]") + case Logging.ErrorLevel => if (isErrorEnabled) notifyError(message) + case Logging.WarningLevel => if (isWarningEnabled) notifyWarning(message) + case Logging.InfoLevel => if (isInfoEnabled) notifyInfo(message) + case Logging.DebugLevel => if (isDebugEnabled) notifyDebug(message) + case level => throw new IllegalArgumentException(s"Unsupported log level [$level]") } /** @@ -1300,9 +1300,9 @@ trait LoggingAdapter { * there are more than four arguments. */ private def format1(t: String, arg: Any): String = arg match { - case a: Array[_] if !a.getClass.getComponentType.isPrimitive ⇒ format(t, a: _*) - case a: Array[_] ⇒ format(t, (a map (_.asInstanceOf[AnyRef]): _*)) - case x ⇒ format(t, x) + case a: Array[_] if !a.getClass.getComponentType.isPrimitive => format(t, a: _*) + case a: Array[_] => format(t, (a map (_.asInstanceOf[AnyRef]): _*)) + case x => format(t, x) } def format(t: String, arg: Any*): String = { @@ -1356,8 +1356,8 @@ trait LoggingFilterWithMarker extends LoggingFilter { object LoggingFilterWithMarker { def wrap(loggingFilter: LoggingFilter): LoggingFilterWithMarker = loggingFilter match { - case lfwm: LoggingFilterWithMarker ⇒ lfwm - case _ ⇒ new LoggingFilterWithMarkerWrapper(loggingFilter) + case lfwm: LoggingFilterWithMarker => lfwm + case _ => new LoggingFilterWithMarkerWrapper(loggingFilter) } } @@ -1373,9 +1373,9 @@ class LoggingFilterWithMarkerWrapper(loggingFilter: LoggingFilter) extends Loggi * initial value is defined in configuration. The logLevel `eventStream` can be * changed while the system is running. */ -class DefaultLoggingFilter(logLevel: () ⇒ Logging.LogLevel) extends LoggingFilterWithMarker { +class DefaultLoggingFilter(logLevel: () => Logging.LogLevel) extends LoggingFilterWithMarker { - def this(settings: Settings, eventStream: EventStream) = this(() ⇒ eventStream.logLevel) + def this(settings: Settings, eventStream: EventStream) = this(() => eventStream.logLevel) import Logging._ def isErrorEnabled(logClass: Class[_], logSource: String) = logLevel() >= ErrorLevel @@ -1390,7 +1390,7 @@ class DefaultLoggingFilter(logLevel: () ⇒ Logging.LogLevel) extends LoggingFil */ trait DiagnosticLoggingAdapter extends LoggingAdapter { - import java.{ util ⇒ ju } + import java.{ util => ju } import Logging._ @@ -1465,8 +1465,8 @@ object LogMarker { @deprecated("use akka.event.LogEventWithMarker#marker instead", since = "2.5.12") def extractFromMDC(mdc: MDC): Option[String] = mdc.get(MDCKey) match { - case Some(v) ⇒ Some(v.toString) - case None ⇒ None + case Some(v) => Some(v.toString) + case None => None } private[akka] final val Security = apply("SECURITY") @@ -1487,7 +1487,7 @@ class MarkerLoggingAdapter( // For backwards compatibility, and when LoggingAdapter is created without direct // association to an ActorSystem def this(bus: LoggingBus, logSource: String, logClass: Class[_]) = - this(bus, logSource, logClass, new DefaultLoggingFilter(() ⇒ bus.logLevel)) + this(bus, logSource, logClass, new DefaultLoggingFilter(() => bus.logLevel)) val loggingFilterWithMarker: LoggingFilterWithMarker = LoggingFilterWithMarker.wrap(loggingFilter) @@ -1713,9 +1713,9 @@ class MarkerLoggingAdapter( // Copy of LoggingAdapter.format1 due to binary compatibility restrictions private def format1(t: String, arg: Any): String = arg match { - case a: Array[_] if !a.getClass.getComponentType.isPrimitive ⇒ format(t, a: _*) - case a: Array[_] ⇒ format(t, (a map (_.asInstanceOf[AnyRef]): _*)) - case x ⇒ format(t, x) + case a: Array[_] if !a.getClass.getComponentType.isPrimitive => format(t, a: _*) + case a: Array[_] => format(t, (a map (_.asInstanceOf[AnyRef]): _*)) + case x => format(t, x) } } @@ -1735,7 +1735,7 @@ class BusLogging(val bus: LoggingBus, val logSource: String, val logClass: Class // For backwards compatibility, and when LoggingAdapter is created without direct // association to an ActorSystem def this(bus: LoggingBus, logSource: String, logClass: Class[_]) = - this(bus, logSource, logClass, new DefaultLoggingFilter(() ⇒ bus.logLevel)) + this(bus, logSource, logClass, new DefaultLoggingFilter(() => bus.logLevel)) import Logging._ diff --git a/akka-actor/src/main/scala/akka/event/LoggingReceive.scala b/akka-actor/src/main/scala/akka/event/LoggingReceive.scala index e9084c70d8..5096353b86 100644 --- a/akka-actor/src/main/scala/akka/event/LoggingReceive.scala +++ b/akka-actor/src/main/scala/akka/event/LoggingReceive.scala @@ -55,8 +55,8 @@ object LoggingReceive { * Create a decorated logger which will append `" in state " + label` to each message it logs. */ def withLabel(label: String, logLevel: LogLevel)(r: Receive)(implicit context: ActorContext): Receive = r match { - case _: LoggingReceive ⇒ r - case _ ⇒ if (context.system.settings.AddLoggingReceive) new LoggingReceive(None, r, Option(label), logLevel) else r + case _: LoggingReceive => r + case _ => if (context.system.settings.AddLoggingReceive) new LoggingReceive(None, r, Option(label), logLevel) else r } /** @@ -79,12 +79,12 @@ class LoggingReceive(source: Option[AnyRef], r: Receive, label: Option[String], val (str, clazz) = LogSource.fromAnyRef(src) val message = "received " + (if (handled) "handled" else "unhandled") + " message " + o + " from " + context.sender() + (label match { - case Some(l) ⇒ " in state " + l - case _ ⇒ "" + case Some(l) => " in state " + l + case _ => "" }) val event = src match { - case a: DiagnosticActorLogging ⇒ LogEvent(logLevel, str, clazz, message, a.log.mdc) - case _ ⇒ LogEvent(logLevel, str, clazz, message) + case a: DiagnosticActorLogging => LogEvent(logLevel, str, clazz, message, a.log.mdc) + case _ => LogEvent(logLevel, str, clazz, message) } context.system.eventStream.publish(event) } diff --git a/akka-actor/src/main/scala/akka/event/jul/JavaLogger.scala b/akka-actor/src/main/scala/akka/event/jul/JavaLogger.scala index 2b204f8b49..bd421810d2 100644 --- a/akka-actor/src/main/scala/akka/event/jul/JavaLogger.scala +++ b/akka-actor/src/main/scala/akka/event/jul/JavaLogger.scala @@ -23,11 +23,11 @@ class JavaLogger extends Actor with RequiresMessageQueue[LoggerMessageQueueSeman import Logger.mapLevel def receive = { - case event @ Error(cause, _, _, _) ⇒ log(mapLevel(event.level), cause, event) - case event: Warning ⇒ log(mapLevel(event.level), null, event) - case event: Info ⇒ log(mapLevel(event.level), null, event) - case event: Debug ⇒ log(mapLevel(event.level), null, event) - case InitializeLogger(_) ⇒ sender() ! LoggerInitialized + case event @ Error(cause, _, _, _) => log(mapLevel(event.level), cause, event) + case event: Warning => log(mapLevel(event.level), null, event) + case event: Info => log(mapLevel(event.level), null, event) + case event: Debug => log(mapLevel(event.level), null, event) + case InitializeLogger(_) => sender() ! LoggerInitialized } def log(level: logging.Level, cause: Throwable, event: LogEvent): Unit = { @@ -66,8 +66,8 @@ object Logger { * @return a Logger for the specified parameters */ def apply(logClass: Class[_], logSource: String): logging.Logger = logClass match { - case c if c == classOf[DummyClassForStringSources] ⇒ apply(logSource) - case _ ⇒ logging.Logger.getLogger(logClass.getName) + case c if c == classOf[DummyClassForStringSources] => apply(logSource) + case _ => logging.Logger.getLogger(logClass.getName) } /** @@ -76,11 +76,11 @@ object Logger { def root: logging.Logger = logging.Logger.getGlobal() def mapLevel(level: LogLevel): logging.Level = level.asInt match { - case InfoLevel.asInt ⇒ logging.Level.INFO - case DebugLevel.asInt ⇒ logging.Level.CONFIG - case WarningLevel.asInt ⇒ logging.Level.WARNING - case ErrorLevel.asInt ⇒ logging.Level.SEVERE - case _ ⇒ logging.Level.FINE + case InfoLevel.asInt => logging.Level.INFO + case DebugLevel.asInt => logging.Level.CONFIG + case WarningLevel.asInt => logging.Level.WARNING + case ErrorLevel.asInt => logging.Level.SEVERE + case _ => logging.Level.FINE } } diff --git a/akka-actor/src/main/scala/akka/io/DirectByteBufferPool.scala b/akka-actor/src/main/scala/akka/io/DirectByteBufferPool.scala index 114712135c..24db9c684d 100644 --- a/akka-actor/src/main/scala/akka/io/DirectByteBufferPool.scala +++ b/akka-actor/src/main/scala/akka/io/DirectByteBufferPool.scala @@ -76,7 +76,7 @@ private[akka] class DirectByteBufferPool(defaultBufferSize: Int, maxPoolEntries: /** INTERNAL API */ private[akka] object DirectByteBufferPool { - private val CleanDirectBuffer: ByteBuffer ⇒ Unit = + private val CleanDirectBuffer: ByteBuffer => Unit = try { val cleanerMethod = Class.forName("java.nio.DirectByteBuffer").getMethod("cleaner") cleanerMethod.setAccessible(true) @@ -84,15 +84,15 @@ private[akka] object DirectByteBufferPool { val cleanMethod = Class.forName("sun.misc.Cleaner").getMethod("clean") cleanMethod.setAccessible(true) - { (bb: ByteBuffer) ⇒ + { (bb: ByteBuffer) => try if (bb.isDirect) { val cleaner = cleanerMethod.invoke(bb) cleanMethod.invoke(cleaner) } - catch { case NonFatal(_) ⇒ /* ok, best effort attempt to cleanup failed */ } + catch { case NonFatal(_) => /* ok, best effort attempt to cleanup failed */ } } - } catch { case NonFatal(_) ⇒ _ ⇒ () /* reflection failed, use no-op fallback */ } + } catch { case NonFatal(_) => _ => () /* reflection failed, use no-op fallback */ } /** * DirectByteBuffers are garbage collected by using a phantom reference and a diff --git a/akka-actor/src/main/scala/akka/io/Dns.scala b/akka-actor/src/main/scala/akka/io/Dns.scala index 00e21074a3..14667a474c 100644 --- a/akka-actor/src/main/scala/akka/io/Dns.scala +++ b/akka-actor/src/main/scala/akka/io/Dns.scala @@ -11,7 +11,7 @@ import akka.actor._ import akka.annotation.InternalApi import akka.routing.ConsistentHashingRouter.ConsistentHashable import com.typesafe.config.Config -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import akka.util.unused @@ -50,18 +50,18 @@ object Dns extends ExtensionId[DnsExt] with ExtensionIdProvider { @throws[UnknownHostException] def addr: InetAddress = addrOption match { - case Some(ipAddress) ⇒ ipAddress - case None ⇒ throw new UnknownHostException(name) + case Some(ipAddress) => ipAddress + case None => throw new UnknownHostException(name) } } object Resolved { def apply(name: String, addresses: Iterable[InetAddress]): Resolved = { val ipv4: immutable.Seq[Inet4Address] = addresses.iterator.collect({ - case a: Inet4Address ⇒ a + case a: Inet4Address => a }).to(immutable.IndexedSeq) val ipv6: immutable.Seq[Inet6Address] = addresses.iterator.collect({ - case a: Inet6Address ⇒ a + case a: Inet6Address => a }).to(immutable.IndexedSeq) Resolved(name, ipv4, ipv6) } @@ -169,7 +169,7 @@ class DnsExt private[akka] (val system: ExtendedActorSystem, resolverName: Strin object IpVersionSelector { def getInetAddress(ipv4: Option[Inet4Address], ipv6: Option[Inet6Address]): Option[InetAddress] = System.getProperty("java.net.preferIPv6Addresses") match { - case "true" ⇒ ipv6 orElse ipv4 - case _ ⇒ ipv4 orElse ipv6 + case "true" => ipv6 orElse ipv4 + case _ => ipv4 orElse ipv6 } } diff --git a/akka-actor/src/main/scala/akka/io/InetAddressDnsResolver.scala b/akka-actor/src/main/scala/akka/io/InetAddressDnsResolver.scala index 3eebf9e151..124ca825c5 100644 --- a/akka-actor/src/main/scala/akka/io/InetAddressDnsResolver.scala +++ b/akka-actor/src/main/scala/akka/io/InetAddressDnsResolver.scala @@ -35,10 +35,10 @@ class InetAddressDnsResolver(cache: SimpleDnsCache, config: Config) extends Acto private lazy val defaultCachePolicy: CachePolicy = Option(Security.getProperty(CachePolicyProp)).filter(_ != "") .orElse(Option(System.getProperty(CachePolicyPropFallback))).filter(_ != "") - .map(x ⇒ Try(x.toInt)) match { - case None ⇒ DefaultPositive - case Some(Success(n)) ⇒ parsePolicy(n) - case Some(Failure(_)) ⇒ + .map(x => Try(x.toInt)) match { + case None => DefaultPositive + case Some(Success(n)) => parsePolicy(n) + case Some(Failure(_)) => log.warning("Caching TTL misconfigured. Using default value {}.", DefaultPositive) DefaultPositive } @@ -46,28 +46,28 @@ class InetAddressDnsResolver(cache: SimpleDnsCache, config: Config) extends Acto private lazy val defaultNegativeCachePolicy: CachePolicy = Option(Security.getProperty(NegativeCachePolicyProp)).filter(_ != "") .orElse(Option(System.getProperty(NegativeCachePolicyPropFallback))).filter(_ != "") - .map(x ⇒ Try(x.toInt)) match { - case None ⇒ Never - case Some(Success(n)) ⇒ parsePolicy(n) - case Some(Failure(_)) ⇒ + .map(x => Try(x.toInt)) match { + case None => Never + case Some(Success(n)) => parsePolicy(n) + case Some(Failure(_)) => log.warning("Negative caching TTL misconfigured. Using default value {}.", Never) Never } private def parsePolicy(n: Int): CachePolicy = { n match { - case 0 ⇒ Never - case x if x < 0 ⇒ Forever - case x ⇒ Ttl.fromPositive(x.seconds) + case 0 => Never + case x if x < 0 => Forever + case x => Ttl.fromPositive(x.seconds) } } private def getTtl(path: String, positive: Boolean): CachePolicy = config.getString(path) match { - case "default" ⇒ if (positive) defaultCachePolicy else defaultNegativeCachePolicy - case "forever" ⇒ Forever - case "never" ⇒ Never - case _ ⇒ { + case "default" => if (positive) defaultCachePolicy else defaultNegativeCachePolicy + case "forever" => Forever + case "never" => Never + case _ => { val finiteTtl = config .getDuration(path, TimeUnit.SECONDS) .requiring(_ > 0, s"akka.io.dns.$path must be 'default', 'forever', 'never' or positive duration") @@ -84,23 +84,23 @@ class InetAddressDnsResolver(cache: SimpleDnsCache, config: Config) extends Acto private def toLongTtl(cp: CachePolicy): Long = { cp match { - case Forever ⇒ Long.MaxValue - case Never ⇒ 0 - case Ttl(ttl) ⇒ ttl.toMillis + case Forever => Long.MaxValue + case Never => 0 + case Ttl(ttl) => ttl.toMillis } } override def receive = { - case Dns.Resolve(name) ⇒ + case Dns.Resolve(name) => val answer = cache.cached(name) match { - case Some(a) ⇒ a - case None ⇒ + case Some(a) => a + case None => try { val answer = Dns.Resolved(name, InetAddress.getAllByName(name)) if (positiveCachePolicy != Never) cache.put(answer, positiveCachePolicy) answer } catch { - case _: UnknownHostException ⇒ + case _: UnknownHostException => val answer = Dns.Resolved(name, immutable.Seq.empty, immutable.Seq.empty) if (negativeCachePolicy != Never) cache.put(answer, negativeCachePolicy) answer diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index 5fdf02a9eb..8605d7540c 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -4,7 +4,7 @@ package akka.io -import java.util.{ Iterator ⇒ JIterator } +import java.util.{ Iterator => JIterator } import java.util.concurrent.atomic.AtomicBoolean import java.nio.channels.{ CancelledKeyException, SelectableChannel, SelectionKey } import java.nio.channels.SelectionKey._ @@ -30,8 +30,8 @@ abstract class SelectionHandlerSettings(config: Config) { import config._ val MaxChannels: Int = getString("max-channels") match { - case "unlimited" ⇒ -1 - case _ ⇒ getInt("max-channels") requiring (_ > 0, "max-channels must be > 0 or 'unlimited'") + case "unlimited" => -1 + case _ => getInt("max-channels") requiring (_ > 0, "max-channels must be > 0 or 'unlimited'") } val SelectorAssociationRetries: Int = getInt("selector-association-retries") requiring ( _ >= 0, "selector-association-retries must be >= 0") @@ -67,7 +67,7 @@ private[io] trait ChannelRegistration extends NoSerializationVerificationNeeded * Explicitly cancel the registration and close the underlying channel. Then run the given `andThen` method. * The `andThen` method is run from another thread so make sure it's safe to execute from there. */ - def cancelAndClose(andThen: () ⇒ Unit): Unit + def cancelAndClose(andThen: () => Unit): Unit } private[io] object SelectionHandler { @@ -82,7 +82,7 @@ private[io] object SelectionHandler { def failureMessage: Any } - final case class WorkerForCommand(apiCommand: HasFailureMessage, commander: ActorRef, childProps: ChannelRegistry ⇒ Props) + final case class WorkerForCommand(apiCommand: HasFailureMessage, commander: ActorRef, childProps: ChannelRegistry => Props) extends NoSerializationVerificationNeeded final case class Retry(command: WorkerForCommand, retriesLeft: Int) extends NoSerializationVerificationNeeded { require(retriesLeft >= 0) } @@ -100,8 +100,8 @@ private[io] object SelectionHandler { props = RandomPool(nrOfSelectors).props(Props(classOf[SelectionHandler], selectorSettings)).withDeploy(Deploy.local), name = "selectors") - final def workerForCommandHandler(pf: PartialFunction[HasFailureMessage, ChannelRegistry ⇒ Props]): Receive = { - case cmd: HasFailureMessage if pf.isDefinedAt(cmd) ⇒ selectorPool ! WorkerForCommand(cmd, sender(), pf(cmd)) + final def workerForCommandHandler(pf: PartialFunction[HasFailureMessage, ChannelRegistry => Props]): Receive = { + case cmd: HasFailureMessage if pf.isDefinedAt(cmd) => selectorPool ! WorkerForCommand(cmd, sender(), pf(cmd)) } } @@ -116,7 +116,7 @@ private[io] object SelectionHandler { if (cause.isInstanceOf[DeathPactException]) { try context.system.eventStream.publish { Logging.Debug(child.path.toString, getClass, "Closed after handler termination") - } catch { case NonFatal(_) ⇒ } + } catch { case NonFatal(_) => } } else super.logFailure(context, child, cause, decision) } @@ -140,15 +140,15 @@ private[io] object SelectionHandler { key.interestOps(key.interestOps & ~readyOps) // prevent immediate reselection by always clearing val connection = key.attachment.asInstanceOf[ActorRef] readyOps match { - case OP_READ ⇒ connection ! ChannelReadable - case OP_WRITE ⇒ connection ! ChannelWritable - case OP_READ_AND_WRITE ⇒ { connection ! ChannelWritable; connection ! ChannelReadable } - case x if (x & OP_ACCEPT) > 0 ⇒ connection ! ChannelAcceptable - case x if (x & OP_CONNECT) > 0 ⇒ connection ! ChannelConnectable - case x ⇒ log.warning("Invalid readyOps: [{}]", x) + case OP_READ => connection ! ChannelReadable + case OP_WRITE => connection ! ChannelWritable + case OP_READ_AND_WRITE => { connection ! ChannelWritable; connection ! ChannelReadable } + case x if (x & OP_ACCEPT) > 0 => connection ! ChannelAcceptable + case x if (x & OP_CONNECT) > 0 => connection ! ChannelConnectable + case x => log.warning("Invalid readyOps: [{}]", x) } } catch { - case _: CancelledKeyException ⇒ + case _: CancelledKeyException => // can be ignored because this exception is triggered when the key becomes invalid // because `channel.close()` in `TcpConnection.postStop` is called from another thread } @@ -179,10 +179,10 @@ private[io] object SelectionHandler { def disableInterest(ops: Int): Unit = disableInterestOps(key, ops) - def cancelAndClose(andThen: () ⇒ Unit): Unit = cancelKeyAndClose(key, andThen) + def cancelAndClose(andThen: () => Unit): Unit = cancelKeyAndClose(key, andThen) } } catch { - case _: ClosedChannelException ⇒ + case _: ClosedChannelException => // ignore, might happen if a connection is closed in the same moment as an interest is registered } } @@ -195,7 +195,7 @@ private[io] object SelectionHandler { def tryRun(): Unit = { // thorough 'close' of the Selector @tailrec def closeNextChannel(it: JIterator[SelectionKey]): Unit = if (it.hasNext) { - try it.next().channel.close() catch { case NonFatal(e) ⇒ log.debug("Error closing channel: {}", e) } + try it.next().channel.close() catch { case NonFatal(e) => log.debug("Error closing channel: {}", e) } closeNextChannel(it) } try closeNextChannel(selector.keys.iterator) @@ -218,7 +218,7 @@ private[io] object SelectionHandler { } } - private def cancelKeyAndClose(key: SelectionKey, andThen: () ⇒ Unit): Unit = + private def cancelKeyAndClose(key: SelectionKey, andThen: () => Unit): Unit = execute { new Task { def tryRun(): Unit = { @@ -238,7 +238,7 @@ private[io] object SelectionHandler { } } - private def runThunk(andThen: () ⇒ Unit): Unit = + private def runThunk(andThen: () => Unit): Unit = execute { new Task { def tryRun(): Unit = andThen() @@ -268,8 +268,8 @@ private[io] object SelectionHandler { def run(): Unit = { try tryRun() catch { - case _: CancelledKeyException ⇒ // ok, can be triggered while setting interest ops - case NonFatal(e) ⇒ log.error(e, "Error during selector management task: [{}]", e) + case _: CancelledKeyException => // ok, can be triggered while setting interest ops + case NonFatal(e) => log.error(e, "Error during selector management task: [{}]", e) } } } @@ -289,13 +289,13 @@ private[io] class SelectionHandler(settings: SelectionHandlerSettings) extends A } def receive: Receive = { - case cmd: WorkerForCommand ⇒ spawnChildWithCapacityProtection(cmd, SelectorAssociationRetries) + case cmd: WorkerForCommand => spawnChildWithCapacityProtection(cmd, SelectorAssociationRetries) - case Retry(cmd, retriesLeft) ⇒ spawnChildWithCapacityProtection(cmd, retriesLeft) + case Retry(cmd, retriesLeft) => spawnChildWithCapacityProtection(cmd, retriesLeft) // since our ActorRef is never exposed to the user and we are only assigning watches to our // children all incoming `Terminated` events must be for a child of ours - case _: Terminated ⇒ childCount -= 1 + case _: Terminated => childCount -= 1 } override def postStop(): Unit = registry.shutdown() @@ -304,24 +304,24 @@ private[io] class SelectionHandler(settings: SelectionHandlerSettings) extends A // and log the failure at debug level override def supervisorStrategy = { def stoppingDecider: SupervisorStrategy.Decider = { - case _: Exception ⇒ SupervisorStrategy.Stop + case _: Exception => SupervisorStrategy.Stop } new OneForOneStrategy()(stoppingDecider) { override def logFailure(context: ActorContext, child: ActorRef, cause: Throwable, decision: SupervisorStrategy.Directive): Unit = try { val logMessage = cause match { - case e: ActorInitializationException if (e.getCause ne null) && (e.getCause.getMessage ne null) ⇒ e.getCause.getMessage - case e: ActorInitializationException if e.getCause ne null ⇒ + case e: ActorInitializationException if (e.getCause ne null) && (e.getCause.getMessage ne null) => e.getCause.getMessage + case e: ActorInitializationException if e.getCause ne null => e.getCause match { - case ie: java.lang.reflect.InvocationTargetException ⇒ ie.getTargetException.toString - case t: Throwable ⇒ Logging.simpleName(t) + case ie: java.lang.reflect.InvocationTargetException => ie.getTargetException.toString + case t: Throwable => Logging.simpleName(t) } - case e ⇒ e.getMessage + case e => e.getMessage } context.system.eventStream.publish( Logging.Debug(child.path.toString, classOf[SelectionHandler], logMessage)) - } catch { case NonFatal(_) ⇒ } + } catch { case NonFatal(_) => } } } diff --git a/akka-actor/src/main/scala/akka/io/SimpleDnsCache.scala b/akka-actor/src/main/scala/akka/io/SimpleDnsCache.scala index 3e89330622..108235641a 100644 --- a/akka-actor/src/main/scala/akka/io/SimpleDnsCache.scala +++ b/akka-actor/src/main/scala/akka/io/SimpleDnsCache.scala @@ -22,7 +22,7 @@ class SimpleDnsCache extends Dns with PeriodicCacheCleanup { private val cache = new AtomicReference(new Cache[String, Dns.Resolved]( immutable.SortedSet()(expiryEntryOrdering[String]()), - Map(), () ⇒ clock)) + Map(), () => clock)) private val nanoBase = System.nanoTime() @@ -57,24 +57,24 @@ object SimpleDnsCache { * INTERNAL API */ @InternalApi - private[io] class Cache[K, V](queue: immutable.SortedSet[ExpiryEntry[K]], cache: immutable.Map[K, CacheEntry[V]], clock: () ⇒ Long) { + private[io] class Cache[K, V](queue: immutable.SortedSet[ExpiryEntry[K]], cache: immutable.Map[K, CacheEntry[V]], clock: () => Long) { def get(name: K): Option[V] = { for { - e ← cache.get(name) + e <- cache.get(name) if e.isValid(clock()) } yield e.answer } def put(name: K, answer: V, ttl: CachePolicy): Cache[K, V] = { val until = ttl match { - case Forever ⇒ Long.MaxValue - case Never ⇒ clock() - 1 - case Ttl(ttl) ⇒ clock() + ttl.toMillis + case Forever => Long.MaxValue + case Never => clock() - 1 + case Ttl(ttl) => clock() + ttl.toMillis } new Cache[K, V]( queue + new ExpiryEntry[K](name, until), - cache + (name → CacheEntry(answer, until)), + cache + (name -> CacheEntry(answer, until)), clock) } diff --git a/akka-actor/src/main/scala/akka/io/SimpleDnsManager.scala b/akka-actor/src/main/scala/akka/io/SimpleDnsManager.scala index 07e12c79e6..cd692b9061 100644 --- a/akka-actor/src/main/scala/akka/io/SimpleDnsManager.scala +++ b/akka-actor/src/main/scala/akka/io/SimpleDnsManager.scala @@ -23,24 +23,24 @@ class SimpleDnsManager(val ext: DnsExt) extends Actor with RequiresMessageQueue[ private val inetDnsEnabled = ext.provider.actorClass == classOf[InetAddressDnsResolver] private val cacheCleanup = ext.cache match { - case cleanup: PeriodicCacheCleanup ⇒ Some(cleanup) - case _ ⇒ None + case cleanup: PeriodicCacheCleanup => Some(cleanup) + case _ => None } - private val cleanupTimer = cacheCleanup map { _ ⇒ + private val cleanupTimer = cacheCleanup map { _ => val interval = Duration(ext.Settings.ResolverConfig.getDuration("cache-cleanup-interval", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) system.scheduler.schedule(interval, interval, self, SimpleDnsManager.CacheCleanup) } override def receive: Receive = { - case r @ Dns.Resolve(name) ⇒ + case r @ Dns.Resolve(name) => log.debug("Resolution request for {} from {}", name, sender()) resolver.forward(r) - case SimpleDnsManager.CacheCleanup ⇒ + case SimpleDnsManager.CacheCleanup => cacheCleanup.foreach(_.cleanup()) - case m: dns.DnsProtocol.Resolve ⇒ + case m: dns.DnsProtocol.Resolve => if (inetDnsEnabled) { log.error( "Message of [akka.io.dns.DnsProtocol.Protocol] received ({}) while inet-address dns was configured. Dropping DNS resolve request. " + diff --git a/akka-actor/src/main/scala/akka/io/Tcp.scala b/akka-actor/src/main/scala/akka/io/Tcp.scala index e11c2941a1..38030347d5 100644 --- a/akka-actor/src/main/scala/akka/io/Tcp.scala +++ b/akka-actor/src/main/scala/akka/io/Tcp.scala @@ -17,7 +17,7 @@ import akka.util.{ ByteString, Helpers } import akka.util.Helpers.Requiring import akka.util.JavaDurationConverters._ import akka.actor._ -import java.lang.{ Iterable ⇒ JIterable } +import java.lang.{ Iterable => JIterable } import java.nio.file.Path import akka.annotation.InternalApi @@ -261,8 +261,8 @@ object Tcp extends ExtensionId[TcpExt] with ExtensionIdProvider { */ def ++:(writes: Iterable[WriteCommand]): WriteCommand = writes.foldRight(this) { - case (a: SimpleWriteCommand, b) ⇒ a +: b - case (a: CompoundWrite, b) ⇒ a ++: b + case (a: SimpleWriteCommand, b) => a +: b + case (a: CompoundWrite, b) => a ++: b } /** @@ -382,9 +382,9 @@ object Tcp extends ExtensionId[TcpExt] with ExtensionIdProvider { def hasNext: Boolean = current ne null def next(): SimpleWriteCommand = current match { - case null ⇒ Iterator.empty.next() - case CompoundWrite(h, t) ⇒ { current = t; h } - case x: SimpleWriteCommand ⇒ { current = null; x } + case null => Iterator.empty.next() + case CompoundWrite(h, t) => { current = t; h } + case x: SimpleWriteCommand => { current = null; x } } } } @@ -462,7 +462,7 @@ object Tcp extends ExtensionId[TcpExt] with ExtensionIdProvider { } @InternalApi - private[akka] def causedByString = _cause.map(t ⇒ { + private[akka] def causedByString = _cause.map(t => { val msg = if (t.getCause == null) t.getMessage @@ -576,18 +576,18 @@ class TcpExt(system: ExtendedActorSystem) extends IO.Extension { val DirectBufferSize: Int = getIntBytes("direct-buffer-size") val MaxDirectBufferPoolSize: Int = getInt("direct-buffer-pool-limit") val RegisterTimeout: Duration = getString("register-timeout") match { - case "infinite" ⇒ Duration.Undefined - case _ ⇒ _config.getMillisDuration("register-timeout") + case "infinite" => Duration.Undefined + case _ => _config.getMillisDuration("register-timeout") } val ReceivedMessageSizeLimit: Int = getString("max-received-message-size") match { - case "unlimited" ⇒ Int.MaxValue - case _ ⇒ getIntBytes("max-received-message-size") + case "unlimited" => Int.MaxValue + case _ => getIntBytes("max-received-message-size") } val ManagementDispatcher: String = getString("management-dispatcher") val FileIODispatcher: String = getString("file-io-dispatcher") val TransferToLimit: Int = getString("file-io-transferTo-limit") match { - case "unlimited" ⇒ Int.MaxValue - case _ ⇒ getIntBytes("file-io-transferTo-limit") + case "unlimited" => Int.MaxValue + case _ => getIntBytes("file-io-transferTo-limit") } val MaxChannelsPerSelector: Int = if (MaxChannels == -1) -1 else math.max(MaxChannels / NrOfSelectors, 1) @@ -595,8 +595,8 @@ class TcpExt(system: ExtendedActorSystem) extends IO.Extension { "finish-connect-retries must be > 0") val WindowsConnectionAbortWorkaroundEnabled: Boolean = getString("windows-connection-abort-workaround-enabled") match { - case "auto" ⇒ Helpers.isWindows - case _ ⇒ getBoolean("windows-connection-abort-workaround-enabled") + case "auto" => Helpers.isWindows + case _ => getBoolean("windows-connection-abort-workaround-enabled") } private[this] def getIntBytes(path: String): Int = { diff --git a/akka-actor/src/main/scala/akka/io/TcpConnection.scala b/akka-actor/src/main/scala/akka/io/TcpConnection.scala index 026c549182..26b7a83491 100644 --- a/akka-actor/src/main/scala/akka/io/TcpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpConnection.scala @@ -60,7 +60,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha /** connection established, waiting for registration from user handler */ def waitingForRegistration(registration: ChannelRegistration, commander: ActorRef): Receive = { - case Register(handler, keepOpenOnPeerClosed, useResumeWriting) ⇒ + case Register(handler, keepOpenOnPeerClosed, useResumeWriting) => // up to this point we've been watching the commander, // but since registration is now complete we only need to watch the handler from here on if (handler != commander) { @@ -77,17 +77,17 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha context.setReceiveTimeout(Duration.Undefined) context.become(connected(info)) - case ResumeReading ⇒ + case ResumeReading => readingSuspended = false - case SuspendReading ⇒ + case SuspendReading => readingSuspended = true - case cmd: CloseCommand ⇒ + case cmd: CloseCommand => val info = ConnectionInfo(registration, commander, keepOpenOnPeerClosed = false, useResumeWriting = false) handleClose(info, Some(sender()), cmd.event) - case ReceiveTimeout ⇒ + case ReceiveTimeout => // after sending `Register` user should watch this actor to make sure // it didn't die because of the timeout log.debug("Configured registration timeout of [{}] expired, stopping", RegisterTimeout) @@ -97,52 +97,52 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha /** normal connected state */ def connected(info: ConnectionInfo): Receive = handleWriteMessages(info) orElse { - case SuspendReading ⇒ suspendReading(info) - case ResumeReading ⇒ resumeReading(info) - case ChannelReadable ⇒ doRead(info, None) - case cmd: CloseCommand ⇒ handleClose(info, Some(sender()), cmd.event) + case SuspendReading => suspendReading(info) + case ResumeReading => resumeReading(info) + case ChannelReadable => doRead(info, None) + case cmd: CloseCommand => handleClose(info, Some(sender()), cmd.event) } /** the peer sent EOF first, but we may still want to send */ def peerSentEOF(info: ConnectionInfo): Receive = handleWriteMessages(info) orElse { - case cmd: CloseCommand ⇒ handleClose(info, Some(sender()), cmd.event) - case ResumeReading ⇒ // ignore, no more data to read + case cmd: CloseCommand => handleClose(info, Some(sender()), cmd.event) + case ResumeReading => // ignore, no more data to read } /** connection is closing but a write has to be finished first */ def closingWithPendingWrite(info: ConnectionInfo, closeCommander: Option[ActorRef], closedEvent: ConnectionClosed): Receive = { - case SuspendReading ⇒ suspendReading(info) - case ResumeReading ⇒ resumeReading(info) - case ChannelReadable ⇒ doRead(info, closeCommander) + case SuspendReading => suspendReading(info) + case ResumeReading => resumeReading(info) + case ChannelReadable => doRead(info, closeCommander) - case ChannelWritable ⇒ + case ChannelWritable => doWrite(info) if (!writePending) // writing is now finished handleClose(info, closeCommander, closedEvent) - case UpdatePendingWriteAndThen(remaining, work) ⇒ + case UpdatePendingWriteAndThen(remaining, work) => pendingWrite = remaining work() if (writePending) info.registration.enableInterest(OP_WRITE) else handleClose(info, closeCommander, closedEvent) - case WriteFileFailed(e) ⇒ handleError(info.handler, e) // rethrow exception from dispatcher task + case WriteFileFailed(e) => handleError(info.handler, e) // rethrow exception from dispatcher task - case Abort ⇒ handleClose(info, Some(sender()), Aborted) + case Abort => handleClose(info, Some(sender()), Aborted) } /** connection is closed on our side and we're waiting from confirmation from the other side */ def closing(info: ConnectionInfo, closeCommander: Option[ActorRef]): Receive = { - case SuspendReading ⇒ suspendReading(info) - case ResumeReading ⇒ resumeReading(info) - case ChannelReadable ⇒ doRead(info, closeCommander) - case Abort ⇒ handleClose(info, Some(sender()), Aborted) + case SuspendReading => suspendReading(info) + case ResumeReading => resumeReading(info) + case ChannelReadable => doRead(info, closeCommander) + case Abort => handleClose(info, Some(sender()), Aborted) } def handleWriteMessages(info: ConnectionInfo): Receive = { - case ChannelWritable ⇒ + case ChannelWritable => if (writePending) { doWrite(info) if (!writePending && interestedInResume.nonEmpty) { @@ -151,7 +151,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha } } - case write: WriteCommand ⇒ + case write: WriteCommand => if (writingSuspended) { if (TraceLogging) log.debug("Dropping write because writing is suspended") sender() ! write.failureMessage.withCause(DroppingWriteBecauseWritingIsSuspendedException) @@ -166,7 +166,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha if (writePending) doWrite(info) } - case ResumeWriting ⇒ + case ResumeWriting => /* * If more than one actor sends Writes then the first to send this * message might resume too early for the second, leading to a Write of @@ -183,17 +183,17 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha else sender() ! CommandFailed(ResumeWriting) } else sender() ! WritingResumed - case UpdatePendingWriteAndThen(remaining, work) ⇒ + case UpdatePendingWriteAndThen(remaining, work) => pendingWrite = remaining work() if (writePending) info.registration.enableInterest(OP_WRITE) - case WriteFileFailed(e) ⇒ handleError(info.handler, e) // rethrow exception from dispatcher task + case WriteFileFailed(e) => handleError(info.handler, e) // rethrow exception from dispatcher task } /** stopWith sets this state while waiting for the SelectionHandler to execute the `cancelAndClose` thunk */ def unregistering: Receive = { - case Unregistered ⇒ context.stop(self) // postStop will notify interested parties + case Unregistered => context.stop(self) // postStop will notify interested parties } // AUXILIARIES and IMPLEMENTATION @@ -205,7 +205,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha // Turn off Nagle's algorithm by default try channel.socket.setTcpNoDelay(true) catch { - case e: SocketException ⇒ + case e: SocketException => // as reported in #16653 some versions of netcat (`nc -z`) doesn't allow setTcpNoDelay // continue anyway log.debug("Could not enable TcpNoDelay: {}", e.getMessage) @@ -253,28 +253,28 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha if (readBytes > 0) info.handler ! Received(ByteString(buffer)) readBytes match { - case `maxBufferSpace` ⇒ if (pullMode) MoreDataWaiting else innerRead(buffer, remainingLimit - maxBufferSpace) - case x if x >= 0 ⇒ AllRead - case -1 ⇒ EndOfStream - case _ ⇒ + case `maxBufferSpace` => if (pullMode) MoreDataWaiting else innerRead(buffer, remainingLimit - maxBufferSpace) + case x if x >= 0 => AllRead + case -1 => EndOfStream + case _ => throw new IllegalStateException("Unexpected value returned from read: " + readBytes) } } else MoreDataWaiting val buffer = bufferPool.acquire() try innerRead(buffer, ReceivedMessageSizeLimit) match { - case AllRead ⇒ + case AllRead => if (!pullMode) info.registration.enableInterest(OP_READ) - case MoreDataWaiting ⇒ + case MoreDataWaiting => if (!pullMode) self ! ChannelReadable - case EndOfStream if channel.socket.isOutputShutdown ⇒ + case EndOfStream if channel.socket.isOutputShutdown => if (TraceLogging) log.debug("Read returned end-of-stream, our side already closed") doCloseConnection(info.handler, closeCommander, ConfirmedClosed) - case EndOfStream ⇒ + case EndOfStream => if (TraceLogging) log.debug("Read returned end-of-stream, our side not yet closed") handleClose(info, closeCommander, PeerClosed) } catch { - case e: IOException ⇒ handleError(info.handler, e) + case e: IOException => handleError(info.handler, e) } finally bufferPool.release(buffer) } @@ -286,21 +286,21 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha def handleClose(info: ConnectionInfo, closeCommander: Option[ActorRef], closedEvent: ConnectionClosed): Unit = closedEvent match { - case Aborted ⇒ + case Aborted => if (TraceLogging) log.debug("Got Abort command. RESETing connection.") doCloseConnection(info.handler, closeCommander, closedEvent) - case PeerClosed if info.keepOpenOnPeerClosed ⇒ + case PeerClosed if info.keepOpenOnPeerClosed => // report that peer closed the connection info.handler ! PeerClosed // used to check if peer already closed its side later peerClosed = true context.become(peerSentEOF(info)) - case _ if writePending ⇒ // finish writing first + case _ if writePending => // finish writing first // Our registered actor is now free to terminate cleanly unsignDeathPact() if (TraceLogging) log.debug("Got Close command but write is still pending.") context.become(closingWithPendingWrite(info, closeCommander, closedEvent)) - case ConfirmedClosed ⇒ // shutdown output and wait for confirmation + case ConfirmedClosed => // shutdown output and wait for confirmation if (TraceLogging) log.debug("Got ConfirmedClose command, sending FIN.") // If peer closed first, the socket is now fully closed. @@ -310,7 +310,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha if (peerClosed || !safeShutdownOutput()) doCloseConnection(info.handler, closeCommander, closedEvent) else context.become(closing(info, closeCommander)) - case _ ⇒ // close now + case _ => // close now if (TraceLogging) log.debug("Got Close command, closing connection.") doCloseConnection(info.handler, closeCommander, closedEvent) } @@ -329,22 +329,22 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha channel.socket().shutdownOutput() true } catch { - case _: SocketException ⇒ false + case _: SocketException => false } @tailrec private[this] def extractMsg(t: Throwable): String = if (t == null) "unknown" else { t.getMessage match { - case null | "" ⇒ extractMsg(t.getCause) - case msg ⇒ msg + case null | "" => extractMsg(t.getCause) + case msg => msg } } def prepareAbort(): Unit = { try channel.socket.setSoLinger(true, 0) // causes the following close() to send TCP RST catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // setSoLinger can fail due to http://bugs.sun.com/view_bug.do?bug_id=6799574 // (also affected: OS/X Java 1.6.0_37) if (TraceLogging) log.debug("setSoLinger(true, 0) failed with [{}]", e) @@ -364,11 +364,11 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha prepareAbort() registration match { - case None ⇒ + case None => context.stop(self) - case Some(reg) ⇒ + case Some(reg) => context.become(unregistering) - reg.cancelAndClose(() ⇒ self ! Unregistered) + reg.cancelAndClose(() => self ! Unregistered) } } @@ -385,8 +385,8 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha def isCommandFailed: Boolean = closedMessage.exists(_.closedEvent.isInstanceOf[CommandFailed]) def notifyInterested(): Unit = for { - msg ← closedMessage - ref ← interestedInClose + msg <- closedMessage + ref <- interestedInClose } ref ! msg.closedEvent if (!channel.isOpen || isCommandFailed || registration.isEmpty) @@ -394,7 +394,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha notifyInterested() else // otherwise, we unregister and notify afterwards - registration.foreach(_.cancelAndClose(() ⇒ notifyInterested())) + registration.foreach(_.cancelAndClose(() => notifyInterested())) } override def postRestart(reason: Throwable): Unit = @@ -403,12 +403,12 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha def PendingWrite(commander: ActorRef, write: WriteCommand): PendingWrite = { @tailrec def create(head: WriteCommand, tail: WriteCommand = Write.empty): PendingWrite = head match { - case Write.empty ⇒ if (tail eq Write.empty) EmptyPendingWrite else create(tail) - case Write(data, ack) if data.nonEmpty ⇒ PendingBufferWrite(commander, data, ack, tail) - case WriteFile(path, offset, count, ack) ⇒ PendingWriteFile(commander, Paths.get(path), offset, count, ack, tail) - case WritePath(path, offset, count, ack) ⇒ PendingWriteFile(commander, path, offset, count, ack, tail) - case CompoundWrite(h, t) ⇒ create(h, t) - case x @ Write(_, ack) ⇒ // empty write with either an ACK or a non-standard NoACK + case Write.empty => if (tail eq Write.empty) EmptyPendingWrite else create(tail) + case Write(data, ack) if data.nonEmpty => PendingBufferWrite(commander, data, ack, tail) + case WriteFile(path, offset, count, ack) => PendingWriteFile(commander, Paths.get(path), offset, count, ack, tail) + case WritePath(path, offset, count, ack) => PendingWriteFile(commander, path, offset, count, ack, tail) + case CompoundWrite(h, t) => create(h, t) + case x @ Write(_, ack) => // empty write with either an ACK or a non-standard NoACK if (x.wantsAck) commander ! ack create(tail) } @@ -422,7 +422,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha buffer.flip() new PendingBufferWrite(commander, data.drop(copied), ack, buffer, tail) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => bufferPool.release(buffer) throw e } @@ -460,7 +460,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha val next = writeToChannel(remainingData) if (next ne EmptyPendingWrite) info.registration.enableInterest(OP_WRITE) next - } catch { case e: IOException ⇒ handleError(info.handler, e); this } + } catch { case e: IOException => handleError(info.handler, e); this } } def release(): Unit = bufferPool.release(buffer) @@ -495,11 +495,11 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha self ! UpdatePendingWriteAndThen(updated, TcpConnection.doNothing) } else { release() - val andThen = if (!ack.isInstanceOf[NoAck]) () ⇒ commander ! ack else doNothing + val andThen = if (!ack.isInstanceOf[NoAck]) () => commander ! ack else doNothing self ! UpdatePendingWriteAndThen(PendingWrite(commander, tail), andThen) } } catch { - case e: IOException ⇒ self ! WriteFileFailed(e) + case e: IOException => self ! WriteFileFailed(e) } } } @@ -530,7 +530,7 @@ private[io] object TcpConnection { // INTERNAL MESSAGES - final case class UpdatePendingWriteAndThen(remainingWrite: PendingWrite, work: () ⇒ Unit) extends NoSerializationVerificationNeeded + final case class UpdatePendingWriteAndThen(remainingWrite: PendingWrite, work: () => Unit) extends NoSerializationVerificationNeeded final case class WriteFileFailed(e: IOException) case object Unregistered @@ -546,7 +546,7 @@ private[io] object TcpConnection { def release(): Unit = throw new IllegalStateException } - val doNothing: () ⇒ Unit = () ⇒ () + val doNothing: () => Unit = () => () val DroppingWriteBecauseWritingIsSuspendedException = new IOException("Dropping write because writing is suspended") with NoStackTrace diff --git a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala index 5f32c30aa6..716b031c26 100644 --- a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala @@ -29,6 +29,6 @@ private[io] class TcpIncomingConnection( registry.register(channel, initialOps = 0) def receive = { - case registration: ChannelRegistration ⇒ completeConnect(registration, bindHandler, options) + case registration: ChannelRegistration => completeConnect(registration, bindHandler, options) } } diff --git a/akka-actor/src/main/scala/akka/io/TcpListener.scala b/akka-actor/src/main/scala/akka/io/TcpListener.scala index a757381a82..57bbe809b3 100644 --- a/akka-actor/src/main/scala/akka/io/TcpListener.scala +++ b/akka-actor/src/main/scala/akka/io/TcpListener.scala @@ -54,18 +54,18 @@ private[io] class TcpListener( bind.options.foreach(_.beforeServerSocketBind(socket)) socket.bind(bind.localAddress, bind.backlog) val ret = socket.getLocalSocketAddress match { - case isa: InetSocketAddress ⇒ isa - case x ⇒ throw new IllegalArgumentException(s"bound to unknown SocketAddress [$x]") + case isa: InetSocketAddress => isa + case x => throw new IllegalArgumentException(s"bound to unknown SocketAddress [$x]") } channelRegistry.register(channel, if (bind.pullMode) 0 else SelectionKey.OP_ACCEPT) log.debug("Successfully bound to {}", ret) bind.options.foreach { - case o: Inet.SocketOptionV2 ⇒ o.afterBind(channel.socket) - case _ ⇒ + case o: Inet.SocketOptionV2 => o.afterBind(channel.socket) + case _ => } ret } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => bindCommander ! bind.failureMessage.withCause(e) log.error(e, "Bind failed for TCP channel on endpoint [{}]", bind.localAddress) context.stop(self) @@ -74,35 +74,35 @@ private[io] class TcpListener( override def supervisorStrategy = SelectionHandler.connectionSupervisorStrategy def receive: Receive = { - case registration: ChannelRegistration ⇒ + case registration: ChannelRegistration => bindCommander ! Bound(channel.socket.getLocalSocketAddress.asInstanceOf[InetSocketAddress]) context.become(bound(registration)) } def bound(registration: ChannelRegistration): Receive = { - case ChannelAcceptable ⇒ + case ChannelAcceptable => acceptLimit = acceptAllPending(registration, acceptLimit) if (acceptLimit > 0) registration.enableInterest(SelectionKey.OP_ACCEPT) - case ResumeAccepting(batchSize) ⇒ + case ResumeAccepting(batchSize) => acceptLimit = batchSize registration.enableInterest(SelectionKey.OP_ACCEPT) - case FailedRegisterIncoming(socketChannel) ⇒ + case FailedRegisterIncoming(socketChannel) => log.warning("Could not register incoming connection since selector capacity limit is reached, closing connection") try socketChannel.close() catch { - case NonFatal(e) ⇒ log.debug("Error closing socket channel: {}", e) + case NonFatal(e) => log.debug("Error closing socket channel: {}", e) } - case Unbind ⇒ + case Unbind => log.debug("Unbinding endpoint {}", localAddress) - registration.cancelAndClose { () ⇒ self ! Unbound } + registration.cancelAndClose { () => self ! Unbound } context.become(unregistering(sender())) } def unregistering(requester: ActorRef): Receive = { - case Unbound ⇒ + case Unbound => requester ! Unbound log.debug("Unbound endpoint {}, stopping listener", localAddress) context.stop(self) @@ -113,7 +113,7 @@ private[io] class TcpListener( if (limit > 0) { try channel.accept() catch { - case NonFatal(e) ⇒ { log.error(e, "Accept error: could not accept new connection"); null } + case NonFatal(e) => { log.error(e, "Accept error: could not accept new connection"); null } } } else null if (socketChannel != null) { @@ -133,7 +133,7 @@ private[io] class TcpListener( channel.close() } } catch { - case NonFatal(e) ⇒ log.debug("Error closing ServerSocketChannel: {}", e) + case NonFatal(e) => log.debug("Error closing ServerSocketChannel: {}", e) } } } diff --git a/akka-actor/src/main/scala/akka/io/TcpManager.scala b/akka-actor/src/main/scala/akka/io/TcpManager.scala index ba2a9c11d7..6b70581703 100644 --- a/akka-actor/src/main/scala/akka/io/TcpManager.scala +++ b/akka-actor/src/main/scala/akka/io/TcpManager.scala @@ -48,13 +48,13 @@ private[io] class TcpManager(tcp: TcpExt) extends SelectionHandler.SelectorBasedManager(tcp.Settings, tcp.Settings.NrOfSelectors) with ActorLogging { def receive = workerForCommandHandler { - case c: Connect ⇒ + case c: Connect => val commander = sender() // cache because we create a function that will run asynchly - (registry ⇒ Props(classOf[TcpOutgoingConnection], tcp, registry, commander, c)) + (registry => Props(classOf[TcpOutgoingConnection], tcp, registry, commander, c)) - case b: Bind ⇒ + case b: Bind => val commander = sender() // cache because we create a function that will run asynchly - (registry ⇒ Props(classOf[TcpListener], selectorPool, tcp, registry, commander, b)) + (registry => Props(classOf[TcpListener], selectorPool, tcp, registry, commander, b)) } } diff --git a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala index cc646d4346..5ecd481764 100644 --- a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala @@ -42,42 +42,42 @@ private[io] class TcpOutgoingConnection( private def stop(cause: Throwable): Unit = stopWith(CloseInformation(Set(commander), connect.failureMessage.withCause(cause)), shouldAbort = true) - private def reportConnectFailure(thunk: ⇒ Unit): Unit = { + private def reportConnectFailure(thunk: => Unit): Unit = { try { thunk } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.debug("Could not establish connection to [{}] due to {}", remoteAddress, e) stop(e) } } def receive: Receive = { - case registration: ChannelRegistration ⇒ + case registration: ChannelRegistration => setRegistration(registration) reportConnectFailure { if (remoteAddress.isUnresolved) { log.debug("Resolving {} before connecting", remoteAddress.getHostName) Dns.resolve(remoteAddress.getHostName)(system, self) match { - case None ⇒ + case None => context.become(resolving(registration)) - case Some(resolved) ⇒ + case Some(resolved) => register(new InetSocketAddress(resolved.addr, remoteAddress.getPort), registration) } } else { register(remoteAddress, registration) } } - case ReceiveTimeout ⇒ + case ReceiveTimeout => connectionTimeout() } def resolving(registration: ChannelRegistration): Receive = { - case resolved: Dns.Resolved ⇒ + case resolved: Dns.Resolved => reportConnectFailure { register(new InetSocketAddress(resolved.addr, remoteAddress.getPort), registration) } - case ReceiveTimeout ⇒ + case ReceiveTimeout => connectionTimeout() } @@ -95,7 +95,7 @@ private[io] class TcpOutgoingConnection( def connecting(registration: ChannelRegistration, remainingFinishConnectRetries: Int): Receive = { { - case ChannelConnectable ⇒ + case ChannelConnectable => reportConnectFailure { if (channel.finishConnect()) { if (timeout.isDefined) context.setReceiveTimeout(Duration.Undefined) // Clear the timeout @@ -114,7 +114,7 @@ private[io] class TcpOutgoingConnection( } } } - case ReceiveTimeout ⇒ + case ReceiveTimeout => connectionTimeout() } } diff --git a/akka-actor/src/main/scala/akka/io/Udp.scala b/akka-actor/src/main/scala/akka/io/Udp.scala index ee4149b4f6..35abda6217 100644 --- a/akka-actor/src/main/scala/akka/io/Udp.scala +++ b/akka-actor/src/main/scala/akka/io/Udp.scala @@ -236,7 +236,7 @@ class UdpExt(system: ExtendedActorSystem) extends IO.Extension { */ object UdpMessage { import Udp._ - import java.lang.{ Iterable ⇒ JIterable } + import java.lang.{ Iterable => JIterable } import scala.collection.JavaConverters._ /** diff --git a/akka-actor/src/main/scala/akka/io/UdpConnected.scala b/akka-actor/src/main/scala/akka/io/UdpConnected.scala index 2d78b12176..92bea743ff 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnected.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnected.scala @@ -4,7 +4,7 @@ package akka.io -import java.lang.{ Iterable ⇒ JIterable } +import java.lang.{ Iterable => JIterable } import java.net.InetSocketAddress import scala.collection.immutable import akka.io.Inet.SocketOption diff --git a/akka-actor/src/main/scala/akka/io/UdpConnectedManager.scala b/akka-actor/src/main/scala/akka/io/UdpConnectedManager.scala index 732a8363b9..fe072c5740 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnectedManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnectedManager.scala @@ -14,9 +14,9 @@ private[io] class UdpConnectedManager(udpConn: UdpConnectedExt) extends SelectionHandler.SelectorBasedManager(udpConn.settings, udpConn.settings.NrOfSelectors) { def receive = workerForCommandHandler { - case c: Connect ⇒ + case c: Connect => val commander = sender() // cache because we create a function that will run asynchly - registry ⇒ Props(classOf[UdpConnection], udpConn, registry, commander, c) + registry => Props(classOf[UdpConnection], udpConn, registry, commander, c) } } diff --git a/akka-actor/src/main/scala/akka/io/UdpConnection.scala b/akka-actor/src/main/scala/akka/io/UdpConnection.scala index 6577791219..c6d8b78712 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnection.scala @@ -39,9 +39,9 @@ private[io] class UdpConnection( if (remoteAddress.isUnresolved) { Dns.resolve(remoteAddress.getHostName)(context.system, self) match { - case Some(r) ⇒ + case Some(r) => doConnect(new InetSocketAddress(r.addr, remoteAddress.getPort)) - case None ⇒ + case None => context.become(resolving(), discardOld = true) } } else { @@ -49,7 +49,7 @@ private[io] class UdpConnection( } def resolving(): Receive = { - case r: Dns.Resolved ⇒ + case r: Dns.Resolved => reportConnectFailure { doConnect(new InetSocketAddress(r.addr, remoteAddress.getPort)) } @@ -69,40 +69,40 @@ private[io] class UdpConnection( } def receive = { - case registration: ChannelRegistration ⇒ + case registration: ChannelRegistration => options.foreach { - case v2: Inet.SocketOptionV2 ⇒ v2.afterConnect(channel.socket) - case _ ⇒ + case v2: Inet.SocketOptionV2 => v2.afterConnect(channel.socket) + case _ => } commander ! Connected context.become(connected(registration), discardOld = true) } def connected(registration: ChannelRegistration): Receive = { - case SuspendReading ⇒ registration.disableInterest(OP_READ) - case ResumeReading ⇒ registration.enableInterest(OP_READ) - case ChannelReadable ⇒ doRead(registration, handler) + case SuspendReading => registration.disableInterest(OP_READ) + case ResumeReading => registration.enableInterest(OP_READ) + case ChannelReadable => doRead(registration, handler) - case Disconnect ⇒ + case Disconnect => log.debug("Closing UDP connection to [{}]", remoteAddress) channel.close() sender() ! Disconnected log.debug("Connection closed to [{}], stopping listener", remoteAddress) context.stop(self) - case send: Send if writePending ⇒ + case send: Send if writePending => if (TraceLogging) log.debug("Dropping write because queue is full") sender() ! CommandFailed(send) - case send: Send if send.payload.isEmpty ⇒ + case send: Send if send.payload.isEmpty => if (send.wantsAck) sender() ! send.ack - case send: Send ⇒ + case send: Send => pendingSend = (send, sender()) registration.enableInterest(OP_WRITE) - case ChannelWritable ⇒ doWrite() + case ChannelWritable => doWrite() } def doRead(registration: ChannelRegistration, handler: ActorRef): Unit = { @@ -147,15 +147,15 @@ private[io] class UdpConnection( log.debug("Closing DatagramChannel after being stopped") try channel.close() catch { - case NonFatal(e) ⇒ log.debug("Error closing DatagramChannel: {}", e) + case NonFatal(e) => log.debug("Error closing DatagramChannel: {}", e) } } - private def reportConnectFailure(thunk: ⇒ Unit): Unit = { + private def reportConnectFailure(thunk: => Unit): Unit = { try { thunk } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.debug( "Failure while connecting UDP channel to remote address [{}] local address [{}]: {}", remoteAddress, localAddress.getOrElse("undefined"), e) diff --git a/akka-actor/src/main/scala/akka/io/UdpListener.scala b/akka-actor/src/main/scala/akka/io/UdpListener.scala index 061e550748..ba33ef0560 100644 --- a/akka-actor/src/main/scala/akka/io/UdpListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpListener.scala @@ -35,7 +35,7 @@ private[io] class UdpListener( context.watch(bind.handler) // sign death pact val channel = bind.options.collectFirst { - case creator: DatagramChannelCreator ⇒ creator + case creator: DatagramChannelCreator => creator }.getOrElse(DatagramChannelCreator()).create() channel.configureBlocking(false) @@ -45,42 +45,42 @@ private[io] class UdpListener( bind.options.foreach(_.beforeDatagramBind(socket)) socket.bind(bind.localAddress) val ret = socket.getLocalSocketAddress match { - case isa: InetSocketAddress ⇒ isa - case x ⇒ throw new IllegalArgumentException(s"bound to unknown SocketAddress [$x]") + case isa: InetSocketAddress => isa + case x => throw new IllegalArgumentException(s"bound to unknown SocketAddress [$x]") } channelRegistry.register(channel, OP_READ) log.debug("Successfully bound to [{}]", ret) bind.options.foreach { - case o: Inet.SocketOptionV2 ⇒ o.afterBind(channel.socket) - case _ ⇒ + case o: Inet.SocketOptionV2 => o.afterBind(channel.socket) + case _ => } ret } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => bindCommander ! CommandFailed(bind) log.error(e, "Failed to bind UDP channel to endpoint [{}]", bind.localAddress) context.stop(self) } def receive: Receive = { - case registration: ChannelRegistration ⇒ + case registration: ChannelRegistration => bindCommander ! Bound(channel.socket.getLocalSocketAddress.asInstanceOf[InetSocketAddress]) context.become(readHandlers(registration) orElse sendHandlers(registration), discardOld = true) } def readHandlers(registration: ChannelRegistration): Receive = { - case SuspendReading ⇒ registration.disableInterest(OP_READ) - case ResumeReading ⇒ registration.enableInterest(OP_READ) - case ChannelReadable ⇒ doReceive(registration, bind.handler) + case SuspendReading => registration.disableInterest(OP_READ) + case ResumeReading => registration.enableInterest(OP_READ) + case ChannelReadable => doReceive(registration, bind.handler) - case Unbind ⇒ + case Unbind => log.debug("Unbinding endpoint [{}]", bind.localAddress) - registration.cancelAndClose(() ⇒ self ! Unbound) + registration.cancelAndClose(() => self ! Unbound) context.become(unregistering(sender())) } def unregistering(requester: ActorRef): Receive = { - case Unbound ⇒ + case Unbound => log.debug("Unbound endpoint [{}], stopping listener", bind.localAddress) requester ! Unbound context.stop(self) @@ -92,11 +92,11 @@ private[io] class UdpListener( buffer.limit(DirectBufferSize) channel.receive(buffer) match { - case sender: InetSocketAddress ⇒ + case sender: InetSocketAddress => buffer.flip() handler ! Received(ByteString(buffer), sender) if (readsLeft > 0) innerReceive(readsLeft - 1, buffer) - case null ⇒ // null means no data was available + case null => // null means no data was available } } @@ -112,7 +112,7 @@ private[io] class UdpListener( log.debug("Closing DatagramChannel after being stopped") try channel.close() catch { - case NonFatal(e) ⇒ log.debug("Error closing DatagramChannel: {}", e) + case NonFatal(e) => log.debug("Error closing DatagramChannel: {}", e) } } } diff --git a/akka-actor/src/main/scala/akka/io/UdpManager.scala b/akka-actor/src/main/scala/akka/io/UdpManager.scala index b1f44855f6..0927c135a1 100644 --- a/akka-actor/src/main/scala/akka/io/UdpManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpManager.scala @@ -47,13 +47,13 @@ import akka.io.Udp._ private[io] class UdpManager(udp: UdpExt) extends SelectionHandler.SelectorBasedManager(udp.settings, udp.settings.NrOfSelectors) { def receive = workerForCommandHandler { - case b: Bind ⇒ + case b: Bind => val commander = sender() // cache because we create a function that will run asynchly - (registry ⇒ Props(classOf[UdpListener], udp, registry, commander, b)) + (registry => Props(classOf[UdpListener], udp, registry, commander, b)) - case SimpleSender(options) ⇒ + case SimpleSender(options) => val commander = sender() // cache because we create a function that will run asynchly - (registry ⇒ Props(classOf[UdpSender], udp, registry, commander, options)) + (registry => Props(classOf[UdpSender], udp, registry, commander, options)) } } diff --git a/akka-actor/src/main/scala/akka/io/UdpSender.scala b/akka-actor/src/main/scala/akka/io/UdpSender.scala index 5b0e1dcc05..9531d845f8 100644 --- a/akka-actor/src/main/scala/akka/io/UdpSender.scala +++ b/akka-actor/src/main/scala/akka/io/UdpSender.scala @@ -33,10 +33,10 @@ private[io] class UdpSender( channelRegistry.register(channel, initialOps = 0) def receive: Receive = { - case registration: ChannelRegistration ⇒ + case registration: ChannelRegistration => options.foreach { - case v2: Inet.SocketOptionV2 ⇒ v2.afterConnect(channel.socket) - case _ ⇒ + case v2: Inet.SocketOptionV2 => v2.afterConnect(channel.socket) + case _ => } commander ! SimpleSenderReady context.become(sendHandlers(registration)) @@ -46,7 +46,7 @@ private[io] class UdpSender( log.debug("Closing DatagramChannel after being stopped") try channel.close() catch { - case NonFatal(e) ⇒ log.debug("Error closing DatagramChannel: {}", e) + case NonFatal(e) => log.debug("Error closing DatagramChannel: {}", e) } } } diff --git a/akka-actor/src/main/scala/akka/io/WithUdpSend.scala b/akka-actor/src/main/scala/akka/io/WithUdpSend.scala index a4b296e615..275ca2da2c 100644 --- a/akka-actor/src/main/scala/akka/io/WithUdpSend.scala +++ b/akka-actor/src/main/scala/akka/io/WithUdpSend.scala @@ -16,7 +16,7 @@ import scala.util.control.NonFatal * INTERNAL API */ private[io] trait WithUdpSend { - me: Actor with ActorLogging ⇒ + me: Actor with ActorLogging => private var pendingSend: Send = null private var pendingCommander: ActorRef = null @@ -32,25 +32,25 @@ private[io] trait WithUdpSend { import settings._ def sendHandlers(registration: ChannelRegistration): Receive = { - case send: Send if hasWritePending ⇒ + case send: Send if hasWritePending => if (TraceLogging) log.debug("Dropping write because queue is full") sender() ! CommandFailed(send) - case send: Send if send.payload.isEmpty ⇒ + case send: Send if send.payload.isEmpty => if (send.wantsAck) sender() ! send.ack - case send: Send ⇒ + case send: Send => pendingSend = send pendingCommander = sender() if (send.target.isUnresolved) { Dns.resolve(send.target.getHostName)(context.system, self) match { - case Some(r) ⇒ + case Some(r) => try { pendingSend = pendingSend.copy(target = new InetSocketAddress(r.addr, pendingSend.target.getPort)) doSend(registration) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => sender() ! CommandFailed(send) log.debug( "Failure while sending UDP datagram to remote address [{}]: {}", @@ -59,7 +59,7 @@ private[io] trait WithUdpSend { pendingSend = null pendingCommander = null } - case None ⇒ + case None => sender() ! CommandFailed(send) log.debug( "Name resolution failed for remote address [{}]", @@ -72,7 +72,7 @@ private[io] trait WithUdpSend { doSend(registration) } - case ChannelWritable ⇒ if (hasWritePending) doSend(registration) + case ChannelWritable => if (hasWritePending) doSend(registration) } private def doSend(registration: ChannelRegistration): Unit = { diff --git a/akka-actor/src/main/scala/akka/io/dns/CachePolicy.scala b/akka-actor/src/main/scala/akka/io/dns/CachePolicy.scala index 4914152e65..0920df81b0 100644 --- a/akka-actor/src/main/scala/akka/io/dns/CachePolicy.scala +++ b/akka-actor/src/main/scala/akka/io/dns/CachePolicy.scala @@ -20,8 +20,8 @@ object CachePolicy { def getValue: java.time.Duration = value.asJava override def equals(other: Any): Boolean = other match { - case that: Ttl ⇒ value == that.value - case _ ⇒ false + case that: Ttl => value == that.value + case _ => false } override def hashCode(): Int = value.hashCode() diff --git a/akka-actor/src/main/scala/akka/io/dns/DnsProtocol.scala b/akka-actor/src/main/scala/akka/io/dns/DnsProtocol.scala index 832d107780..2076573f26 100644 --- a/akka-actor/src/main/scala/akka/io/dns/DnsProtocol.scala +++ b/akka-actor/src/main/scala/akka/io/dns/DnsProtocol.scala @@ -8,7 +8,7 @@ import java.util import akka.actor.NoSerializationVerificationNeeded -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } import scala.collection.JavaConverters._ /** diff --git a/akka-actor/src/main/scala/akka/io/dns/DnsResourceRecords.scala b/akka-actor/src/main/scala/akka/io/dns/DnsResourceRecords.scala index 3407f505d7..e20f1823f2 100644 --- a/akka-actor/src/main/scala/akka/io/dns/DnsResourceRecords.scala +++ b/akka-actor/src/main/scala/akka/io/dns/DnsResourceRecords.scala @@ -129,11 +129,11 @@ private[dns] object ResourceRecord { val data = it.clone().take(rdLength) it.drop(rdLength) (recType: @switch) match { - case 1 ⇒ ARecord.parseBody(name, ttl, rdLength, data) - case 5 ⇒ CNameRecord.parseBody(name, ttl, rdLength, data, msg) - case 28 ⇒ AAAARecord.parseBody(name, ttl, rdLength, data) - case 33 ⇒ SRVRecord.parseBody(name, ttl, rdLength, data, msg) - case _ ⇒ UnknownRecord.parseBody(name, ttl, recType, recClass, rdLength, data) + case 1 => ARecord.parseBody(name, ttl, rdLength, data) + case 5 => CNameRecord.parseBody(name, ttl, rdLength, data, msg) + case 28 => AAAARecord.parseBody(name, ttl, rdLength, data) + case 33 => SRVRecord.parseBody(name, ttl, rdLength, data, msg) + case _ => UnknownRecord.parseBody(name, ttl, recType, recClass, rdLength, data) } } } diff --git a/akka-actor/src/main/scala/akka/io/dns/DnsSettings.scala b/akka-actor/src/main/scala/akka/io/dns/DnsSettings.scala index d283fa246b..56d9a9bfa6 100644 --- a/akka-actor/src/main/scala/akka/io/dns/DnsSettings.scala +++ b/akka-actor/src/main/scala/akka/io/dns/DnsSettings.scala @@ -29,20 +29,20 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { val NameServers: List[InetSocketAddress] = { c.getValue("nameservers").valueType() match { - case ConfigValueType.STRING ⇒ + case ConfigValueType.STRING => c.getString("nameservers") match { - case "default" ⇒ + case "default" => val osAddresses = getDefaultNameServers(system).getOrElse(failUnableToDetermineDefaultNameservers) if (osAddresses.isEmpty) failUnableToDetermineDefaultNameservers osAddresses - case other ⇒ + case other => parseNameserverAddress(other) :: Nil } - case ConfigValueType.LIST ⇒ + case ConfigValueType.LIST => val userAddresses = c.getStringList("nameservers").asScala.iterator.map(parseNameserverAddress).to(immutable.IndexedSeq) require(userAddresses.nonEmpty, "nameservers can not be empty") userAddresses.toList - case _ ⇒ throw new IllegalArgumentException("Invalid type for nameservers. Must be a string or string list") + case _ => throw new IllegalArgumentException("Invalid type for nameservers. Must be a string or string list") } } @@ -56,8 +56,8 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { } else if (etcResolvConf.exists()) { val parsed = ResolvConfParser.parseFile(etcResolvConf) parsed match { - case Success(value) ⇒ Some(value) - case Failure(exception) ⇒ + case Success(value) => Some(value) + case Failure(exception) => if (system.log.isWarningEnabled) { system.log.error(exception, "Error parsing /etc/resolv.conf, ignoring.") } @@ -68,31 +68,31 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { val SearchDomains: List[String] = { c.getValue("search-domains").valueType() match { - case ConfigValueType.STRING ⇒ + case ConfigValueType.STRING => c.getString("search-domains") match { - case "default" ⇒ resolvConf.map(_.search).getOrElse(Nil) - case single ⇒ List(single) + case "default" => resolvConf.map(_.search).getOrElse(Nil) + case single => List(single) } - case ConfigValueType.LIST ⇒ + case ConfigValueType.LIST => c.getStringList("search-domains").asScala.toList - case _ ⇒ throw new IllegalArgumentException("Invalid type for search-domains. Must be a string or string list.") + case _ => throw new IllegalArgumentException("Invalid type for search-domains. Must be a string or string list.") } } val NDots: Int = { c.getValue("ndots").valueType() match { - case ConfigValueType.STRING ⇒ + case ConfigValueType.STRING => c.getString("ndots") match { - case "default" ⇒ resolvConf.map(_.ndots).getOrElse(1) - case _ ⇒ throw new IllegalArgumentException("Invalid value for ndots. Must be the string 'default' or an integer.") + case "default" => resolvConf.map(_.ndots).getOrElse(1) + case _ => throw new IllegalArgumentException("Invalid value for ndots. Must be the string 'default' or an integer.") } - case ConfigValueType.NUMBER ⇒ + case ConfigValueType.NUMBER => val ndots = c.getInt("ndots") if (ndots < 0) { throw new IllegalArgumentException("Invalid value for ndots, ndots must not be negative.") } ndots - case _ ⇒ throw new IllegalArgumentException("Invalid value for ndots. Must be the string 'default' or an integer.") + case _ => throw new IllegalArgumentException("Invalid value for ndots. Must be the string 'default' or an integer.") } } @@ -133,8 +133,8 @@ object DnsSettings { val uri = new URI(server) val host = uri.getHost val port = uri.getPort match { - case -1 ⇒ DnsFallbackPort - case selected ⇒ selected + case -1 => DnsFallbackPort + case selected => selected } new InetSocketAddress(host, port) } @@ -160,7 +160,7 @@ object DnsSettings { // Only try if not empty as otherwise we will produce an exception if (dnsUrls != null && !dnsUrls.isEmpty) { val servers = dnsUrls.split(" ") - servers.flatMap { server ⇒ asInetSocketAddress(server).toOption }.toList + servers.flatMap { server => asInetSocketAddress(server).toOption }.toList } else Nil } } @@ -169,7 +169,7 @@ object DnsSettings { // this method will not work when running modularised of course since it needs access to internal sun classes def getNameserversUsingReflection: Try[List[InetSocketAddress]] = { system.dynamicAccess.getClassFor("sun.net.dns.ResolverConfiguration") - .flatMap { c ⇒ + .flatMap { c => Try { val open = c.getMethod("open") val nameservers = c.getMethod("nameservers") @@ -177,7 +177,7 @@ object DnsSettings { val ns = nameservers.invoke(instance).asInstanceOf[util.List[String]] val res = if (ns.isEmpty) throw new IllegalStateException("Empty nameservers list discovered using reflection. Consider configuring default nameservers manually!") else ns.asScala.toList - res.flatMap(s ⇒ asInetSocketAddress(s).toOption) + res.flatMap(s => asInetSocketAddress(s).toOption) } } } diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsCache.scala b/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsCache.scala index c4ef22db24..2b11874f35 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsCache.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsCache.scala @@ -22,7 +22,7 @@ import scala.collection.immutable @InternalApi class AsyncDnsCache extends Dns with PeriodicCacheCleanup with NoSerializationVerificationNeeded { private val cacheRef = new AtomicReference(new Cache[(String, RequestType), Resolved]( immutable.SortedSet()(expiryEntryOrdering()), - immutable.Map(), () ⇒ clock)) + immutable.Map(), () => clock)) private val nanoBase = System.nanoTime() @@ -36,8 +36,8 @@ import scala.collection.immutable val both = cacheRef.get().get((name, Ip())).toList.flatMap(_.records) val all = (ipv4 ++ ipv6 ++ both).collect { - case r: ARecord ⇒ r.ip - case r: AAAARecord ⇒ r.ip + case r: ARecord => r.ip + case r: AAAARecord => r.ip } if (all.isEmpty) None else Some(Dns.Resolved(name, all)) diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsManager.scala b/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsManager.scala index 05f6a70145..a4ae6be326 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsManager.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsManager.scala @@ -49,47 +49,47 @@ private[io] final class AsyncDnsManager(name: String, system: ExtendedActorSyste implicit val timeout = Timeout(settings.ResolveTimeout) private val resolver = { - val props: Props = FromConfig.props(Props(provider.actorClass, settings, cache, (factory: ActorRefFactory, dns: List[InetSocketAddress]) ⇒ { - dns.map(ns ⇒ factory.actorOf(Props(new DnsClient(ns)))) + val props: Props = FromConfig.props(Props(provider.actorClass, settings, cache, (factory: ActorRefFactory, dns: List[InetSocketAddress]) => { + dns.map(ns => factory.actorOf(Props(new DnsClient(ns)))) }).withDeploy(Deploy.local).withDispatcher(dispatcher)) context.actorOf(props, name) } private val cacheCleanup = cache match { - case cleanup: PeriodicCacheCleanup ⇒ Some(cleanup) - case _ ⇒ None + case cleanup: PeriodicCacheCleanup => Some(cleanup) + case _ => None } override def preStart(): Unit = { - cacheCleanup.foreach { _ ⇒ + cacheCleanup.foreach { _ => val interval = Duration(resolverConfig.getDuration("cache-cleanup-interval", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) timers.startPeriodicTimer(CacheCleanup, CacheCleanup, interval) } } override def receive: Receive = { - case r: DnsProtocol.Resolve ⇒ + case r: DnsProtocol.Resolve => log.debug("Resolution request for {} {} from {}", r.name, r.requestType, sender()) resolver.forward(r) - case Dns.Resolve(name) ⇒ + case Dns.Resolve(name) => // adapt legacy protocol to new protocol log.debug("Resolution request for {} from {}", name, sender()) val adapted = DnsProtocol.Resolve(name) val reply = (resolver ? adapted).mapTo[DnsProtocol.Resolved] - .map { asyncResolved ⇒ + .map { asyncResolved => val ips = asyncResolved.records.collect { - case a: ARecord ⇒ a.ip - case a: AAAARecord ⇒ a.ip + case a: ARecord => a.ip + case a: AAAARecord => a.ip } Dns.Resolved(asyncResolved.name, ips) } reply pipeTo sender() - case CacheCleanup ⇒ + case CacheCleanup => cacheCleanup.foreach(_.cleanup()) - case AsyncDnsManager.GetCache ⇒ + case AsyncDnsManager.GetCache => sender() ! cache } diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsResolver.scala b/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsResolver.scala index 22c20181e7..787b155874 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsResolver.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/AsyncDnsResolver.scala @@ -28,7 +28,7 @@ import scala.util.control.NonFatal private[io] final class AsyncDnsResolver( settings: DnsSettings, cache: AsyncDnsCache, - clientFactory: (ActorRefFactory, List[InetSocketAddress]) ⇒ List[ActorRef]) extends Actor with ActorLogging { + clientFactory: (ActorRefFactory, List[InetSocketAddress]) => List[ActorRef]) extends Actor with ActorLogging { import AsyncDnsResolver._ @@ -50,13 +50,13 @@ private[io] final class AsyncDnsResolver( private val resolvers: List[ActorRef] = clientFactory(context, nameServers) override def receive: Receive = { - case DnsProtocol.Resolve(name, mode) ⇒ + case DnsProtocol.Resolve(name, mode) => cache.get((name, mode)) match { - case Some(resolved) ⇒ + case Some(resolved) => log.debug("{} cached {}", mode, resolved) sender() ! resolved - case None ⇒ - resolveWithResolvers(name, mode, resolvers).map { resolved ⇒ + case None => + resolveWithResolvers(name, mode, resolvers).map { resolved => if (resolved.records.nonEmpty) { val minTtl = resolved.records.minBy[Duration](_.ttl.value).ttl cache.put((name, mode), resolved, minTtl) @@ -72,18 +72,18 @@ private[io] final class AsyncDnsResolver( Try { val address = InetAddress.getByName(name) // only checks validity, since known to be IP address val record = address match { - case _: Inet4Address ⇒ ARecord(name, Ttl.effectivelyForever, address) - case ipv6address: Inet6Address ⇒ AAAARecord(name, Ttl.effectivelyForever, ipv6address) + case _: Inet4Address => ARecord(name, Ttl.effectivelyForever, address) + case ipv6address: Inet6Address => AAAARecord(name, Ttl.effectivelyForever, ipv6address) } DnsProtocol.Resolved(name, record :: Nil) } } } else { resolvers match { - case Nil ⇒ + case Nil => Future.failed(ResolveFailedException(s"Failed to resolve $name with nameservers: $nameServers")) - case head :: tail ⇒ resolveWithSearch(name, requestType, head).recoverWith { - case NonFatal(t) ⇒ + case head :: tail => resolveWithSearch(name, requestType, head).recoverWith { + case NonFatal(t) => log.error(t, "Resolve failed. Trying next name server") resolveWithResolvers(name, requestType, tail) } @@ -92,13 +92,13 @@ private[io] final class AsyncDnsResolver( private def sendQuestion(resolver: ActorRef, message: DnsQuestion): Future[Answer] = { val result = (resolver ? message).mapTo[Answer] - result.failed.foreach { _ ⇒ resolver ! DropRequest(message.id) } + result.failed.foreach { _ => resolver ! DropRequest(message.id) } result } private def resolveWithSearch(name: String, requestType: RequestType, resolver: ActorRef): Future[DnsProtocol.Resolved] = { if (settings.SearchDomains.nonEmpty) { - val nameWithSearch = settings.SearchDomains.map(sd ⇒ name + "." + sd) + val nameWithSearch = settings.SearchDomains.map(sd => name + "." + sd) // ndots is a heuristic used to try and work out whether the name passed in is a fully qualified domain name, // or a name relative to one of the search names. The idea is to prevent the cost of doing a lookup that is // obviously not going to resolve. So, if a host has less than ndots dots in it, then we don't try and resolve it, @@ -120,14 +120,14 @@ private[io] final class AsyncDnsResolver( private def resolveFirst(searchNames: List[String], requestType: RequestType, resolver: ActorRef): Future[DnsProtocol.Resolved] = { searchNames match { - case searchName :: Nil ⇒ + case searchName :: Nil => resolve(searchName, requestType, resolver) - case searchName :: remaining ⇒ - resolve(searchName, requestType, resolver).flatMap { resolved ⇒ + case searchName :: remaining => + resolve(searchName, requestType, resolver).flatMap { resolved => if (resolved.records.isEmpty) resolveFirst(remaining, requestType, resolver) else Future.successful(resolved) } - case Nil ⇒ + case Nil => // This can't happen Future.failed(new IllegalStateException("Failed to 'resolveFirst': 'searchNames' must not be empty")) } @@ -137,7 +137,7 @@ private[io] final class AsyncDnsResolver( log.debug("Attempting to resolve {} with {}", name, resolver) val caseFoldedName = Helpers.toRootLowerCase(name) requestType match { - case Ip(ipv4, ipv6) ⇒ + case Ip(ipv4, ipv6) => val ipv4Recs: Future[Answer] = if (ipv4) sendQuestion(resolver, Question4(nextId(), caseFoldedName)) @@ -150,13 +150,13 @@ private[io] final class AsyncDnsResolver( Empty for { - ipv4 ← ipv4Recs - ipv6 ← ipv6Recs + ipv4 <- ipv4Recs + ipv6 <- ipv6Recs } yield DnsProtocol.Resolved(name, ipv4.rrs ++ ipv6.rrs, ipv4.additionalRecs ++ ipv6.additionalRecs) - case Srv ⇒ + case Srv => sendQuestion(resolver, SrvQuestion(nextId(), caseFoldedName)) - .map(answer ⇒ { + .map(answer => { DnsProtocol.Resolved(name, answer.rrs, answer.additionalRecs) }) } diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/DnsClient.scala b/akka-actor/src/main/scala/akka/io/dns/internal/DnsClient.scala index 444b74a2dd..fd5ce11136 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/DnsClient.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/DnsClient.scala @@ -13,7 +13,7 @@ import akka.io.dns.{ RecordClass, RecordType, ResourceRecord } import akka.io.{ IO, Tcp, Udp } import akka.pattern.BackoffSupervisor -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } import scala.util.Try import scala.concurrent.duration._ @@ -52,15 +52,15 @@ import scala.concurrent.duration._ } def receive: Receive = { - case Udp.Bound(local) ⇒ + case Udp.Bound(local) => log.debug("Bound to UDP address [{}]", local) context.become(ready(sender())) unstashAll() - case _: Question4 ⇒ + case _: Question4 => stash() - case _: Question6 ⇒ + case _: Question6 => stash() - case _: SrvQuestion ⇒ + case _: SrvQuestion => stash() } @@ -69,47 +69,47 @@ import scala.concurrent.duration._ } def ready(socket: ActorRef): Receive = { - case DropRequest(id) ⇒ + case DropRequest(id) => log.debug("Dropping request [{}]", id) inflightRequests -= id - case Question4(id, name) ⇒ + case Question4(id, name) => log.debug("Resolving [{}] (A)", name) val msg = message(name, id, RecordType.A) inflightRequests += (id -> (sender(), msg)) log.debug("Message [{}] to [{}]: [{}]", id, ns, msg) socket ! Udp.Send(msg.write(), ns) - case Question6(id, name) ⇒ + case Question6(id, name) => log.debug("Resolving [{}] (AAAA)", name) val msg = message(name, id, RecordType.AAAA) inflightRequests += (id -> (sender(), msg)) log.debug("Message to [{}]: [{}]", ns, msg) socket ! Udp.Send(msg.write(), ns) - case SrvQuestion(id, name) ⇒ + case SrvQuestion(id, name) => log.debug("Resolving [{}] (SRV)", name) val msg = message(name, id, RecordType.SRV) inflightRequests += (id -> (sender(), msg)) log.debug("Message to [{}]: [{}]", ns, msg) socket ! Udp.Send(msg.write(), ns) - case Udp.CommandFailed(cmd) ⇒ + case Udp.CommandFailed(cmd) => log.debug("Command failed [{}]", cmd) cmd match { - case send: Udp.Send ⇒ + case send: Udp.Send => // best effort, don't throw Try { val msg = Message.parse(send.payload) inflightRequests.get(msg.id).foreach { - case (s, _) ⇒ + case (s, _) => s ! Failure(new RuntimeException("Send failed to nameserver")) inflightRequests -= msg.id } } - case _ ⇒ + case _ => log.warning("Dns client failed to send {}", cmd) } - case Udp.Received(data, remote) ⇒ + case Udp.Received(data, remote) => log.debug("Received message from [{}]: [{}]", remote, data) val msg = Message.parse(data) log.debug("Decoded UDP DNS response [{}]", msg) @@ -117,25 +117,25 @@ import scala.concurrent.duration._ if (msg.flags.isTruncated) { log.debug("DNS response truncated, falling back to TCP") inflightRequests.get(msg.id) match { - case Some((_, msg)) ⇒ + case Some((_, msg)) => tcpDnsClient ! msg - case _ ⇒ + case _ => log.debug("Client for id {} not found. Discarding unsuccessful response.", msg.id) } } else { val (recs, additionalRecs) = if (msg.flags.responseCode == ResponseCode.SUCCESS) (msg.answerRecs, msg.additionalRecs) else (Nil, Nil) self ! Answer(msg.id, recs, additionalRecs) } - case response: Answer ⇒ + case response: Answer => inflightRequests.get(response.id) match { - case Some((reply, _)) ⇒ + case Some((reply, _)) => reply ! response inflightRequests -= response.id - case None ⇒ + case None => log.debug("Client for id {} not found. Discarding response.", response.id) } - case Udp.Unbind ⇒ socket ! Udp.Unbind - case Udp.Unbound ⇒ context.stop(self) + case Udp.Unbind => socket ! Udp.Unbind + case Udp.Unbound => context.stop(self) } def createTcpClient() = { diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/DnsMessage.scala b/akka-actor/src/main/scala/akka/io/dns/internal/DnsMessage.scala index cfad7d6aa9..e658484aae 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/DnsMessage.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/DnsMessage.scala @@ -135,17 +135,17 @@ private[internal] object Message { val nsCount = it.getShort val arCount = it.getShort - val qs = (0 until qdCount).map { _ ⇒ Try(Question.parse(it, msg)) } - val ans = (0 until anCount).map { _ ⇒ Try(ResourceRecord.parse(it, msg)) } - val nss = (0 until nsCount).map { _ ⇒ Try(ResourceRecord.parse(it, msg)) } - val ars = (0 until arCount).map { _ ⇒ Try(ResourceRecord.parse(it, msg)) } + val qs = (0 until qdCount).map { _ => Try(Question.parse(it, msg)) } + val ans = (0 until anCount).map { _ => Try(ResourceRecord.parse(it, msg)) } + val nss = (0 until nsCount).map { _ => Try(ResourceRecord.parse(it, msg)) } + val ars = (0 until arCount).map { _ => Try(ResourceRecord.parse(it, msg)) } import scala.language.implicitConversions implicit def flattener[T](tried: Try[T]): GenTraversableOnce[T] = if (flags.isTruncated) tried.toOption else tried match { - case Success(value) ⇒ Some(value) - case Failure(reason) ⇒ throw reason + case Success(value) => Some(value) + case Failure(reason) => throw reason } new Message(id, flags, qs.flatten, ans.flatten, nss.flatten, ars.flatten) diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/DomainName.scala b/akka-actor/src/main/scala/akka/io/dns/internal/DomainName.scala index 8f1057a75d..b55d8dcc7f 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/DomainName.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/DomainName.scala @@ -17,9 +17,9 @@ private[akka] object DomainName { } def write(it: ByteStringBuilder, name: String): Unit = { - for (label ← name.split('.')) { + for (label <- name.split('.')) { it.putByte(label.length.toByte) - for (c ← label) { + for (c <- label) { it.putByte(c.toByte) } } diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/RecordClassSerializer.scala b/akka-actor/src/main/scala/akka/io/dns/internal/RecordClassSerializer.scala index 43f0a6eaf9..7f1cca78c7 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/RecordClassSerializer.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/RecordClassSerializer.scala @@ -16,11 +16,11 @@ private[akka] object RecordClassSerializer { def parse(it: ByteIterator): RecordClass = { it.getShort match { - case 1 ⇒ RecordClass.IN - case 2 ⇒ RecordClass.CS - case 3 ⇒ RecordClass.CH - case 255 ⇒ RecordClass.WILDCARD - case unknown ⇒ throw new RuntimeException(s"Unexpected record class $unknown") + case 1 => RecordClass.IN + case 2 => RecordClass.CS + case 3 => RecordClass.CH + case 255 => RecordClass.WILDCARD + case unknown => throw new RuntimeException(s"Unexpected record class $unknown") } } diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/RecordTypeSerializer.scala b/akka-actor/src/main/scala/akka/io/dns/internal/RecordTypeSerializer.scala index d950bb2a38..47922afcec 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/RecordTypeSerializer.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/RecordTypeSerializer.scala @@ -20,8 +20,8 @@ private[akka] object RecordTypeSerializer { def parse(it: ByteIterator): RecordType = { val id = it.getShort RecordType(id) match { - case OptionVal.None ⇒ throw new IllegalArgumentException(s"Illegal id [$id] for DnsRecordType") - case OptionVal.Some(t) ⇒ t + case OptionVal.None => throw new IllegalArgumentException(s"Illegal id [$id] for DnsRecordType") + case OptionVal.Some(t) => t } } diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/ResolvConfParser.scala b/akka-actor/src/main/scala/akka/io/dns/internal/ResolvConfParser.scala index d8f440267d..80376e48a5 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/ResolvConfParser.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/ResolvConfParser.scala @@ -36,27 +36,27 @@ private[dns] object ResolvConfParser { var ndots = 1 lines.map(_.trim) - .filter { line ⇒ + .filter { line => // Ignore blank lines and comments line.nonEmpty && line(0) != ';' && line(0) != '#' } - .foreach { line ⇒ + .foreach { line => val (label, args) = line.span(!_.isWhitespace) def trimmedArgs = args.trim label match { - case `DomainLabel` ⇒ + case `DomainLabel` => search = List(trimmedArgs) - case `SearchLabel` ⇒ + case `SearchLabel` => search = trimmedArgs.split("\\s+").toList - case `OptionsLabel` ⇒ - args.split("\\s+").foreach { option ⇒ + case `OptionsLabel` => + args.split("\\s+").foreach { option => // We're only interested in ndots if (option.startsWith(NdotsOption)) { // Allow exception to fall through to Try ndots = option.drop(NdotsOption.length).toInt } } - case _ ⇒ // Ignore everything else + case _ => // Ignore everything else } } diff --git a/akka-actor/src/main/scala/akka/io/dns/internal/TcpDnsClient.scala b/akka-actor/src/main/scala/akka/io/dns/internal/TcpDnsClient.scala index 8bfed95cc4..71bf0cd000 100644 --- a/akka-actor/src/main/scala/akka/io/dns/internal/TcpDnsClient.scala +++ b/akka-actor/src/main/scala/akka/io/dns/internal/TcpDnsClient.scala @@ -22,7 +22,7 @@ import akka.util.ByteString override def receive: Receive = idle val idle: Receive = { - case _: Message ⇒ + case _: Message => stash() log.debug("Connecting to [{}]", ns) tcp ! Tcp.Connect(ns) @@ -30,25 +30,25 @@ import akka.util.ByteString } val connecting: Receive = { - case failure @ Tcp.CommandFailed(_: Tcp.Connect) ⇒ + case failure @ Tcp.CommandFailed(_: Tcp.Connect) => throwFailure(s"Failed to connect to TCP DNS server at [$ns]", failure.cause) - case _: Tcp.Connected ⇒ + case _: Tcp.Connected => log.debug("Connected to TCP address [{}]", ns) val connection = sender() context.become(ready(connection)) connection ! Tcp.Register(self) unstashAll() - case _: Message ⇒ + case _: Message => stash() } def ready(connection: ActorRef, buffer: ByteString = ByteString.empty): Receive = { - case msg: Message ⇒ + case msg: Message => val bytes = msg.write() connection ! Tcp.Write(encodeLength(bytes.length) ++ bytes) - case failure @ Tcp.CommandFailed(_: Tcp.Write) ⇒ + case failure @ Tcp.CommandFailed(_: Tcp.Write) => throwFailure("Write failed", failure.cause) - case Tcp.Received(newData) ⇒ + case Tcp.Received(newData) => val data = buffer ++ newData // TCP DNS responses are prefixed by 2 bytes encoding the length of the response val prefixSize = 2 @@ -66,7 +66,7 @@ import akka.util.ByteString } } } - case Tcp.PeerClosed ⇒ + case Tcp.PeerClosed => context.become(idle) } @@ -89,9 +89,9 @@ private[internal] object TcpDnsClient { def throwFailure(message: String, cause: Option[Throwable]): Unit = cause match { - case None ⇒ + case None => throw new AkkaException(message) - case Some(throwable) ⇒ + case Some(throwable) => throw new AkkaException(message, throwable) } } diff --git a/akka-actor/src/main/scala/akka/japi/JavaAPI.scala b/akka-actor/src/main/scala/akka/japi/JavaAPI.scala index 4c6234000a..d9a3f096ff 100644 --- a/akka-actor/src/main/scala/akka/japi/JavaAPI.scala +++ b/akka-actor/src/main/scala/akka/japi/JavaAPI.scala @@ -139,9 +139,9 @@ abstract class JavaPartialFunction[A, B] extends AbstractPartialFunction[A, B] { @throws(classOf[Exception]) def apply(x: A, isCheck: Boolean): B - final def isDefinedAt(x: A): Boolean = try { apply(x, true); true } catch { case NoMatch ⇒ false } - final override def apply(x: A): B = try apply(x, false) catch { case NoMatch ⇒ throw new MatchError(x) } - final override def applyOrElse[A1 <: A, B1 >: B](x: A1, default: A1 ⇒ B1): B1 = try apply(x, false) catch { case NoMatch ⇒ default(x) } + final def isDefinedAt(x: A): Boolean = try { apply(x, true); true } catch { case NoMatch => false } + final override def apply(x: A): B = try apply(x, false) catch { case NoMatch => throw new MatchError(x) } + final override def applyOrElse[A1 <: A, B1 >: B](x: A1, default: A1 => B1): B1 = try apply(x, false) catch { case NoMatch => default(x) } } /** @@ -183,8 +183,8 @@ object Option { * Converts a Scala Option to a Java Option */ def fromScalaOption[T](scalaOption: scala.Option[T]): Option[T] = scalaOption match { - case scala.Some(r) ⇒ some(r) - case scala.None ⇒ none + case scala.Some(r) => some(r) + case scala.None => none } /** @@ -238,8 +238,8 @@ object Util { */ def immutableSeq[T](iterable: java.lang.Iterable[T]): immutable.Seq[T] = iterable match { - case imm: immutable.Seq[_] ⇒ imm.asInstanceOf[immutable.Seq[T]] - case other ⇒ + case imm: immutable.Seq[_] => imm.asInstanceOf[immutable.Seq[T]] + case other => val i = other.iterator() if (i.hasNext) { val builder = new immutable.VectorBuilder[T] diff --git a/akka-actor/src/main/scala/akka/pattern/AskSupport.scala b/akka-actor/src/main/scala/akka/pattern/AskSupport.scala index 6d809e987e..1e9d6e18cb 100644 --- a/akka-actor/src/main/scala/akka/pattern/AskSupport.scala +++ b/akka-actor/src/main/scala/akka/pattern/AskSupport.scala @@ -191,9 +191,9 @@ trait ExplicitAskSupport { * } pipeTo nextActor * }}} */ - def ask(actorRef: ActorRef, messageFactory: ActorRef ⇒ Any)(implicit timeout: Timeout): Future[Any] = + def ask(actorRef: ActorRef, messageFactory: ActorRef => Any)(implicit timeout: Timeout): Future[Any] = actorRef.internalAsk(messageFactory, timeout, ActorRef.noSender) - def ask(actorRef: ActorRef, messageFactory: ActorRef ⇒ Any, sender: ActorRef)(implicit timeout: Timeout): Future[Any] = + def ask(actorRef: ActorRef, messageFactory: ActorRef => Any, sender: ActorRef)(implicit timeout: Timeout): Future[Any] = actorRef.internalAsk(messageFactory, timeout, sender) /** @@ -248,9 +248,9 @@ trait ExplicitAskSupport { * }}} * */ - def ask(actorSelection: ActorSelection, messageFactory: ActorRef ⇒ Any)(implicit timeout: Timeout): Future[Any] = + def ask(actorSelection: ActorSelection, messageFactory: ActorRef => Any)(implicit timeout: Timeout): Future[Any] = actorSelection.internalAsk(messageFactory, timeout, ActorRef.noSender) - def ask(actorSelection: ActorSelection, messageFactory: ActorRef ⇒ Any, sender: ActorRef)(implicit timeout: Timeout): Future[Any] = + def ask(actorSelection: ActorSelection, messageFactory: ActorRef => Any, sender: ActorRef)(implicit timeout: Timeout): Future[Any] = actorSelection.internalAsk(messageFactory, timeout, sender) } @@ -325,10 +325,10 @@ final class AskableActorRef(val actorRef: ActorRef) extends AnyVal { * INTERNAL API: for binary compatibility */ private[pattern] def internalAsk(message: Any, timeout: Timeout, sender: ActorRef) = actorRef match { - case ref: InternalActorRef if ref.isTerminated ⇒ + case ref: InternalActorRef if ref.isTerminated => actorRef ! message Future.failed[Any](AskableActorRef.recipientTerminatedException(actorRef, message, sender)) - case ref: InternalActorRef ⇒ + case ref: InternalActorRef => if (timeout.duration.length <= 0) Future.failed[Any](AskableActorRef.negativeTimeoutException(actorRef, message, sender)) else { @@ -336,7 +336,7 @@ final class AskableActorRef(val actorRef: ActorRef) extends AnyVal { actorRef.tell(message, a) a.result.future } - case _ ⇒ Future.failed[Any](AskableActorRef.unsupportedRecipientType(actorRef, message, sender)) + case _ => Future.failed[Any](AskableActorRef.unsupportedRecipientType(actorRef, message, sender)) } } @@ -346,21 +346,21 @@ final class AskableActorRef(val actorRef: ActorRef) extends AnyVal { */ final class ExplicitlyAskableActorRef(val actorRef: ActorRef) extends AnyVal { - def ask(message: ActorRef ⇒ Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] = + def ask(message: ActorRef => Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] = internalAsk(message, timeout, sender) - def ?(message: ActorRef ⇒ Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] = + def ?(message: ActorRef => Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] = internalAsk(message, timeout, sender) /** * INTERNAL API: for binary compatibility */ - private[pattern] def internalAsk(messageFactory: ActorRef ⇒ Any, timeout: Timeout, sender: ActorRef): Future[Any] = actorRef match { - case ref: InternalActorRef if ref.isTerminated ⇒ + private[pattern] def internalAsk(messageFactory: ActorRef => Any, timeout: Timeout, sender: ActorRef): Future[Any] = actorRef match { + case ref: InternalActorRef if ref.isTerminated => val message = messageFactory(ref.provider.deadLetters) actorRef ! message Future.failed[Any](AskableActorRef.recipientTerminatedException(actorRef, message, sender)) - case ref: InternalActorRef ⇒ + case ref: InternalActorRef => if (timeout.duration.length <= 0) { val message = messageFactory(ref.provider.deadLetters) Future.failed[Any](AskableActorRef.negativeTimeoutException(actorRef, message, sender)) @@ -371,10 +371,10 @@ final class ExplicitlyAskableActorRef(val actorRef: ActorRef) extends AnyVal { actorRef.tell(message, a) a.result.future } - case _ if sender eq null ⇒ + case _ if sender eq null => Future.failed[Any](new IllegalArgumentException("No recipient for the reply was provided, " + s"question not sent to [$actorRef].")) - case _ ⇒ + case _ => val message = if (sender == null) null else messageFactory(sender.asInstanceOf[InternalActorRef].provider.deadLetters) Future.failed[Any](AskableActorRef.unsupportedRecipientType(actorRef, message, sender)) } @@ -421,7 +421,7 @@ final class AskableActorSelection(val actorSel: ActorSelection) extends AnyVal { * INTERNAL API: for binary compatibility */ private[pattern] def internalAsk(message: Any, timeout: Timeout, sender: ActorRef): Future[Any] = actorSel.anchor match { - case ref: InternalActorRef ⇒ + case ref: InternalActorRef => if (timeout.duration.length <= 0) Future.failed[Any](AskableActorRef.negativeTimeoutException(actorSel, message, sender)) else { @@ -429,7 +429,7 @@ final class AskableActorSelection(val actorSel: ActorSelection) extends AnyVal { actorSel.tell(message, a) a.result.future } - case _ ⇒ Future.failed[Any](AskableActorRef.unsupportedRecipientType(actorSel, message, sender)) + case _ => Future.failed[Any](AskableActorRef.unsupportedRecipientType(actorSel, message, sender)) } } @@ -438,17 +438,17 @@ final class AskableActorSelection(val actorSel: ActorSelection) extends AnyVal { */ final class ExplicitlyAskableActorSelection(val actorSel: ActorSelection) extends AnyVal { - def ask(message: ActorRef ⇒ Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] = + def ask(message: ActorRef => Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] = internalAsk(message, timeout, sender) - def ?(message: ActorRef ⇒ Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] = + def ?(message: ActorRef => Any)(implicit timeout: Timeout, sender: ActorRef = Actor.noSender): Future[Any] = internalAsk(message, timeout, sender) /** * INTERNAL API: for binary compatibility */ - private[pattern] def internalAsk(messageFactory: ActorRef ⇒ Any, timeout: Timeout, sender: ActorRef): Future[Any] = actorSel.anchor match { - case ref: InternalActorRef ⇒ + private[pattern] def internalAsk(messageFactory: ActorRef => Any, timeout: Timeout, sender: ActorRef): Future[Any] = actorSel.anchor match { + case ref: InternalActorRef => if (timeout.duration.length <= 0) { val message = messageFactory(ref.provider.deadLetters) Future.failed[Any](AskableActorRef.negativeTimeoutException(actorSel, message, sender)) @@ -459,10 +459,10 @@ final class ExplicitlyAskableActorSelection(val actorSel: ActorSelection) extend actorSel.tell(message, a) a.result.future } - case _ if sender eq null ⇒ + case _ if sender eq null => Future.failed[Any](new IllegalArgumentException("No recipient for the reply was provided, " + s"question not sent to [$actorSel].")) - case _ ⇒ + case _ => val message = if (sender == null) null else messageFactory(sender.asInstanceOf[InternalActorRef].provider.deadLetters) Future.failed[Any](AskableActorRef.unsupportedRecipientType(actorSel, message, sender)) } @@ -509,20 +509,20 @@ private[akka] final class PromiseActorRef private (val provider: ActorRefProvide @tailrec // Returns false if the Promise is already completed private[this] final def addWatcher(watcher: ActorRef): Boolean = watchedBy match { - case null ⇒ false - case other ⇒ updateWatchedBy(other, other + watcher) || addWatcher(watcher) + case null => false + case other => updateWatchedBy(other, other + watcher) || addWatcher(watcher) } @tailrec private[this] final def remWatcher(watcher: ActorRef): Unit = watchedBy match { - case null ⇒ () - case other ⇒ if (!updateWatchedBy(other, other - watcher)) remWatcher(watcher) + case null => () + case other => if (!updateWatchedBy(other, other - watcher)) remWatcher(watcher) } @tailrec private[this] final def clearWatchers(): Set[ActorRef] = watchedBy match { - case null ⇒ ActorCell.emptyActorRefSet - case other ⇒ if (!updateWatchedBy(other, null)) clearWatchers() else other + case null => ActorCell.emptyActorRefSet + case other => if (!updateWatchedBy(other, null)) clearWatchers() else other } @inline @@ -547,7 +547,7 @@ private[akka] final class PromiseActorRef private (val provider: ActorRefProvide */ @tailrec def path: ActorPath = state match { - case null ⇒ + case null => if (updateState(null, Registering)) { var p: ActorPath = null try { @@ -556,46 +556,46 @@ private[akka] final class PromiseActorRef private (val provider: ActorRefProvide p } finally { setState(p) } } else path - case p: ActorPath ⇒ p - case StoppedWithPath(p) ⇒ p - case Stopped ⇒ + case p: ActorPath => p + case StoppedWithPath(p) => p + case Stopped => // even if we are already stopped we still need to produce a proper path updateState(Stopped, StoppedWithPath(provider.tempPath())) path - case Registering ⇒ path // spin until registration is completed + case Registering => path // spin until registration is completed } override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = state match { - case Stopped | _: StoppedWithPath ⇒ provider.deadLetters ! message - case _ ⇒ + case Stopped | _: StoppedWithPath => provider.deadLetters ! message + case _ => if (message == null) throw InvalidMessageException("Message is null") if (!(result.tryComplete( message match { - case Status.Success(r) ⇒ Success(r) - case Status.Failure(f) ⇒ Failure(f) - case other ⇒ Success(other) + case Status.Success(r) => Success(r) + case Status.Failure(f) => Failure(f) + case other => Success(other) }))) provider.deadLetters ! message } override def sendSystemMessage(message: SystemMessage): Unit = message match { - case _: Terminate ⇒ stop() - case DeathWatchNotification(a, ec, at) ⇒ this.!(Terminated(a)(existenceConfirmed = ec, addressTerminated = at)) - case Watch(watchee, watcher) ⇒ + case _: Terminate => stop() + case DeathWatchNotification(a, ec, at) => this.!(Terminated(a)(existenceConfirmed = ec, addressTerminated = at)) + case Watch(watchee, watcher) => if (watchee == this && watcher != this) { if (!addWatcher(watcher)) // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ watcher.sendSystemMessage(DeathWatchNotification(watchee, existenceConfirmed = true, addressTerminated = false)) } else System.err.println("BUG: illegal Watch(%s,%s) for %s".format(watchee, watcher, this)) - case Unwatch(watchee, watcher) ⇒ + case Unwatch(watchee, watcher) => if (watchee == this && watcher != this) remWatcher(watcher) else System.err.println("BUG: illegal Unwatch(%s,%s) for %s".format(watchee, watcher, this)) - case _ ⇒ + case _ => } @deprecated("Use context.watch(actor) and receive Terminated(actor)", "2.2") override private[akka] def isTerminated: Boolean = state match { - case Stopped | _: StoppedWithPath ⇒ true - case _ ⇒ false + case Stopped | _: StoppedWithPath => true + case _ => false } @tailrec @@ -604,7 +604,7 @@ private[akka] final class PromiseActorRef private (val provider: ActorRefProvide result tryComplete ActorStopResult val watchers = clearWatchers() if (!watchers.isEmpty) { - watchers foreach { watcher ⇒ + watchers foreach { watcher => // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ watcher.asInstanceOf[InternalActorRef] .sendSystemMessage(DeathWatchNotification(this, existenceConfirmed = true, addressTerminated = false)) @@ -612,12 +612,12 @@ private[akka] final class PromiseActorRef private (val provider: ActorRefProvide } } state match { - case null ⇒ // if path was never queried nobody can possibly be watching us, so we don't have to publish termination either + case null => // if path was never queried nobody can possibly be watching us, so we don't have to publish termination either if (updateState(null, Stopped)) ensureCompleted() else stop() - case p: ActorPath ⇒ + case p: ActorPath => if (updateState(p, StoppedWithPath(p))) { try ensureCompleted() finally provider.unregisterTempActor(p) } else stop() - case Stopped | _: StoppedWithPath ⇒ // already stopped - case Registering ⇒ stop() // spin until registration is completed before stopping + case Stopped | _: StoppedWithPath => // already stopped + case Registering => stop() // spin until registration is completed before stopping } } } @@ -632,10 +632,10 @@ private[akka] object PromiseActorRef { private final case class StoppedWithPath(path: ActorPath) private val ActorStopResult = Failure(ActorKilledException("Stopped")) - private val defaultOnTimeout: String ⇒ Throwable = str ⇒ new AskTimeoutException(str) + private val defaultOnTimeout: String => Throwable = str => new AskTimeoutException(str) def apply(provider: ActorRefProvider, timeout: Timeout, targetName: Any, messageClassName: String, - sender: ActorRef = Actor.noSender, onTimeout: String ⇒ Throwable = defaultOnTimeout): PromiseActorRef = { + sender: ActorRef = Actor.noSender, onTimeout: String => Throwable = defaultOnTimeout): PromiseActorRef = { val result = Promise[Any]() val scheduler = provider.guardian.underlying.system.scheduler val a = new PromiseActorRef(provider, result, messageClassName) @@ -650,7 +650,7 @@ private[akka] object PromiseActorRef { " A typical reason for `AskTimeoutException` is that the recipient actor didn't send a reply.")) } } - result.future onComplete { _ ⇒ try a.stop() finally f.cancel() } + result.future onComplete { _ => try a.stop() finally f.cancel() } a } diff --git a/akka-actor/src/main/scala/akka/pattern/Backoff.scala b/akka-actor/src/main/scala/akka/pattern/Backoff.scala index 0531bc72a5..f82d168d97 100644 --- a/akka-actor/src/main/scala/akka/pattern/Backoff.scala +++ b/akka-actor/src/main/scala/akka/pattern/Backoff.scala @@ -554,7 +554,7 @@ trait BackoffOptions { /** * @see [[BackoffOnStopOptions.withFinalStopMessage()]] */ - def withFinalStopMessage(isFinalStopMessage: Any ⇒ Boolean): BackoffOptions + def withFinalStopMessage(isFinalStopMessage: Any => Boolean): BackoffOptions /** * Returns the props to create the back-off supervisor. @@ -572,7 +572,7 @@ private final case class BackoffOptionsImpl( reset: Option[BackoffReset] = None, supervisorStrategy: OneForOneStrategy = OneForOneStrategy()(SupervisorStrategy.defaultStrategy.decider), replyWhileStopped: Option[Any] = None, - finalStopMessage: Option[Any ⇒ Boolean] = None + finalStopMessage: Option[Any => Boolean] = None ) extends akka.pattern.BackoffOptions { val backoffReset = reset.getOrElse(AutoReset(minBackoff)) @@ -583,24 +583,24 @@ private final case class BackoffOptionsImpl( def withDefaultStoppingStrategy = copy(supervisorStrategy = OneForOneStrategy(supervisorStrategy.maxNrOfRetries)(SupervisorStrategy.stoppingStrategy.decider)) def withReplyWhileStopped(replyWhileStopped: Any) = copy(replyWhileStopped = Some(replyWhileStopped)) def withMaxNrOfRetries(maxNrOfRetries: Int) = copy(supervisorStrategy = supervisorStrategy.withMaxNrOfRetries(maxNrOfRetries)) - def withFinalStopMessage(action: Any ⇒ Boolean) = copy(finalStopMessage = Some(action)) + def withFinalStopMessage(action: Any => Boolean) = copy(finalStopMessage = Some(action)) def props = { require(minBackoff > Duration.Zero, "minBackoff must be > 0") require(maxBackoff >= minBackoff, "maxBackoff must be >= minBackoff") require(0.0 <= randomFactor && randomFactor <= 1.0, "randomFactor must be between 0.0 and 1.0") backoffReset match { - case AutoReset(resetBackoff) ⇒ + case AutoReset(resetBackoff) => require(minBackoff <= resetBackoff && resetBackoff <= maxBackoff) - case _ ⇒ // ignore + case _ => // ignore } backoffType match { //onFailure method in companion object - case RestartImpliesFailure ⇒ + case RestartImpliesFailure => Props(new BackoffOnRestartSupervisor(childProps, childName, minBackoff, maxBackoff, backoffReset, randomFactor, supervisorStrategy, replyWhileStopped)) //onStop method in companion object - case StopImpliesFailure ⇒ + case StopImpliesFailure => Props(new BackoffOnStopSupervisor(childProps, childName, minBackoff, maxBackoff, backoffReset, randomFactor, supervisorStrategy, replyWhileStopped, finalStopMessage)) } } diff --git a/akka-actor/src/main/scala/akka/pattern/BackoffOptions.scala b/akka-actor/src/main/scala/akka/pattern/BackoffOptions.scala index f71f07e526..f237479552 100644 --- a/akka-actor/src/main/scala/akka/pattern/BackoffOptions.scala +++ b/akka-actor/src/main/scala/akka/pattern/BackoffOptions.scala @@ -319,7 +319,7 @@ sealed trait BackoffOnStopOptions extends ExtendedBackoffOptions[BackoffOnStopOp * the supervised actor is running then it will be forwarded to the supervised actor and * when the supervised actor stops its self the supervisor will stop its self. */ - def withFinalStopMessage(isFinalStopMessage: Any ⇒ Boolean): BackoffOnStopOptions + def withFinalStopMessage(isFinalStopMessage: Any => Boolean): BackoffOnStopOptions } @DoNotInherit @@ -334,7 +334,7 @@ private final case class BackoffOnStopOptionsImpl[T]( reset: Option[BackoffReset] = None, supervisorStrategy: OneForOneStrategy = OneForOneStrategy()(SupervisorStrategy.defaultStrategy.decider), replyWhileStopped: Option[Any] = None, - finalStopMessage: Option[Any ⇒ Boolean] = None + finalStopMessage: Option[Any => Boolean] = None ) extends BackoffOnStopOptions { private val backoffReset = reset.getOrElse(AutoReset(minBackoff)) @@ -348,16 +348,16 @@ private final case class BackoffOnStopOptionsImpl[T]( // additional def withDefaultStoppingStrategy = copy(supervisorStrategy = OneForOneStrategy(supervisorStrategy.maxNrOfRetries)(SupervisorStrategy.stoppingStrategy.decider)) - def withFinalStopMessage(action: Any ⇒ Boolean) = copy(finalStopMessage = Some(action)) + def withFinalStopMessage(action: Any => Boolean) = copy(finalStopMessage = Some(action)) def props: Props = { require(minBackoff > Duration.Zero, "minBackoff must be > 0") require(maxBackoff >= minBackoff, "maxBackoff must be >= minBackoff") require(0.0 <= randomFactor && randomFactor <= 1.0, "randomFactor must be between 0.0 and 1.0") backoffReset match { - case AutoReset(resetBackoff) ⇒ + case AutoReset(resetBackoff) => require(minBackoff <= resetBackoff && resetBackoff <= maxBackoff) - case _ ⇒ // ignore + case _ => // ignore } Props(new BackoffOnStopSupervisor(childProps, childName, minBackoff, maxBackoff, backoffReset, randomFactor, supervisorStrategy, replyWhileStopped, finalStopMessage)) @@ -389,9 +389,9 @@ private final case class BackoffOnFailureOptionsImpl[T]( require(maxBackoff >= minBackoff, "maxBackoff must be >= minBackoff") require(0.0 <= randomFactor && randomFactor <= 1.0, "randomFactor must be between 0.0 and 1.0") backoffReset match { - case AutoReset(resetBackoff) ⇒ + case AutoReset(resetBackoff) => require(minBackoff <= resetBackoff && resetBackoff <= maxBackoff) - case _ ⇒ // ignore + case _ => // ignore } Props(new BackoffOnRestartSupervisor(childProps, childName, minBackoff, maxBackoff, backoffReset, randomFactor, supervisorStrategy, replyWhileStopped)) diff --git a/akka-actor/src/main/scala/akka/pattern/BackoffSupervisor.scala b/akka-actor/src/main/scala/akka/pattern/BackoffSupervisor.scala index e691c1a055..be16c27995 100644 --- a/akka-actor/src/main/scala/akka/pattern/BackoffSupervisor.scala +++ b/akka-actor/src/main/scala/akka/pattern/BackoffSupervisor.scala @@ -72,8 +72,8 @@ object BackoffSupervisor { randomFactor: Double, maxNrOfRetries: Int): Props = { val supervisionStrategy = SupervisorStrategy.defaultStrategy match { - case oneForOne: OneForOneStrategy ⇒ oneForOne.withMaxNrOfRetries(maxNrOfRetries) - case s ⇒ s + case oneForOne: OneForOneStrategy => oneForOne.withMaxNrOfRetries(maxNrOfRetries) + case s => s } propsWithSupervisorStrategy(childProps, childName, minBackoff, maxBackoff, randomFactor, supervisionStrategy) } @@ -293,8 +293,8 @@ object BackoffSupervisor { val rnd = 1.0 + ThreadLocalRandom.current().nextDouble() * randomFactor val calculatedDuration = Try(maxBackoff.min(minBackoff * math.pow(2, restartCount)) * rnd).getOrElse(maxBackoff) calculatedDuration match { - case f: FiniteDuration ⇒ f - case _ ⇒ maxBackoff + case f: FiniteDuration => f + case _ => maxBackoff } } } @@ -310,7 +310,7 @@ final class BackoffSupervisor( randomFactor: Double, strategy: SupervisorStrategy, val replyWhileStopped: Option[Any], - val finalStopMessage: Option[Any ⇒ Boolean]) + val finalStopMessage: Option[Any => Boolean]) extends BackoffOnStopSupervisor(childProps, childName, minBackoff, maxBackoff, reset, randomFactor, strategy, replyWhileStopped, finalStopMessage) { // for binary compatibility with 2.5.18 diff --git a/akka-actor/src/main/scala/akka/pattern/CircuitBreaker.scala b/akka-actor/src/main/scala/akka/pattern/CircuitBreaker.scala index 53f16c2e9a..cc016bfec6 100644 --- a/akka-actor/src/main/scala/akka/pattern/CircuitBreaker.scala +++ b/akka-actor/src/main/scala/akka/pattern/CircuitBreaker.scala @@ -77,9 +77,9 @@ object CircuitBreaker { def create(scheduler: Scheduler, maxFailures: Int, callTimeout: java.time.Duration, resetTimeout: java.time.Duration): CircuitBreaker = apply(scheduler, maxFailures, callTimeout.asScala, resetTimeout.asScala) - private val exceptionAsFailure: Try[_] ⇒ Boolean = { - case _: Success[_] ⇒ false - case _ ⇒ true + private val exceptionAsFailure: Try[_] => Boolean = { + case _: Success[_] => false + case _ => true } private def exceptionAsFailureJava[T]: BiFunction[Optional[T], Optional[Throwable], java.lang.Boolean] = @@ -92,10 +92,10 @@ object CircuitBreaker { } } - protected def convertJavaFailureFnToScala[T](javaFn: BiFunction[Optional[T], Optional[Throwable], java.lang.Boolean]): Try[T] ⇒ Boolean = { - val failureFnInScala: Try[T] ⇒ Boolean = { - case Success(t) ⇒ javaFn(Optional.of(t), Optional.empty()) - case Failure(err) ⇒ javaFn(Optional.empty(), Optional.of(err)) + protected def convertJavaFailureFnToScala[T](javaFn: BiFunction[Optional[T], Optional[Throwable], java.lang.Boolean]): Try[T] => Boolean = { + val failureFnInScala: Try[T] => Boolean = { + case Success(t) => javaFn(Optional.of(t), Optional.empty()) + case Failure(err) => javaFn(Optional.empty(), Optional.of(err)) } failureFnInScala } @@ -218,7 +218,7 @@ class CircuitBreaker( * @return [[scala.concurrent.Future]] containing the call result or a * `scala.concurrent.TimeoutException` if the call timed out */ - def withCircuitBreaker[T](body: ⇒ Future[T], defineFailureFn: Try[T] ⇒ Boolean): Future[T] = + def withCircuitBreaker[T](body: => Future[T], defineFailureFn: Try[T] => Boolean): Future[T] = currentState.invoke(body, defineFailureFn) /** @@ -229,7 +229,7 @@ class CircuitBreaker( * `scala.concurrent.TimeoutException` if the call timed out * */ - def withCircuitBreaker[T](body: ⇒ Future[T]): Future[T] = currentState.invoke(body, CircuitBreaker.exceptionAsFailure) + def withCircuitBreaker[T](body: => Future[T]): Future[T] = currentState.invoke(body, CircuitBreaker.exceptionAsFailure) /** * Java API for [[#withCircuitBreaker]] @@ -292,7 +292,7 @@ class CircuitBreaker( * @param body Call needing protected * @return The result of the call */ - def withSyncCircuitBreaker[T](body: ⇒ T): T = + def withSyncCircuitBreaker[T](body: => T): T = withSyncCircuitBreaker(body, CircuitBreaker.exceptionAsFailure) /** @@ -308,10 +308,10 @@ class CircuitBreaker( * @param defineFailureFn function that define what should be consider failure and thus increase failure count * @return The result of the call */ - def withSyncCircuitBreaker[T](body: ⇒ T, defineFailureFn: Try[T] ⇒ Boolean): T = + def withSyncCircuitBreaker[T](body: => T, defineFailureFn: Try[T] => Boolean): T = Await.result( withCircuitBreaker( - try Future.successful(body) catch { case NonFatal(t) ⇒ Future.failed(t) }, + try Future.successful(body) catch { case NonFatal(t) => Future.failed(t) }, defineFailureFn), callTimeout) @@ -392,7 +392,7 @@ class CircuitBreaker( * @param callback Handler to be invoked on state change * @return CircuitBreaker for fluent usage */ - def onOpen(callback: ⇒ Unit): CircuitBreaker = addOnOpenListener(new Runnable { def run = callback }) + def onOpen(callback: => Unit): CircuitBreaker = addOnOpenListener(new Runnable { def run = callback }) /** * Java API for onOpen @@ -421,7 +421,7 @@ class CircuitBreaker( * @param callback Handler to be invoked on state change * @return CircuitBreaker for fluent usage */ - def onHalfOpen(callback: ⇒ Unit): CircuitBreaker = addOnHalfOpenListener(new Runnable { def run = callback }) + def onHalfOpen(callback: => Unit): CircuitBreaker = addOnHalfOpenListener(new Runnable { def run = callback }) /** * JavaAPI for onHalfOpen @@ -451,7 +451,7 @@ class CircuitBreaker( * @param callback Handler to be invoked on state change * @return CircuitBreaker for fluent usage */ - def onClose(callback: ⇒ Unit): CircuitBreaker = addOnCloseListener(new Runnable { def run = callback }) + def onClose(callback: => Unit): CircuitBreaker = addOnCloseListener(new Runnable { def run = callback }) /** * JavaAPI for onClose @@ -481,7 +481,7 @@ class CircuitBreaker( * @param callback Handler to be invoked on successful call, where passed value is elapsed time in nanoseconds. * @return CircuitBreaker for fluent usage */ - def onCallSuccess(callback: Long ⇒ Unit): CircuitBreaker = addOnCallSuccessListener(new Consumer[Long] { + def onCallSuccess(callback: Long => Unit): CircuitBreaker = addOnCallSuccessListener(new Consumer[Long] { def accept(result: Long): Unit = callback(result) }) @@ -504,7 +504,7 @@ class CircuitBreaker( * @param callback Handler to be invoked on failed call, where passed value is elapsed time in nanoseconds. * @return CircuitBreaker for fluent usage */ - def onCallFailure(callback: Long ⇒ Unit): CircuitBreaker = addOnCallFailureListener(new Consumer[Long] { + def onCallFailure(callback: Long => Unit): CircuitBreaker = addOnCallFailureListener(new Consumer[Long] { def accept(result: Long): Unit = callback(result) }) @@ -527,7 +527,7 @@ class CircuitBreaker( * @param callback Handler to be invoked on call finished with timeout, where passed value is elapsed time in nanoseconds. * @return CircuitBreaker for fluent usage */ - def onCallTimeout(callback: Long ⇒ Unit): CircuitBreaker = addOnCallTimeoutListener(new Consumer[Long] { + def onCallTimeout(callback: Long => Unit): CircuitBreaker = addOnCallTimeoutListener(new Consumer[Long] { def accept(result: Long): Unit = callback(result) }) @@ -550,7 +550,7 @@ class CircuitBreaker( * @param callback Handler to be invoked on call failed due to open breaker. * @return CircuitBreaker for fluent usage */ - def onCallBreakerOpen(callback: ⇒ Unit): CircuitBreaker = addOnCallBreakerOpenListener(new Runnable { def run = callback }) + def onCallBreakerOpen(callback: => Unit): CircuitBreaker = addOnCallBreakerOpenListener(new Runnable { def run = callback }) /** * JavaAPI for onCallBreakerOpen. @@ -713,19 +713,19 @@ class CircuitBreaker( * @param defineFailureFn function that define what should be consider failure and thus increase failure count * @return Future containing the result of the call */ - def callThrough[T](body: ⇒ Future[T], defineFailureFn: Try[T] ⇒ Boolean): Future[T] = { + def callThrough[T](body: => Future[T], defineFailureFn: Try[T] => Boolean): Future[T] = { - def materialize[U](value: ⇒ Future[U]): Future[U] = try value catch { case NonFatal(t) ⇒ Future.failed(t) } + def materialize[U](value: => Future[U]): Future[U] = try value catch { case NonFatal(t) => Future.failed(t) } if (callTimeout == Duration.Zero) { val start = System.nanoTime() val f = materialize(body) f.onComplete { - case _: Success[_] ⇒ + case _: Success[_] => notifyCallSuccessListeners(start) callSucceeds() - case Failure(_) ⇒ + case Failure(_) => notifyCallFailureListeners(start) callFails() } @@ -737,7 +737,7 @@ class CircuitBreaker( implicit val ec = sameThreadExecutionContext - p.future.onComplete { fResult ⇒ + p.future.onComplete { fResult => if (defineFailureFn(fResult)) { callFails() } else { @@ -753,10 +753,10 @@ class CircuitBreaker( } materialize(body).onComplete { - case Success(result) ⇒ + case Success(result) => p.trySuccess(result) timeout.cancel - case Failure(ex) ⇒ + case Failure(ex) => if (p.tryFailure(ex)) { notifyCallFailureListeners(start) } @@ -773,7 +773,7 @@ class CircuitBreaker( * @param body Implementation of the call * @return Future containing the result of the call */ - def callThrough[T](body: ⇒ Future[T]): Future[T] = callThrough(body, CircuitBreaker.exceptionAsFailure) + def callThrough[T](body: => Future[T]): Future[T] = callThrough(body, CircuitBreaker.exceptionAsFailure) /** * Abstract entry point for all states @@ -782,7 +782,7 @@ class CircuitBreaker( * @param defineFailureFn function that define what should be consider failure and thus increase failure count * @return Future containing result of protected call */ - def invoke[T](body: ⇒ Future[T], defineFailureFn: Try[T] ⇒ Boolean): Future[T] + def invoke[T](body: => Future[T], defineFailureFn: Try[T] => Boolean): Future[T] /** * Abstract entry point for all states @@ -790,7 +790,7 @@ class CircuitBreaker( * @param body Implementation of the call that needs protected * @return Future containing result of protected call */ - def invoke[T](body: ⇒ Future[T]): Future[T] = invoke(body, CircuitBreaker.exceptionAsFailure) + def invoke[T](body: => Future[T]): Future[T] = invoke(body, CircuitBreaker.exceptionAsFailure) /** * Invoked when call succeeds @@ -832,7 +832,7 @@ class CircuitBreaker( * @param body Implementation of the call that needs protected * @return Future containing result of protected call */ - override def invoke[T](body: ⇒ Future[T], defineFailureFn: Try[T] ⇒ Boolean): Future[T] = + override def invoke[T](body: => Future[T], defineFailureFn: Try[T] => Boolean): Future[T] = callThrough(body, defineFailureFn) /** @@ -880,7 +880,7 @@ class CircuitBreaker( * @param body Implementation of the call that needs protected * @return Future containing result of protected call */ - override def invoke[T](body: ⇒ Future[T], defineFailureFn: Try[T] ⇒ Boolean): Future[T] = + override def invoke[T](body: => Future[T], defineFailureFn: Try[T] => Boolean): Future[T] = if (compareAndSet(true, false)) callThrough(body, defineFailureFn) else { @@ -928,7 +928,7 @@ class CircuitBreaker( * @param body Implementation of the call that needs protected * @return Future containing result of protected call */ - override def invoke[T](body: ⇒ Future[T], defineFailureFn: Try[T] ⇒ Boolean): Future[T] = { + override def invoke[T](body: => Future[T], defineFailureFn: Try[T] => Boolean): Future[T] = { notifyCallBreakerOpenListeners() Future.failed(new CircuitBreakerOpenException(remainingDuration())) } @@ -971,8 +971,8 @@ class CircuitBreaker( attemptReset() } val nextResetTimeout = currentResetTimeout * exponentialBackoffFactor match { - case f: FiniteDuration ⇒ f - case _ ⇒ currentResetTimeout + case f: FiniteDuration => f + case _ => currentResetTimeout } if (nextResetTimeout < maxResetTimeout) diff --git a/akka-actor/src/main/scala/akka/pattern/FutureTimeoutSupport.scala b/akka-actor/src/main/scala/akka/pattern/FutureTimeoutSupport.scala index 4661466727..99b7c003fa 100644 --- a/akka-actor/src/main/scala/akka/pattern/FutureTimeoutSupport.scala +++ b/akka-actor/src/main/scala/akka/pattern/FutureTimeoutSupport.scala @@ -18,12 +18,12 @@ trait FutureTimeoutSupport { * Returns a [[scala.concurrent.Future]] that will be completed with the success or failure of the provided value * after the specified duration. */ - def after[T](duration: FiniteDuration, using: Scheduler)(value: ⇒ Future[T])(implicit ec: ExecutionContext): Future[T] = + def after[T](duration: FiniteDuration, using: Scheduler)(value: => Future[T])(implicit ec: ExecutionContext): Future[T] = if (duration.isFinite && duration.length < 1) { - try value catch { case NonFatal(t) ⇒ Future.failed(t) } + try value catch { case NonFatal(t) => Future.failed(t) } } else { val p = Promise[T]() - using.scheduleOnce(duration) { p completeWith { try value catch { case NonFatal(t) ⇒ Future.failed(t) } } } + using.scheduleOnce(duration) { p completeWith { try value catch { case NonFatal(t) => Future.failed(t) } } } p.future } @@ -31,9 +31,9 @@ trait FutureTimeoutSupport { * Returns a [[java.util.concurrent.CompletionStage]] that will be completed with the success or failure of the provided value * after the specified duration. */ - def afterCompletionStage[T](duration: FiniteDuration, using: Scheduler)(value: ⇒ CompletionStage[T])(implicit ec: ExecutionContext): CompletionStage[T] = + def afterCompletionStage[T](duration: FiniteDuration, using: Scheduler)(value: => CompletionStage[T])(implicit ec: ExecutionContext): CompletionStage[T] = if (duration.isFinite && duration.length < 1) { - try value catch { case NonFatal(t) ⇒ Futures.failedCompletionStage(t) } + try value catch { case NonFatal(t) => Futures.failedCompletionStage(t) } } else { val p = new CompletableFuture[T] using.scheduleOnce(duration) { @@ -46,7 +46,7 @@ trait FutureTimeoutSupport { } }) } catch { - case NonFatal(ex) ⇒ p.completeExceptionally(ex) + case NonFatal(ex) => p.completeExceptionally(ex) } } p diff --git a/akka-actor/src/main/scala/akka/pattern/GracefulStopSupport.scala b/akka-actor/src/main/scala/akka/pattern/GracefulStopSupport.scala index 9b2e666d6d..082f687e64 100644 --- a/akka-actor/src/main/scala/akka/pattern/GracefulStopSupport.scala +++ b/akka-actor/src/main/scala/akka/pattern/GracefulStopSupport.scala @@ -50,9 +50,9 @@ trait GracefulStopSupport { target.tell(stopMessage, Actor.noSender) ref.result.future.transform( { - case Terminated(t) if t.path == target.path ⇒ true - case _ ⇒ { internalTarget.sendSystemMessage(Unwatch(target, ref)); false } + case Terminated(t) if t.path == target.path => true + case _ => { internalTarget.sendSystemMessage(Unwatch(target, ref)); false } }, - t ⇒ { internalTarget.sendSystemMessage(Unwatch(target, ref)); t })(ref.internalCallingThreadExecutionContext) + t => { internalTarget.sendSystemMessage(Unwatch(target, ref)); t })(ref.internalCallingThreadExecutionContext) } } diff --git a/akka-actor/src/main/scala/akka/pattern/HandleBackoff.scala b/akka-actor/src/main/scala/akka/pattern/HandleBackoff.scala index 82e414a92b..86817a2d90 100644 --- a/akka-actor/src/main/scala/akka/pattern/HandleBackoff.scala +++ b/akka-actor/src/main/scala/akka/pattern/HandleBackoff.scala @@ -14,7 +14,7 @@ import akka.pattern.internal.{ BackoffOnRestartSupervisor, BackoffOnStopSupervis * Implements basic backoff handling for [[BackoffOnRestartSupervisor]] and [[BackoffOnStopSupervisor]]. */ @InternalApi private[akka] trait HandleBackoff { - this: Actor ⇒ + this: Actor => def childProps: Props def childName: String def reset: BackoffReset @@ -34,36 +34,36 @@ import akka.pattern.internal.{ BackoffOnRestartSupervisor, BackoffOnStopSupervis } def handleBackoff: Actor.Receive = { - case StartChild ⇒ + case StartChild => startChild() reset match { - case AutoReset(resetBackoff) ⇒ + case AutoReset(resetBackoff) => context.system.scheduler.scheduleOnce(resetBackoff, self, ResetRestartCount(restartCount)) - case _ ⇒ // ignore + case _ => // ignore } - case Reset ⇒ + case Reset => reset match { - case ManualReset ⇒ restartCount = 0 - case msg ⇒ unhandled(msg) + case ManualReset => restartCount = 0 + case msg => unhandled(msg) } - case ResetRestartCount(current) ⇒ + case ResetRestartCount(current) => if (current == restartCount) { restartCount = 0 } - case GetRestartCount ⇒ + case GetRestartCount => sender() ! RestartCount(restartCount) - case GetCurrentChild ⇒ + case GetCurrentChild => sender() ! CurrentChild(child) - case msg if child.contains(sender()) ⇒ + case msg if child.contains(sender()) => // use the BackoffSupervisor as sender context.parent ! msg - case msg ⇒ + case msg => handleMessageToChild(msg) } } diff --git a/akka-actor/src/main/scala/akka/pattern/Patterns.scala b/akka-actor/src/main/scala/akka/pattern/Patterns.scala index d29edfbbff..dc1ca06420 100644 --- a/akka-actor/src/main/scala/akka/pattern/Patterns.scala +++ b/akka-actor/src/main/scala/akka/pattern/Patterns.scala @@ -19,11 +19,11 @@ object Patterns { import akka.actor.ActorRef import akka.japi import akka.pattern.{ - after ⇒ scalaAfter, - ask ⇒ scalaAsk, - gracefulStop ⇒ scalaGracefulStop, - pipe ⇒ scalaPipe, - retry ⇒ scalaRetry + after => scalaAfter, + ask => scalaAsk, + gracefulStop => scalaGracefulStop, + pipe => scalaPipe, + retry => scalaRetry } import akka.util.Timeout @@ -433,7 +433,7 @@ object Patterns { */ def retry[T](attempt: Callable[Future[T]], attempts: Int, delay: FiniteDuration, scheduler: Scheduler, context: ExecutionContext): Future[T] = - scalaRetry(() ⇒ attempt.call, attempts, delay)(context, scheduler) + scalaRetry(() => attempt.call, attempts, delay)(context, scheduler) /** * Returns an internally retrying [[java.util.concurrent.CompletionStage]] @@ -444,7 +444,7 @@ object Patterns { * and therefore must be thread safe (not touch unsafe mutable state). */ def retry[T](attempt: Callable[CompletionStage[T]], attempts: Int, delay: java.time.Duration, scheduler: Scheduler, ec: ExecutionContext): CompletionStage[T] = - scalaRetry(() ⇒ attempt.call().toScala, attempts, delay.asScala)(ec, scheduler).toJava + scalaRetry(() => attempt.call().toScala, attempts, delay.asScala)(ec, scheduler).toJava } /** @@ -456,7 +456,7 @@ object Patterns { object PatternsCS { import akka.actor.ActorRef import akka.japi - import akka.pattern.{ ask ⇒ scalaAsk, gracefulStop ⇒ scalaGracefulStop, retry ⇒ scalaRetry } + import akka.pattern.{ ask => scalaAsk, gracefulStop => scalaGracefulStop, retry => scalaRetry } import akka.util.Timeout import scala.concurrent.duration._ @@ -843,5 +843,5 @@ object PatternsCS { */ @deprecated("Use Patterns.retry instead.", since = "2.5.19") def retry[T](attempt: Callable[CompletionStage[T]], attempts: Int, delay: java.time.Duration, scheduler: Scheduler, ec: ExecutionContext): CompletionStage[T] = - scalaRetry(() ⇒ attempt.call().toScala, attempts, delay.asScala)(ec, scheduler).toJava + scalaRetry(() => attempt.call().toScala, attempts, delay.asScala)(ec, scheduler).toJava } diff --git a/akka-actor/src/main/scala/akka/pattern/PipeToSupport.scala b/akka-actor/src/main/scala/akka/pattern/PipeToSupport.scala index 326202611d..13bb2ee3ed 100644 --- a/akka-actor/src/main/scala/akka/pattern/PipeToSupport.scala +++ b/akka-actor/src/main/scala/akka/pattern/PipeToSupport.scala @@ -19,14 +19,14 @@ trait PipeToSupport { final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) { def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = { future andThen { - case Success(r) ⇒ recipient ! r - case Failure(f) ⇒ recipient ! Status.Failure(f) + case Success(r) => recipient ! r + case Failure(f) => recipient ! Status.Failure(f) } } def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = { future andThen { - case Success(r) ⇒ recipient ! r - case Failure(f) ⇒ recipient ! Status.Failure(f) + case Success(r) => recipient ! r + case Failure(f) => recipient ! Status.Failure(f) } } def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender) diff --git a/akka-actor/src/main/scala/akka/pattern/PromiseRef.scala b/akka-actor/src/main/scala/akka/pattern/PromiseRef.scala index 35ff6f3b85..2eb1b04bbe 100644 --- a/akka-actor/src/main/scala/akka/pattern/PromiseRef.scala +++ b/akka-actor/src/main/scala/akka/pattern/PromiseRef.scala @@ -29,7 +29,7 @@ trait FutureRef[T] { * A combination of a Promise and an ActorRef associated with it, which points * to an actor performing a task which will eventually resolve the Promise. */ -trait PromiseRef[T] { this: FutureRef[T] ⇒ +trait PromiseRef[T] { this: FutureRef[T] => /** * ActorRef associated with this PromiseRef. */ diff --git a/akka-actor/src/main/scala/akka/pattern/RetrySupport.scala b/akka-actor/src/main/scala/akka/pattern/RetrySupport.scala index 2cf059a3e7..690cade024 100644 --- a/akka-actor/src/main/scala/akka/pattern/RetrySupport.scala +++ b/akka-actor/src/main/scala/akka/pattern/RetrySupport.scala @@ -35,11 +35,11 @@ trait RetrySupport { * ) * }}} */ - def retry[T](attempt: () ⇒ Future[T], attempts: Int, delay: FiniteDuration)(implicit ec: ExecutionContext, scheduler: Scheduler): Future[T] = { + def retry[T](attempt: () => Future[T], attempts: Int, delay: FiniteDuration)(implicit ec: ExecutionContext, scheduler: Scheduler): Future[T] = { try { if (attempts > 0) { attempt() recoverWith { - case NonFatal(_) ⇒ after(delay, scheduler) { + case NonFatal(_) => after(delay, scheduler) { retry(attempt, attempts - 1, delay) } } @@ -47,7 +47,7 @@ trait RetrySupport { attempt() } } catch { - case NonFatal(error) ⇒ Future.failed(error) + case NonFatal(error) => Future.failed(error) } } } diff --git a/akka-actor/src/main/scala/akka/pattern/internal/BackoffOnRestartSupervisor.scala b/akka-actor/src/main/scala/akka/pattern/internal/BackoffOnRestartSupervisor.scala index 38e455a34a..75283c899b 100644 --- a/akka-actor/src/main/scala/akka/pattern/internal/BackoffOnRestartSupervisor.scala +++ b/akka-actor/src/main/scala/akka/pattern/internal/BackoffOnRestartSupervisor.scala @@ -34,15 +34,15 @@ import scala.concurrent.duration._ import context._ override val supervisorStrategy = OneForOneStrategy(strategy.maxNrOfRetries, strategy.withinTimeRange, strategy.loggingEnabled) { - case ex ⇒ + case ex => val defaultDirective: Directive = - super.supervisorStrategy.decider.applyOrElse(ex, (_: Any) ⇒ Escalate) + super.supervisorStrategy.decider.applyOrElse(ex, (_: Any) => Escalate) - strategy.decider.applyOrElse(ex, (_: Any) ⇒ defaultDirective) match { + strategy.decider.applyOrElse(ex, (_: Any) => defaultDirective) match { // Whatever the final Directive is, we will translate all Restarts // to our own Restarts, which involves stopping the child. - case Restart ⇒ + case Restart => if (strategy.withinTimeRange.isFinite && restartCount == 0) { // If the user has defined a time range for the maxNrOfRetries, we'll schedule a message // to ourselves every time that range elapses, to reset the restart counter. We hide it @@ -62,23 +62,23 @@ import scala.concurrent.duration._ } Stop - case other ⇒ other + case other => other } } def waitChildTerminatedBeforeBackoff(childRef: ActorRef): Receive = { - case Terminated(`childRef`) ⇒ + case Terminated(`childRef`) => become(receive) child = None val restartDelay = BackoffSupervisor.calculateDelay(restartCount, minBackoff, maxBackoff, randomFactor) context.system.scheduler.scheduleOnce(restartDelay, self, BackoffSupervisor.StartChild) restartCount += 1 - case StartChild ⇒ // Ignore it, we will schedule a new one once current child terminated. + case StartChild => // Ignore it, we will schedule a new one once current child terminated. } def onTerminated: Receive = { - case Terminated(c) ⇒ + case Terminated(c) => log.debug(s"Terminating, because child [$c] terminated itself") stop(self) } @@ -86,12 +86,12 @@ import scala.concurrent.duration._ def receive: Receive = onTerminated orElse handleBackoff protected def handleMessageToChild(msg: Any): Unit = child match { - case Some(c) ⇒ + case Some(c) => c.forward(msg) - case None ⇒ + case None => replyWhileStopped match { - case None ⇒ context.system.deadLetters.forward(msg) - case Some(r) ⇒ sender() ! r + case None => context.system.deadLetters.forward(msg) + case Some(r) => sender() ! r } } } diff --git a/akka-actor/src/main/scala/akka/pattern/internal/BackoffOnStopSupervisor.scala b/akka-actor/src/main/scala/akka/pattern/internal/BackoffOnStopSupervisor.scala index 10cbaceed3..5f59abfe5f 100644 --- a/akka-actor/src/main/scala/akka/pattern/internal/BackoffOnStopSupervisor.scala +++ b/akka-actor/src/main/scala/akka/pattern/internal/BackoffOnStopSupervisor.scala @@ -27,7 +27,7 @@ import scala.concurrent.duration.FiniteDuration randomFactor: Double, strategy: SupervisorStrategy, replyWhileStopped: Option[Any], - finalStopMessage: Option[Any ⇒ Boolean]) + finalStopMessage: Option[Any => Boolean]) extends Actor with HandleBackoff with ActorLogging { @@ -35,26 +35,26 @@ import scala.concurrent.duration.FiniteDuration import context.dispatcher override val supervisorStrategy = strategy match { - case oneForOne: OneForOneStrategy ⇒ + case oneForOne: OneForOneStrategy => OneForOneStrategy(oneForOne.maxNrOfRetries, oneForOne.withinTimeRange, oneForOne.loggingEnabled) { - case ex ⇒ + case ex => val defaultDirective: Directive = - super.supervisorStrategy.decider.applyOrElse(ex, (_: Any) ⇒ Escalate) + super.supervisorStrategy.decider.applyOrElse(ex, (_: Any) => Escalate) - strategy.decider.applyOrElse(ex, (_: Any) ⇒ defaultDirective) + strategy.decider.applyOrElse(ex, (_: Any) => defaultDirective) } - case s ⇒ s + case s => s } def onTerminated: Receive = { - case Terminated(ref) if child.contains(ref) ⇒ + case Terminated(ref) if child.contains(ref) => child = None if (finalStopMessageReceived) { context.stop(self) } else { val maxNrOfRetries = strategy match { - case oneForOne: OneForOneStrategy ⇒ oneForOne.maxNrOfRetries - case _ ⇒ -1 + case oneForOne: OneForOneStrategy => oneForOne.maxNrOfRetries + case _ => -1 } val nextRestartCount = restartCount + 1 @@ -74,20 +74,20 @@ import scala.concurrent.duration.FiniteDuration def receive: Receive = onTerminated orElse handleBackoff protected def handleMessageToChild(msg: Any): Unit = child match { - case Some(c) ⇒ + case Some(c) => c.forward(msg) if (!finalStopMessageReceived) finalStopMessage match { - case Some(fsm) ⇒ finalStopMessageReceived = fsm(msg) - case None ⇒ + case Some(fsm) => finalStopMessageReceived = fsm(msg) + case None => } - case None ⇒ + case None => replyWhileStopped match { - case Some(r) ⇒ sender() ! r - case None ⇒ context.system.deadLetters.forward(msg) + case Some(r) => sender() ! r + case None => context.system.deadLetters.forward(msg) } finalStopMessage match { - case Some(fsm) if fsm(msg) ⇒ context.stop(self) - case _ ⇒ + case Some(fsm) if fsm(msg) => context.stop(self) + case _ => } } } diff --git a/akka-actor/src/main/scala/akka/routing/Balancing.scala b/akka-actor/src/main/scala/akka/routing/Balancing.scala index 4b57b204c4..cab477b4dc 100644 --- a/akka-actor/src/main/scala/akka/routing/Balancing.scala +++ b/akka-actor/src/main/scala/akka/routing/Balancing.scala @@ -102,7 +102,7 @@ final case class BalancingPool( override private[akka] def newRoutee(routeeProps: Props, context: ActorContext): Routee = { val rawDeployPath = context.self.path.elements.drop(1).mkString("/", "/", "") - val deployPath = BalancingPoolDeploy.invalidConfigKeyChars.foldLeft(rawDeployPath) { (replaced, c) ⇒ + val deployPath = BalancingPoolDeploy.invalidConfigKeyChars.foldLeft(rawDeployPath) { (replaced, c) => replaced.replace(c, '_') } val dispatcherId = s"BalancingPool-$deployPath" @@ -137,13 +137,13 @@ final case class BalancingPool( else { other match { - case p: Pool ⇒ + case p: Pool => if ((this.supervisorStrategy eq Pool.defaultSupervisorStrategy) && (p.supervisorStrategy ne Pool.defaultSupervisorStrategy)) this.withSupervisorStrategy(p.supervisorStrategy) else this - case _ ⇒ this + case _ => this } } diff --git a/akka-actor/src/main/scala/akka/routing/ConsistentHash.scala b/akka-actor/src/main/scala/akka/routing/ConsistentHash.scala index 7e7680dddc..805bd5ed4e 100644 --- a/akka-actor/src/main/scala/akka/routing/ConsistentHash.scala +++ b/akka-actor/src/main/scala/akka/routing/ConsistentHash.scala @@ -40,7 +40,7 @@ class ConsistentHash[T: ClassTag] private (nodes: immutable.SortedMap[Int, T], v def :+(node: T): ConsistentHash[T] = { val nodeHash = hashFor(node.toString) new ConsistentHash( - nodes ++ ((1 to virtualNodesFactor) map { r ⇒ (concatenateNodeHash(nodeHash, r) → node) }), + nodes ++ ((1 to virtualNodesFactor) map { r => (concatenateNodeHash(nodeHash, r) -> node) }), virtualNodesFactor) } @@ -59,7 +59,7 @@ class ConsistentHash[T: ClassTag] private (nodes: immutable.SortedMap[Int, T], v def :-(node: T): ConsistentHash[T] = { val nodeHash = hashFor(node.toString) new ConsistentHash( - nodes -- ((1 to virtualNodesFactor) map { r ⇒ concatenateNodeHash(nodeHash, r) }), + nodes -- ((1 to virtualNodesFactor) map { r => concatenateNodeHash(nodeHash, r) }), virtualNodesFactor) } @@ -115,10 +115,10 @@ object ConsistentHash { new ConsistentHash( immutable.SortedMap.empty[Int, T] ++ (for { - node ← nodes + node <- nodes nodeHash = hashFor(node.toString) - vnode ← 1 to virtualNodesFactor - } yield (concatenateNodeHash(nodeHash, vnode) → node)), + vnode <- 1 to virtualNodesFactor + } yield (concatenateNodeHash(nodeHash, vnode) -> node)), virtualNodesFactor) } diff --git a/akka-actor/src/main/scala/akka/routing/ConsistentHashing.scala b/akka-actor/src/main/scala/akka/routing/ConsistentHashing.scala index 6bbf5cdb9e..529c597dfe 100644 --- a/akka-actor/src/main/scala/akka/routing/ConsistentHashing.scala +++ b/akka-actor/src/main/scala/akka/routing/ConsistentHashing.scala @@ -92,7 +92,7 @@ object ConsistentHashingRouter { * INTERNAL API */ private[akka] def hashMappingAdapter(mapper: ConsistentHashMapper): ConsistentHashMapping = { - case message if mapper.hashKey(message).asInstanceOf[AnyRef] ne null ⇒ + case message if mapper.hashKey(message).asInstanceOf[AnyRef] ne null => mapper.hashKey(message) } @@ -206,20 +206,20 @@ final case class ConsistentHashingRoutingLogic( val currentConsistenHash = updateConsistentHash() if (currentConsistenHash.isEmpty) NoRoutee else hashData match { - case bytes: Array[Byte] ⇒ currentConsistenHash.nodeFor(bytes).routee - case str: String ⇒ currentConsistenHash.nodeFor(str).routee - case x: AnyRef ⇒ currentConsistenHash.nodeFor(SerializationExtension(system).serialize(x).get).routee + case bytes: Array[Byte] => currentConsistenHash.nodeFor(bytes).routee + case str: String => currentConsistenHash.nodeFor(str).routee + case x: AnyRef => currentConsistenHash.nodeFor(SerializationExtension(system).serialize(x).get).routee } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning("Couldn't route message with consistent hash key [{}] due to [{}]", hashData, e.getMessage) NoRoutee } message match { - case _ if hashMapping.isDefinedAt(message) ⇒ target(hashMapping(message)) - case hashable: ConsistentHashable ⇒ target(hashable.consistentHashKey) - case _ ⇒ + case _ if hashMapping.isDefinedAt(message) => target(hashMapping(message)) + case hashable: ConsistentHashable => target(hashable.consistentHashKey) + case _ => log.warning( "Message [{}] must be handled by hashMapping, or implement [{}] or be wrapped in [{}]", message.getClass.getName, classOf[ConsistentHashable].getName, @@ -328,9 +328,9 @@ final case class ConsistentHashingPool( * Uses the `hashMapping` defined in code, since that can't be defined in configuration. */ override def withFallback(other: RouterConfig): RouterConfig = other match { - case _: FromConfig | _: NoRouter ⇒ this.overrideUnsetConfig(other) - case otherRouter: ConsistentHashingPool ⇒ (copy(hashMapping = otherRouter.hashMapping)).overrideUnsetConfig(other) - case _ ⇒ throw new IllegalArgumentException("Expected ConsistentHashingPool, got [%s]".format(other)) + case _: FromConfig | _: NoRouter => this.overrideUnsetConfig(other) + case otherRouter: ConsistentHashingPool => (copy(hashMapping = otherRouter.hashMapping)).overrideUnsetConfig(other) + case _ => throw new IllegalArgumentException("Expected ConsistentHashingPool, got [%s]".format(other)) } } @@ -398,9 +398,9 @@ final case class ConsistentHashingGroup( * Uses the `hashMapping` defined in code, since that can't be defined in configuration. */ override def withFallback(other: RouterConfig): RouterConfig = other match { - case _: FromConfig | _: NoRouter ⇒ super.withFallback(other) - case otherRouter: ConsistentHashingGroup ⇒ copy(hashMapping = otherRouter.hashMapping) - case _ ⇒ throw new IllegalArgumentException("Expected ConsistentHashingGroup, got [%s]".format(other)) + case _: FromConfig | _: NoRouter => super.withFallback(other) + case otherRouter: ConsistentHashingGroup => copy(hashMapping = otherRouter.hashMapping) + case _ => throw new IllegalArgumentException("Expected ConsistentHashingGroup, got [%s]".format(other)) } } @@ -416,15 +416,15 @@ final case class ConsistentHashingGroup( private[akka] final case class ConsistentRoutee(routee: Routee, selfAddress: Address) { override def toString: String = routee match { - case ActorRefRoutee(ref) ⇒ toStringWithfullAddress(ref.path) - case ActorSelectionRoutee(sel) ⇒ toStringWithfullAddress(sel.anchorPath) + sel.pathString - case other ⇒ other.toString + case ActorRefRoutee(ref) => toStringWithfullAddress(ref.path) + case ActorSelectionRoutee(sel) => toStringWithfullAddress(sel.anchorPath) + sel.pathString + case other => other.toString } private def toStringWithfullAddress(path: ActorPath): String = { path.address match { - case Address(_, _, None, None) ⇒ path.toStringWithAddress(selfAddress) - case _ ⇒ path.toString + case Address(_, _, None, None) => path.toStringWithAddress(selfAddress) + case _ => path.toString } } } diff --git a/akka-actor/src/main/scala/akka/routing/Listeners.scala b/akka-actor/src/main/scala/akka/routing/Listeners.scala index c8ca17b118..60374838c0 100644 --- a/akka-actor/src/main/scala/akka/routing/Listeners.scala +++ b/akka-actor/src/main/scala/akka/routing/Listeners.scala @@ -10,7 +10,7 @@ import java.util.{ Set, TreeSet } sealed trait ListenerMessage final case class Listen(listener: ActorRef) extends ListenerMessage final case class Deafen(listener: ActorRef) extends ListenerMessage -final case class WithListeners(f: (ActorRef) ⇒ Unit) extends ListenerMessage +final case class WithListeners(f: (ActorRef) => Unit) extends ListenerMessage /** * Listeners is a generic trait to implement listening capability on an Actor. @@ -23,7 +23,7 @@ final case class WithListeners(f: (ActorRef) ⇒ Unit) extends ListenerMessage *

* Send WithListeners(fun) to traverse the current listeners. */ -trait Listeners { self: Actor ⇒ +trait Listeners { self: Actor => protected val listeners: Set[ActorRef] = new TreeSet[ActorRef] /** @@ -32,9 +32,9 @@ trait Listeners { self: Actor ⇒ * {{{ def receive = listenerManagement orElse … }}} */ protected def listenerManagement: Actor.Receive = { - case Listen(l) ⇒ listeners add l - case Deafen(l) ⇒ listeners remove l - case WithListeners(f) ⇒ + case Listen(l) => listeners add l + case Deafen(l) => listeners remove l + case WithListeners(f) => val i = listeners.iterator while (i.hasNext) f(i.next) } diff --git a/akka-actor/src/main/scala/akka/routing/MurmurHash.scala b/akka-actor/src/main/scala/akka/routing/MurmurHash.scala index 510b5e4efe..752f114f4a 100644 --- a/akka-actor/src/main/scala/akka/routing/MurmurHash.scala +++ b/akka-actor/src/main/scala/akka/routing/MurmurHash.scala @@ -20,7 +20,7 @@ package akka.routing -import java.lang.Integer.{ rotateLeft ⇒ rotl } +import java.lang.Integer.{ rotateLeft => rotl } import akka.util.ccompat._ /** @@ -134,7 +134,7 @@ object MurmurHash { def symmetricHash[T](xs: IterableOnce[T], seed: Int): Int = { var a, b, n = 0 var c = 1 - xs.foreach(i ⇒ { + xs.foreach(i => { val h = i.## a += h b ^= h diff --git a/akka-actor/src/main/scala/akka/routing/OptimalSizeExploringResizer.scala b/akka-actor/src/main/scala/akka/routing/OptimalSizeExploringResizer.scala index 90edadd57e..ec116e8a88 100644 --- a/akka-actor/src/main/scala/akka/routing/OptimalSizeExploringResizer.scala +++ b/akka-actor/src/main/scala/akka/routing/OptimalSizeExploringResizer.scala @@ -188,13 +188,13 @@ case class DefaultOptimalSizeExploringResizer( val currentSize = currentRoutees.length val messagesInRoutees = currentRoutees map { - case ActorRefRoutee(a: ActorRefWithCell) ⇒ + case ActorRefRoutee(a: ActorRefWithCell) => a.underlying match { - case cell: ActorCell ⇒ + case cell: ActorCell => cell.mailbox.numberOfMessages + (if (cell.currentMessage != null) 1 else 0) - case cell ⇒ cell.numberOfMessages + case cell => cell.numberOfMessages } - case _ ⇒ 0 + case _ => 0 } val totalQueueLength = messagesInRoutees.sum @@ -219,10 +219,10 @@ case class DefaultOptimalSizeExploringResizer( val duration = Duration.fromNanos(System.nanoTime() - record.checkTime) val last: Duration = duration / totalProcessed //exponentially decrease the weight of old last metrics data - val toUpdate = performanceLog.get(currentSize).fold(last) { oldSpeed ⇒ + val toUpdate = performanceLog.get(currentSize).fold(last) { oldSpeed => (oldSpeed * (1.0 - weightOfLatestMetric)) + (last * weightOfLatestMetric) } - performanceLog + (currentSize → toUpdate) + performanceLog + (currentSize -> toUpdate) } else performanceLog } else performanceLog @@ -257,12 +257,12 @@ case class DefaultOptimalSizeExploringResizer( private def optimize(currentSize: PoolSize): Int = { val adjacentDispatchWaits: Map[PoolSize, Duration] = { - def adjacency = (size: Int) ⇒ Math.abs(currentSize - size) + def adjacency = (size: Int) => Math.abs(currentSize - size) val sizes = performanceLog.keys.toSeq val numOfSizesEachSide = numOfAdjacentSizesToConsiderDuringOptimization / 2 val leftBoundary = sizes.filter(_ < currentSize).sortBy(adjacency).take(numOfSizesEachSide).lastOption.getOrElse(currentSize) val rightBoundary = sizes.filter(_ >= currentSize).sortBy(adjacency).take(numOfSizesEachSide).lastOption.getOrElse(currentSize) - performanceLog.filter { case (size, _) ⇒ size >= leftBoundary && size <= rightBoundary } + performanceLog.filter { case (size, _) => size >= leftBoundary && size <= rightBoundary } } val optimalSize = adjacentDispatchWaits.minBy(_._2)._1 diff --git a/akka-actor/src/main/scala/akka/routing/Resizer.scala b/akka-actor/src/main/scala/akka/routing/Resizer.scala index a56d06353c..b964800f0c 100644 --- a/akka-actor/src/main/scala/akka/routing/Resizer.scala +++ b/akka-actor/src/main/scala/akka/routing/Resizer.scala @@ -60,10 +60,10 @@ object Resizer { val defaultResizerConfig = parentConfig.getConfig("resizer") val metricsBasedResizerConfig = parentConfig.getConfig("optimal-size-exploring-resizer") (defaultResizerConfig.getBoolean("enabled"), metricsBasedResizerConfig.getBoolean("enabled")) match { - case (true, false) ⇒ Some(DefaultResizer(defaultResizerConfig)) - case (false, true) ⇒ Some(OptimalSizeExploringResizer(metricsBasedResizerConfig)) - case (false, false) ⇒ None - case (true, true) ⇒ + case (true, false) => Some(DefaultResizer(defaultResizerConfig)) + case (false, true) => Some(OptimalSizeExploringResizer(metricsBasedResizerConfig)) + case (false, false) => None + case (true, true) => throw new ResizerInitializationException(s"cannot enable both resizer and optimal-size-exploring-resizer", null) } } @@ -190,22 +190,22 @@ case class DefaultResizer( */ def pressure(routees: immutable.IndexedSeq[Routee]): Int = { routees count { - case ActorRefRoutee(a: ActorRefWithCell) ⇒ + case ActorRefRoutee(a: ActorRefWithCell) => a.underlying match { - case cell: ActorCell ⇒ + case cell: ActorCell => pressureThreshold match { - case 1 ⇒ cell.mailbox.isScheduled && cell.mailbox.hasMessages - case i if i < 1 ⇒ cell.mailbox.isScheduled && cell.currentMessage != null - case threshold ⇒ cell.mailbox.numberOfMessages >= threshold + case 1 => cell.mailbox.isScheduled && cell.mailbox.hasMessages + case i if i < 1 => cell.mailbox.isScheduled && cell.currentMessage != null + case threshold => cell.mailbox.numberOfMessages >= threshold } - case cell ⇒ + case cell => pressureThreshold match { - case 1 ⇒ cell.hasMessages - case i if i < 1 ⇒ true // unstarted cells are always busy, for example - case threshold ⇒ cell.numberOfMessages >= threshold + case 1 => cell.hasMessages + case i if i < 1 => true // unstarted cells are always busy, for example + case threshold => cell.numberOfMessages >= threshold } } - case _ ⇒ + case _ => false } } @@ -297,8 +297,8 @@ private[akka] final class ResizablePoolCell( */ private def tryReportMessageCount(): Unit = { resizer match { - case r: OptimalSizeExploringResizer ⇒ r.reportMessageCount(router.routees, resizeCounter.get()) - case _ ⇒ //ignore + case r: OptimalSizeExploringResizer => r.reportMessageCount(router.routees, resizeCounter.get()) + case _ => //ignore } } @@ -319,13 +319,13 @@ private[akka] class ResizablePoolActor(supervisorStrategy: SupervisorStrategy) import ResizablePoolActor._ val resizerCell = context match { - case x: ResizablePoolCell ⇒ x - case _ ⇒ + case x: ResizablePoolCell => x + case _ => throw ActorInitializationException("Resizable router actor can only be used when resizer is defined, not in " + context.getClass) } override def receive = ({ - case Resize ⇒ + case Resize => resizerCell.resize(initial = false) }: Actor.Receive) orElse super.receive diff --git a/akka-actor/src/main/scala/akka/routing/RoutedActorCell.scala b/akka-actor/src/main/scala/akka/routing/RoutedActorCell.scala index eb92f35bba..4608965c8c 100644 --- a/akka-actor/src/main/scala/akka/routing/RoutedActorCell.scala +++ b/akka-actor/src/main/scala/akka/routing/RoutedActorCell.scala @@ -72,46 +72,46 @@ private[akka] class RoutedActorCell( */ def removeRoutees(routees: immutable.Iterable[Routee], stopChild: Boolean): Unit = { val r = _router - val newRoutees = routees.foldLeft(r.routees) { (xs, x) ⇒ unwatch(x); xs.filterNot(_ == x) } + val newRoutees = routees.foldLeft(r.routees) { (xs, x) => unwatch(x); xs.filterNot(_ == x) } _router = r.withRoutees(newRoutees) if (stopChild) routees foreach stopIfChild } private def watch(routee: Routee): Unit = routee match { - case ActorRefRoutee(ref) ⇒ watch(ref) - case _ ⇒ + case ActorRefRoutee(ref) => watch(ref) + case _ => } private def unwatch(routee: Routee): Unit = routee match { - case ActorRefRoutee(ref) ⇒ unwatch(ref) - case _ ⇒ + case ActorRefRoutee(ref) => unwatch(ref) + case _ => } private def stopIfChild(routee: Routee): Unit = routee match { - case ActorRefRoutee(ref) ⇒ child(ref.path.name) match { - case Some(`ref`) ⇒ + case ActorRefRoutee(ref) => child(ref.path.name) match { + case Some(`ref`) => // The reason for the delay is to give concurrent // messages a chance to be placed in mailbox before sending PoisonPill, // best effort. system.scheduler.scheduleOnce(100.milliseconds, ref, PoisonPill)(dispatcher) - case _ ⇒ + case _ => } - case _ ⇒ + case _ => } override def start(): this.type = { // create the initial routees before scheduling the Router actor _router = routerConfig.createRouter(system) routerConfig match { - case pool: Pool ⇒ + case pool: Pool => val nrOfRoutees = pool.nrOfInstances(system) if (nrOfRoutees > 0) addRoutees(Vector.fill(nrOfRoutees)(pool.newRoutee(routeeProps, this))) - case group: Group ⇒ + case group: Group => val paths = group.paths(system) if (paths.nonEmpty) - addRoutees(paths.iterator.map(p ⇒ group.routeeFor(p, this)).to(immutable.IndexedSeq)) - case _ ⇒ + addRoutees(paths.iterator.map(p => group.routeeFor(p, this)).to(immutable.IndexedSeq)) + case _ => } preSuperStart() super.start() @@ -144,28 +144,28 @@ private[akka] class RoutedActorCell( */ private[akka] class RouterActor extends Actor { val cell = context match { - case x: RoutedActorCell ⇒ x - case _ ⇒ + case x: RoutedActorCell => x + case _ => throw ActorInitializationException("Router actor can only be used in RoutedActorRef, not in " + context.getClass) } val routingLogicController: Option[ActorRef] = cell.routerConfig.routingLogicController( - cell.router.logic).map(props ⇒ context.actorOf( + cell.router.logic).map(props => context.actorOf( props.withDispatcher(context.props.dispatcher), name = "routingLogicController")) def receive = { - case GetRoutees ⇒ + case GetRoutees => sender() ! Routees(cell.router.routees) - case AddRoutee(routee) ⇒ + case AddRoutee(routee) => cell.addRoutee(routee) - case RemoveRoutee(routee) ⇒ + case RemoveRoutee(routee) => cell.removeRoutee(routee, stopChild = true) stopIfAllRouteesRemoved() - case Terminated(child) ⇒ + case Terminated(child) => cell.removeRoutee(ActorRefRoutee(child), stopChild = false) stopIfAllRouteesRemoved() - case other if routingLogicController.isDefined ⇒ + case other if routingLogicController.isDefined => routingLogicController.foreach(_.forward(other)) } @@ -184,13 +184,13 @@ private[akka] class RouterActor extends Actor { private[akka] class RouterPoolActor(override val supervisorStrategy: SupervisorStrategy) extends RouterActor { val pool = cell.routerConfig match { - case x: Pool ⇒ x - case other ⇒ + case x: Pool => x + case other => throw ActorInitializationException("RouterPoolActor can only be used with Pool, not " + other.getClass) } override def receive = ({ - case AdjustPoolSize(change: Int) ⇒ + case AdjustPoolSize(change: Int) => if (change > 0) { val newRoutees = Vector.fill(change)(pool.newRoutee(cell.routeeProps, context)) cell.addRoutees(newRoutees) diff --git a/akka-actor/src/main/scala/akka/routing/RoutedActorRef.scala b/akka-actor/src/main/scala/akka/routing/RoutedActorRef.scala index dc83df505b..b512902628 100644 --- a/akka-actor/src/main/scala/akka/routing/RoutedActorRef.scala +++ b/akka-actor/src/main/scala/akka/routing/RoutedActorRef.scala @@ -41,9 +41,9 @@ private[akka] class RoutedActorRef( override def newCell(old: UnstartedCell): Cell = { val cell = props.routerConfig match { - case pool: Pool if pool.resizer.isDefined ⇒ + case pool: Pool if pool.resizer.isDefined => new ResizablePoolCell(system, this, props, dispatcher, _routeeProps, supervisor, pool) - case _ ⇒ + case _ => new RoutedActorCell(system, this, props, dispatcher, _routeeProps, supervisor) } cell.init(sendSupervise = false, mailboxType) diff --git a/akka-actor/src/main/scala/akka/routing/Router.scala b/akka-actor/src/main/scala/akka/routing/Router.scala index 1ac9ee25c8..2ef2337faa 100644 --- a/akka-actor/src/main/scala/akka/routing/Router.scala +++ b/akka-actor/src/main/scala/akka/routing/Router.scala @@ -113,8 +113,8 @@ final case class Router(val logic: RoutingLogic, val routees: immutable.IndexedS */ def route(message: Any, sender: ActorRef): Unit = message match { - case akka.routing.Broadcast(msg) ⇒ SeveralRoutees(routees).send(msg, sender) - case msg ⇒ send(logic.select(msg, routees), message, sender) + case akka.routing.Broadcast(msg) => SeveralRoutees(routees).send(msg, sender) + case msg => send(logic.select(msg, routees), message, sender) } private def send(routee: Routee, msg: Any, sender: ActorRef): Unit = { @@ -125,8 +125,8 @@ final case class Router(val logic: RoutingLogic, val routees: immutable.IndexedS } private def unwrap(msg: Any): Any = msg match { - case env: RouterEnvelope ⇒ env.message - case _ ⇒ msg + case env: RouterEnvelope => env.message + case _ => msg } /** diff --git a/akka-actor/src/main/scala/akka/routing/RouterConfig.scala b/akka-actor/src/main/scala/akka/routing/RouterConfig.scala index 3dc790a789..793d9ffb9c 100644 --- a/akka-actor/src/main/scala/akka/routing/RouterConfig.scala +++ b/akka-actor/src/main/scala/akka/routing/RouterConfig.scala @@ -66,8 +66,8 @@ trait RouterConfig extends Serializable { * [[#routingLogicController]] actor. */ def isManagementMessage(msg: Any): Boolean = msg match { - case _: AutoReceivedMessage | _: Terminated | _: RouterManagementMesssage ⇒ true - case _ ⇒ false + case _: AutoReceivedMessage | _: Terminated | _: RouterManagementMesssage => true + case _ => false } /* @@ -106,7 +106,7 @@ private[akka] trait PoolOverrideUnsetConfig[T <: Pool] extends Pool { else { other match { - case p: Pool ⇒ + case p: Pool => val wssConf: PoolOverrideUnsetConfig[T] = if ((this.supervisorStrategy eq Pool.defaultSupervisorStrategy) && (p.supervisorStrategy ne Pool.defaultSupervisorStrategy)) @@ -117,7 +117,7 @@ private[akka] trait PoolOverrideUnsetConfig[T <: Pool] extends Pool { wssConf.withResizer(p.resizer.get) else wssConf - case _ ⇒ this + case _ => this } } @@ -166,7 +166,7 @@ trait Group extends RouterConfig { object Pool { val defaultSupervisorStrategy: SupervisorStrategy = OneForOneStrategy() { - case _ ⇒ SupervisorStrategy.Escalate + case _ => SupervisorStrategy.Escalate } } @@ -240,8 +240,8 @@ trait Pool extends RouterConfig { */ private[akka] override def createRouterActor(): RouterActor = resizer match { - case None ⇒ new RouterPoolActor(supervisorStrategy) - case Some(_) ⇒ new ResizablePoolActor(supervisorStrategy) + case None => new RouterPoolActor(supervisorStrategy) + case Some(_) => new ResizablePoolActor(supervisorStrategy) } } diff --git a/akka-actor/src/main/scala/akka/routing/ScatterGatherFirstCompleted.scala b/akka-actor/src/main/scala/akka/routing/ScatterGatherFirstCompleted.scala index c671711777..4147fe77a6 100644 --- a/akka-actor/src/main/scala/akka/routing/ScatterGatherFirstCompleted.scala +++ b/akka-actor/src/main/scala/akka/routing/ScatterGatherFirstCompleted.scala @@ -51,11 +51,11 @@ private[akka] final case class ScatterGatherFirstCompletedRoutees( implicit val timeout = Timeout(within) val promise = Promise[Any]() routees.foreach { - case ActorRefRoutee(ref) ⇒ + case ActorRefRoutee(ref) => promise.tryCompleteWith(ref.ask(message)) - case ActorSelectionRoutee(sel) ⇒ + case ActorSelectionRoutee(sel) => promise.tryCompleteWith(sel.ask(message)) - case _ ⇒ + case _ => } promise.future.pipeTo(sender) diff --git a/akka-actor/src/main/scala/akka/routing/SmallestMailbox.scala b/akka-actor/src/main/scala/akka/routing/SmallestMailbox.scala index a88c227060..a36daf344d 100644 --- a/akka-actor/src/main/scala/akka/routing/SmallestMailbox.scala +++ b/akka-actor/src/main/scala/akka/routing/SmallestMailbox.scala @@ -76,8 +76,8 @@ class SmallestMailboxRoutingLogic extends RoutingLogic { } protected def isTerminated(a: Routee): Boolean = a match { - case ActorRefRoutee(ref) ⇒ ref.isTerminated - case _ ⇒ false + case ActorRefRoutee(ref) => ref.isTerminated + case _ => false } /** @@ -87,12 +87,12 @@ class SmallestMailboxRoutingLogic extends RoutingLogic { * routers based on mailbox and actor internal state. */ protected def isProcessingMessage(a: Routee): Boolean = a match { - case ActorRefRoutee(x: ActorRefWithCell) ⇒ + case ActorRefRoutee(x: ActorRefWithCell) => x.underlying match { - case cell: ActorCell ⇒ cell.mailbox.isScheduled && cell.currentMessage != null - case _ ⇒ false + case cell: ActorCell => cell.mailbox.isScheduled && cell.currentMessage != null + case _ => false } - case _ ⇒ false + case _ => false } /** @@ -103,8 +103,8 @@ class SmallestMailboxRoutingLogic extends RoutingLogic { * routers based on mailbox and actor internal state. */ protected def hasMessages(a: Routee): Boolean = a match { - case ActorRefRoutee(x: ActorRefWithCell) ⇒ x.underlying.hasMessages - case _ ⇒ false + case ActorRefRoutee(x: ActorRefWithCell) => x.underlying.hasMessages + case _ => false } /** @@ -114,12 +114,12 @@ class SmallestMailboxRoutingLogic extends RoutingLogic { * routers based on mailbox and actor internal state. */ protected def isSuspended(a: Routee): Boolean = a match { - case ActorRefRoutee(x: ActorRefWithCell) ⇒ + case ActorRefRoutee(x: ActorRefWithCell) => x.underlying match { - case cell: ActorCell ⇒ cell.mailbox.isSuspended - case _ ⇒ true + case cell: ActorCell => cell.mailbox.isSuspended + case _ => true } - case _ ⇒ false + case _ => false } /** @@ -129,8 +129,8 @@ class SmallestMailboxRoutingLogic extends RoutingLogic { * routers based on mailbox and actor internal state. */ protected def numberOfMessages(a: Routee): Int = a match { - case ActorRefRoutee(x: ActorRefWithCell) ⇒ x.underlying.numberOfMessages - case _ ⇒ 0 + case ActorRefRoutee(x: ActorRefWithCell) => x.underlying.numberOfMessages + case _ => 0 } } diff --git a/akka-actor/src/main/scala/akka/routing/TailChopping.scala b/akka-actor/src/main/scala/akka/routing/TailChopping.scala index fdccb107e7..a2b70c5849 100644 --- a/akka-actor/src/main/scala/akka/routing/TailChopping.scala +++ b/akka-actor/src/main/scala/akka/routing/TailChopping.scala @@ -74,11 +74,11 @@ private[akka] final case class TailChoppingRoutees( val idx = aIdx.getAndIncrement if (idx < size) { shuffled(idx) match { - case ActorRefRoutee(ref) ⇒ + case ActorRefRoutee(ref) => promise.tryCompleteWith(ref.ask(message)) - case ActorSelectionRoutee(sel) ⇒ + case ActorSelectionRoutee(sel) => promise.tryCompleteWith(sel.ask(message)) - case _ ⇒ + case _ => } } } @@ -88,7 +88,7 @@ private[akka] final case class TailChoppingRoutees( val f = promise.future f.onComplete { - case _ ⇒ + case _ => tryWithNext.cancel() sendTimeout.cancel() } diff --git a/akka-actor/src/main/scala/akka/serialization/Serialization.scala b/akka-actor/src/main/scala/akka/serialization/Serialization.scala index 1a12bf3546..fbedca50b3 100644 --- a/akka-actor/src/main/scala/akka/serialization/Serialization.scala +++ b/akka-actor/src/main/scala/akka/serialization/Serialization.scala @@ -63,7 +63,7 @@ object Serialization { private final def configToMap(cfg: Config): Map[String, String] = { import scala.collection.JavaConverters._ - cfg.root.unwrapped.asScala.toMap map { case (k, v) ⇒ (k → v.toString) } + cfg.root.unwrapped.asScala.toMap map { case (k, v) => (k -> v.toString) } } } @@ -76,17 +76,17 @@ object Serialization { def serializedActorPath(actorRef: ActorRef): String = { val path = actorRef.path val originalSystem: ExtendedActorSystem = actorRef match { - case a: ActorRefWithCell ⇒ a.underlying.system.asInstanceOf[ExtendedActorSystem] - case _ ⇒ null + case a: ActorRefWithCell => a.underlying.system.asInstanceOf[ExtendedActorSystem] + case _ => null } Serialization.currentTransportInformation.value match { - case null ⇒ originalSystem match { - case null ⇒ path.toSerializationFormat - case system ⇒ + case null => originalSystem match { + case null => path.toSerializationFormat + case system => try path.toSerializationFormatWithAddress(system.provider.getDefaultAddress) - catch { case NonFatal(_) ⇒ path.toSerializationFormat } + catch { case NonFatal(_) => path.toSerializationFormat } } - case Information(address, system) ⇒ + case Information(address, system) => if (originalSystem == null || originalSystem == system) path.toSerializationFormatWithAddress(address) else { @@ -115,7 +115,7 @@ object Serialization { * * @return value returned by `f` */ - def withTransportInformation[T](system: ExtendedActorSystem)(f: () ⇒ T): T = { + def withTransportInformation[T](system: ExtendedActorSystem)(f: () => T): T = { val info = system.provider.serializationInformation if (Serialization.currentTransportInformation.value eq info) f() // already set @@ -135,9 +135,9 @@ object Serialization { */ def getCurrentTransportInformation(): Information = { Serialization.currentTransportInformation.value match { - case null ⇒ throw new IllegalStateException( + case null => throw new IllegalStateException( "currentTransportInformation is not set, use Serialization.withTransportInformation") - case t ⇒ t + case t => t } } @@ -161,7 +161,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { @InternalApi private[akka] def serializationInformation: Serialization.Information = system.provider.serializationInformation - private def withTransportInformation[T](f: () ⇒ T): T = { + private def withTransportInformation[T](f: () => T): T = { val oldInfo = Serialization.currentTransportInformation.value try { if (oldInfo eq null) @@ -175,7 +175,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { * to either an Array of Bytes or an Exception if one was thrown. */ def serialize(o: AnyRef): Try[Array[Byte]] = { - withTransportInformation { () ⇒ + withTransportInformation { () => Try(findSerializerFor(o).toBinary(o)) } } @@ -188,12 +188,12 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { def deserialize[T](bytes: Array[Byte], serializerId: Int, clazz: Option[Class[_ <: T]]): Try[T] = Try { val serializer = try getSerializerById(serializerId) catch { - case _: NoSuchElementException ⇒ throw new NotSerializableException( - s"Cannot find serializer with id [$serializerId]${clazz.map(c ⇒ " (class [" + c.getName + "])").getOrElse("")}. " + + case _: NoSuchElementException => throw new NotSerializableException( + s"Cannot find serializer with id [$serializerId]${clazz.map(c => " (class [" + c.getName + "])").getOrElse("")}. " + "The most probable reason is that the configuration entry " + "akka.actor.serializers is not in sync between the two systems.") } - withTransportInformation { () ⇒ + withTransportInformation { () => serializer.fromBinary(bytes, clazz).asInstanceOf[T] } } @@ -206,7 +206,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { def deserialize(bytes: Array[Byte], serializerId: Int, manifest: String): Try[AnyRef] = Try { val serializer = try getSerializerById(serializerId) catch { - case _: NoSuchElementException ⇒ throw new NotSerializableException( + case _: NoSuchElementException => throw new NotSerializableException( s"Cannot find serializer with id [$serializerId] (manifest [$manifest]). The most probable reason is that the configuration entry " + "akka.actor.serializers is not in sync between the two systems.") } @@ -220,23 +220,23 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { updateCache(manifestCache.get, key, value) // recursive, try again } - withTransportInformation { () ⇒ + withTransportInformation { () => serializer match { - case s2: SerializerWithStringManifest ⇒ s2.fromBinary(bytes, manifest) - case s1 ⇒ + case s2: SerializerWithStringManifest => s2.fromBinary(bytes, manifest) + case s1 => if (manifest == "") s1.fromBinary(bytes, None) else { val cache = manifestCache.get cache.get(manifest) match { - case Some(cachedClassManifest) ⇒ s1.fromBinary(bytes, cachedClassManifest) - case None ⇒ + case Some(cachedClassManifest) => s1.fromBinary(bytes, cachedClassManifest) + case None => system.dynamicAccess.getClassFor[AnyRef](manifest) match { - case Success(classManifest) ⇒ + case Success(classManifest) => val classManifestOption: Option[Class[_]] = Some(classManifest) updateCache(cache, manifest, classManifestOption) s1.fromBinary(bytes, classManifestOption) - case Failure(_) ⇒ + case Failure(_) => throw new NotSerializableException( s"Cannot find manifest class [$manifest] for serializer with id [${serializer.identifier}].") } @@ -254,7 +254,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { @throws(classOf[NotSerializableException]) def deserializeByteBuffer(buf: ByteBuffer, serializerId: Int, manifest: String): AnyRef = { val serializer = try getSerializerById(serializerId) catch { - case _: NoSuchElementException ⇒ throw new NotSerializableException( + case _: NoSuchElementException => throw new NotSerializableException( s"Cannot find serializer with id [$serializerId] (manifest [$manifest]). The most probable reason is that the configuration entry " + "akka.actor.serializers is not in synch between the two systems.") } @@ -267,9 +267,9 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { Serialization.currentTransportInformation.value = serializationInformation serializer match { - case ser: ByteBufferSerializer ⇒ + case ser: ByteBufferSerializer => ser.fromBinary(buf, manifest) - case _ ⇒ + case _ => val bytes = new Array[Byte](buf.remaining()) buf.get(bytes) deserializeByteArray(bytes, serializer, manifest) @@ -282,7 +282,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { * Returns either the resulting object or an Exception if one was thrown. */ def deserialize[T](bytes: Array[Byte], clazz: Class[T]): Try[T] = { - withTransportInformation { () ⇒ + withTransportInformation { () => Try(serializerFor(clazz).fromBinary(bytes, Some(clazz)).asInstanceOf[T]) } } @@ -308,7 +308,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { @throws(classOf[NotSerializableException]) def serializerFor(clazz: Class[_]): Serializer = serializerMap.get(clazz) match { - case null ⇒ // bindings are ordered from most specific to least specific + case null => // bindings are ordered from most specific to least specific def unique(possibilities: immutable.Seq[(Class[_], Serializer)]): Boolean = possibilities.size == 1 || (possibilities forall (_._1 isAssignableFrom possibilities(0)._1)) || @@ -316,19 +316,19 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { val ser = { bindings.filter { - case (c, _) ⇒ c isAssignableFrom clazz + case (c, _) => c isAssignableFrom clazz } match { - case immutable.Seq() ⇒ + case immutable.Seq() => throw new NotSerializableException(s"No configured serialization-bindings for class [${clazz.getName}]") - case possibilities ⇒ + case possibilities => if (unique(possibilities)) possibilities.head._2 else { // give JavaSerializer lower priority if multiple serializers found val possibilitiesWithoutJavaSerializer = possibilities.filter { - case (_, _: JavaSerializer) ⇒ false - case (_, _: DisabledJavaSerializer) ⇒ false - case _ ⇒ true + case (_, _: JavaSerializer) => false + case (_, _: DisabledJavaSerializer) => false + case _ => true } if (possibilitiesWithoutJavaSerializer.isEmpty) { // shouldn't happen @@ -338,7 +338,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { if (!unique(possibilitiesWithoutJavaSerializer)) { _log.warning(LogMarker.Security, "Multiple serializers found for [{}], choosing first of: [{}]", clazz.getName, - possibilitiesWithoutJavaSerializer.map { case (_, s) ⇒ s.getClass.getName }.mkString(", ")) + possibilitiesWithoutJavaSerializer.map { case (_, s) => s.getClass.getName }.mkString(", ")) } possibilitiesWithoutJavaSerializer.head._2 @@ -348,7 +348,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { } serializerMap.putIfAbsent(clazz, ser) match { - case null ⇒ + case null => if (shouldWarnAboutJavaSerializer(clazz, ser)) { _log.warning(LogMarker.Security, "Using the default Java serializer for class [{}] which is not recommended because of " + "performance implications. Use another serializer or disable this warning using the setting " + @@ -359,9 +359,9 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { log.debug("Using serializer [{}] for message [{}]", ser.getClass.getName, clazz.getName) ser - case some ⇒ some + case some => some } - case ser ⇒ ser + case ser => ser } /** @@ -377,11 +377,11 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { classOf[DisabledJavaSerializer].getName } else serializerFQN - system.dynamicAccess.createInstanceFor[Serializer](fqn, List(classOf[ExtendedActorSystem] → system)) recoverWith { - case _: NoSuchMethodException ⇒ + system.dynamicAccess.createInstanceFor[Serializer](fqn, List(classOf[ExtendedActorSystem] -> system)) recoverWith { + case _: NoSuchMethodException => system.dynamicAccess.createInstanceFor[Serializer](fqn, Nil) // FIXME only needed on 2.13.0-M5 due to https://github.com/scala/bug/issues/11242 - case t ⇒ Failure(t) + case t => Failure(t) } } @@ -390,14 +390,14 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { */ private val serializerDetails: immutable.Seq[SerializerDetails] = (system.settings.setup.get[SerializationSetup] match { - case None ⇒ Vector.empty - case Some(setting) ⇒ setting.createSerializers(system) + case None => Vector.empty + case Some(setting) => setting.createSerializers(system) }) collect { - case det: SerializerDetails if isDisallowedJavaSerializer(det.serializer) ⇒ + case det: SerializerDetails if isDisallowedJavaSerializer(det.serializer) => log.debug("Replacing JavaSerializer with DisabledJavaSerializer, " + "due to `akka.actor.allow-java-serialization = off`.") SerializerDetails(det.alias, new DisabledJavaSerializer(system), det.useFor) - case det ⇒ det + case det => det } /** @@ -405,9 +405,9 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { * By default always contains the following mapping: "java" -> akka.serialization.JavaSerializer */ private val serializers: Map[String, Serializer] = { - val fromConfig = for ((k: String, v: String) ← settings.Serializers) yield k → serializerOf(v).get - val result = fromConfig ++ serializerDetails.map(d ⇒ d.alias → d.serializer) - ensureOnlyAllowedSerializers(result.iterator.map { case (_, ser) ⇒ ser }) + val fromConfig = for ((k: String, v: String) <- settings.Serializers) yield k -> serializerOf(v).get + val result = fromConfig ++ serializerDetails.map(d => d.alias -> d.serializer) + ensureOnlyAllowedSerializers(result.iterator.map { case (_, ser) => ser }) result } @@ -417,17 +417,17 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { */ private[akka] val bindings: immutable.Seq[ClassSerializer] = { val fromConfig = for { - (className: String, alias: String) ← settings.SerializationBindings + (className: String, alias: String) <- settings.SerializationBindings if alias != "none" && checkGoogleProtobuf(className) } yield (system.dynamicAccess.getClassFor[Any](className).get, serializers(alias)) - val fromSettings = serializerDetails.flatMap { detail ⇒ - detail.useFor.map(clazz ⇒ clazz → detail.serializer) + val fromSettings = serializerDetails.flatMap { detail => + detail.useFor.map(clazz => clazz -> detail.serializer) } val result = sort(fromConfig ++ fromSettings) - ensureOnlyAllowedSerializers(result.iterator.map { case (_, ser) ⇒ ser }) - result.foreach { case (clazz, ser) ⇒ warnUnexpectedNonAkkaSerializer(clazz, ser) } + ensureOnlyAllowedSerializers(result.iterator.map { case (_, ser) => ser }) + result.foreach { case (clazz, ser) => warnUnexpectedNonAkkaSerializer(clazz, ser) } result } @@ -458,10 +458,10 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { * obeying any order between unrelated subtypes (insert sort). */ private def sort(in: Iterable[ClassSerializer]): immutable.Seq[ClassSerializer] = - (in.foldLeft(new ArrayBuffer[ClassSerializer](in.size)) { (buf, ca) ⇒ + (in.foldLeft(new ArrayBuffer[ClassSerializer](in.size)) { (buf, ca) => buf.indexWhere(_._1 isAssignableFrom ca._1) match { - case -1 ⇒ buf append ca - case x ⇒ buf insert (x, ca) + case -1 => buf append ca + case x => buf insert (x, ca) } buf }).to(immutable.Seq) @@ -471,13 +471,13 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { * to be used for that class. */ private val serializerMap: ConcurrentHashMap[Class[_], Serializer] = - bindings.foldLeft(new ConcurrentHashMap[Class[_], Serializer]) { case (map, (c, s)) ⇒ map.put(c, s); map } + bindings.foldLeft(new ConcurrentHashMap[Class[_], Serializer]) { case (map, (c, s)) => map.put(c, s); map } /** * Maps from a Serializer Identity (Int) to a Serializer instance (optimization) */ val serializerByIdentity: Map[Int, Serializer] = - Map(NullSerializer.identifier → NullSerializer) ++ serializers.map { case (_, v) ⇒ (v.identifier, v) } + Map(NullSerializer.identifier -> NullSerializer) ++ serializers.map { case (_, v) => (v.identifier, v) } /** * Serializers with id 0 - 1023 are stored in an array for quick allocation free access @@ -486,7 +486,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { val size = 1024 val table = new Array[Serializer](size) serializerByIdentity.foreach { - case (id, ser) ⇒ if (0 <= id && id < size) table(id) = ser + case (id, ser) => if (0 <= id && id < size) table(id) = ser } table } @@ -497,8 +497,8 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { private def getSerializerById(id: Int): Serializer = { if (0 <= id && id < quickSerializerByIdentity.length) { quickSerializerByIdentity(id) match { - case null ⇒ throw new NoSuchElementException(s"key not found: $id") - case ser ⇒ ser + case null => throw new NoSuchElementException(s"key not found: $id") + case ser => ser } } else serializerByIdentity(id) diff --git a/akka-actor/src/main/scala/akka/serialization/SerializationSetup.scala b/akka-actor/src/main/scala/akka/serialization/SerializationSetup.scala index 77b9bfe7cd..a3afd82229 100644 --- a/akka-actor/src/main/scala/akka/serialization/SerializationSetup.scala +++ b/akka-actor/src/main/scala/akka/serialization/SerializationSetup.scala @@ -16,7 +16,7 @@ object SerializationSetup { * Scala API: Programmatic definition of serializers * @param createSerializers create pairs of serializer and the set of classes it should be used for */ - def apply(createSerializers: ExtendedActorSystem ⇒ immutable.Seq[SerializerDetails]): SerializationSetup = { + def apply(createSerializers: ExtendedActorSystem => immutable.Seq[SerializerDetails]): SerializationSetup = { new SerializationSetup(createSerializers) } @@ -26,7 +26,7 @@ object SerializationSetup { */ def create( createSerializers: akka.japi.Function[ExtendedActorSystem, java.util.List[SerializerDetails]]): SerializationSetup = - apply(sys ⇒ createSerializers(sys).asScala.toVector) + apply(sys => createSerializers(sys).asScala.toVector) } @@ -34,7 +34,7 @@ object SerializationSetup { * Setup for the serialization subsystem, constructor is *Internal API*, use factories in [[SerializationSetup()]] */ final class SerializationSetup private ( - val createSerializers: ExtendedActorSystem ⇒ immutable.Seq[SerializerDetails] + val createSerializers: ExtendedActorSystem => immutable.Seq[SerializerDetails] ) extends Setup object SerializerDetails { diff --git a/akka-actor/src/main/scala/akka/serialization/Serializer.scala b/akka-actor/src/main/scala/akka/serialization/Serializer.scala index e91e08f789..44ac5e9b3c 100644 --- a/akka-actor/src/main/scala/akka/serialization/Serializer.scala +++ b/akka-actor/src/main/scala/akka/serialization/Serializer.scala @@ -76,8 +76,8 @@ object Serializers { // NOTE!!! If you change this method it is likely that DaemonMsgCreateSerializer.serialize needs the changes too. def manifestFor(s: Serializer, message: AnyRef): String = s match { - case s2: SerializerWithStringManifest ⇒ s2.manifest(message) - case _ ⇒ if (s.includeManifest) message.getClass.getName else "" + case s2: SerializerWithStringManifest => s2.manifest(message) + case _ => if (s.includeManifest) message.getClass.getName else "" } } @@ -147,8 +147,8 @@ abstract class SerializerWithStringManifest extends Serializer { final def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = { val manifestString = manifest match { - case Some(c) ⇒ c.getName - case None ⇒ "" + case Some(c) => c.getName + case None => "" } fromBinary(bytes, manifestString) } @@ -402,9 +402,9 @@ class ByteArraySerializer(val system: ExtendedActorSystem) extends BaseSerialize def includeManifest: Boolean = false def toBinary(o: AnyRef): Array[Byte] = o match { - case null ⇒ null - case o: Array[Byte] ⇒ o - case other ⇒ throw new IllegalArgumentException( + case null => null + case o: Array[Byte] => o + case other => throw new IllegalArgumentException( s"${getClass.getName} only serializes byte arrays, not [${other.getClass.getName}]") } @@ -413,9 +413,9 @@ class ByteArraySerializer(val system: ExtendedActorSystem) extends BaseSerialize override def toBinary(o: AnyRef, buf: ByteBuffer): Unit = o match { - case null ⇒ - case bytes: Array[Byte] ⇒ buf.put(bytes) - case other ⇒ throw new IllegalArgumentException( + case null => + case bytes: Array[Byte] => buf.put(bytes) + case other => throw new IllegalArgumentException( s"${getClass.getName} only serializes byte arrays, not [${other.getClass.getName}]") } diff --git a/akka-actor/src/main/scala/akka/util/BoundedBlockingQueue.scala b/akka-actor/src/main/scala/akka/util/BoundedBlockingQueue.scala index 8e44d3a975..c3e662a17e 100644 --- a/akka-actor/src/main/scala/akka/util/BoundedBlockingQueue.scala +++ b/akka-actor/src/main/scala/akka/util/BoundedBlockingQueue.scala @@ -19,12 +19,12 @@ class BoundedBlockingQueue[E <: AnyRef]( val maxCapacity: Int, private val backing: Queue[E]) extends AbstractQueue[E] with BlockingQueue[E] { backing match { - case null ⇒ throw new IllegalArgumentException("Backing Queue may not be null") - case b: BlockingQueue[_] ⇒ + case null => throw new IllegalArgumentException("Backing Queue may not be null") + case b: BlockingQueue[_] => require(maxCapacity > 0) require(b.size() == 0) require(b.remainingCapacity >= maxCapacity) - case b: Queue[_] ⇒ + case b: Queue[_] => require(b.size() == 0) require(maxCapacity > 0) } @@ -107,9 +107,9 @@ class BoundedBlockingQueue[E <: AnyRef]( try { @tailrec def pollElement(remainingNanos: Long): E = { backing.poll() match { - case null if remainingNanos <= 0 ⇒ null.asInstanceOf[E] - case null ⇒ pollElement(notEmpty.awaitNanos(remainingNanos)) - case e ⇒ { + case null if remainingNanos <= 0 => null.asInstanceOf[E] + case null => pollElement(notEmpty.awaitNanos(remainingNanos)) + case e => { notFull.signal() e } @@ -123,8 +123,8 @@ class BoundedBlockingQueue[E <: AnyRef]( lock.lock() try { backing.poll() match { - case null ⇒ null.asInstanceOf[E] - case e ⇒ + case null => null.asInstanceOf[E] + case e => notFull.signal() e } @@ -186,8 +186,8 @@ class BoundedBlockingQueue[E <: AnyRef]( @tailrec def drainOne(n: Int = 0): Int = { if (n < maxElements) { backing.poll() match { - case null ⇒ n - case e ⇒ c add e; drainOne(n + 1) + case null => n + case e => c add e; drainOne(n + 1) } } else n } diff --git a/akka-actor/src/main/scala/akka/util/BoxedType.scala b/akka-actor/src/main/scala/akka/util/BoxedType.scala index 69293f59e3..769ae04ed9 100644 --- a/akka-actor/src/main/scala/akka/util/BoxedType.scala +++ b/akka-actor/src/main/scala/akka/util/BoxedType.scala @@ -5,18 +5,18 @@ package akka.util object BoxedType { - import java.{ lang ⇒ jl } + import java.{ lang => jl } private val toBoxed = Map[Class[_], Class[_]]( - classOf[Boolean] → classOf[jl.Boolean], - classOf[Byte] → classOf[jl.Byte], - classOf[Char] → classOf[jl.Character], - classOf[Short] → classOf[jl.Short], - classOf[Int] → classOf[jl.Integer], - classOf[Long] → classOf[jl.Long], - classOf[Float] → classOf[jl.Float], - classOf[Double] → classOf[jl.Double], - classOf[Unit] → classOf[scala.runtime.BoxedUnit]) + classOf[Boolean] -> classOf[jl.Boolean], + classOf[Byte] -> classOf[jl.Byte], + classOf[Char] -> classOf[jl.Character], + classOf[Short] -> classOf[jl.Short], + classOf[Int] -> classOf[jl.Integer], + classOf[Long] -> classOf[jl.Long], + classOf[Float] -> classOf[jl.Float], + classOf[Double] -> classOf[jl.Double], + classOf[Unit] -> classOf[scala.runtime.BoxedUnit]) final def apply(c: Class[_]): Class[_] = if (c.isPrimitive) toBoxed(c) else c } diff --git a/akka-actor/src/main/scala/akka/util/ClassLoaderObjectInputStream.scala b/akka-actor/src/main/scala/akka/util/ClassLoaderObjectInputStream.scala index c3f8cacc1c..3f35dcdbd9 100644 --- a/akka-actor/src/main/scala/akka/util/ClassLoaderObjectInputStream.scala +++ b/akka-actor/src/main/scala/akka/util/ClassLoaderObjectInputStream.scala @@ -16,6 +16,6 @@ import java.io.{ InputStream, ObjectInputStream, ObjectStreamClass } class ClassLoaderObjectInputStream(classLoader: ClassLoader, is: InputStream) extends ObjectInputStream(is) { override protected def resolveClass(objectStreamClass: ObjectStreamClass): Class[_] = try Class.forName(objectStreamClass.getName, false, classLoader) catch { - case _: ClassNotFoundException ⇒ super.resolveClass(objectStreamClass) + case _: ClassNotFoundException => super.resolveClass(objectStreamClass) } } diff --git a/akka-actor/src/main/scala/akka/util/Collections.scala b/akka-actor/src/main/scala/akka/util/Collections.scala index 4482db9890..5131622566 100644 --- a/akka-actor/src/main/scala/akka/util/Collections.scala +++ b/akka-actor/src/main/scala/akka/util/Collections.scala @@ -49,7 +49,7 @@ private[akka] object Collections { } override lazy val size: Int = iterator.size - override def foreach[C](f: To ⇒ C) = iterator foreach f + override def foreach[C](f: To => C) = iterator foreach f } } diff --git a/akka-actor/src/main/scala/akka/util/ConstantFun.scala b/akka-actor/src/main/scala/akka/util/ConstantFun.scala index 2d35a59eb8..25329416dc 100644 --- a/akka-actor/src/main/scala/akka/util/ConstantFun.scala +++ b/akka-actor/src/main/scala/akka/util/ConstantFun.scala @@ -5,8 +5,8 @@ package akka.util import akka.annotation.InternalApi -import akka.japi.function.{ Function ⇒ JFun, Function2 ⇒ JFun2 } -import akka.japi.{ Pair ⇒ JPair } +import akka.japi.function.{ Function => JFun, Function2 => JFun2 } +import akka.japi.{ Pair => JPair } /** * INTERNAL API @@ -25,45 +25,45 @@ import akka.japi.{ Pair ⇒ JPair } def javaIdentityFunction[T]: JFun[T, T] = JavaIdentityFunction.asInstanceOf[JFun[T, T]] - def scalaIdentityFunction[T]: T ⇒ T = conforms.asInstanceOf[Function[T, T]] + def scalaIdentityFunction[T]: T => T = conforms.asInstanceOf[Function[T, T]] - def scalaAnyToNone[A, B]: A ⇒ Option[B] = none - def scalaAnyToUnit[A]: A ⇒ Unit = unit - def scalaAnyTwoToNone[A, B, C]: (A, B) ⇒ Option[C] = two2none - def scalaAnyTwoToUnit[A, B]: (A, B) ⇒ Unit = two2unit - def scalaAnyThreeToUnit[A, B, C]: (A, B, C) ⇒ Unit = three2unit - def scalaAnyTwoToTrue[A, B]: (A, B) ⇒ Boolean = two2true - def scalaAnyThreeToFalse[A, B, C]: (A, B, C) ⇒ Boolean = three2false - def scalaAnyThreeToThird[A, B, C]: (A, B, C) ⇒ C = three2third.asInstanceOf[(A, B, C) ⇒ C] - def javaAnyToNone[A, B]: A ⇒ Option[B] = none - def nullFun[T] = _nullFun.asInstanceOf[Any ⇒ T] + def scalaAnyToNone[A, B]: A => Option[B] = none + def scalaAnyToUnit[A]: A => Unit = unit + def scalaAnyTwoToNone[A, B, C]: (A, B) => Option[C] = two2none + def scalaAnyTwoToUnit[A, B]: (A, B) => Unit = two2unit + def scalaAnyThreeToUnit[A, B, C]: (A, B, C) => Unit = three2unit + def scalaAnyTwoToTrue[A, B]: (A, B) => Boolean = two2true + def scalaAnyThreeToFalse[A, B, C]: (A, B, C) => Boolean = three2false + def scalaAnyThreeToThird[A, B, C]: (A, B, C) => C = three2third.asInstanceOf[(A, B, C) => C] + def javaAnyToNone[A, B]: A => Option[B] = none + def nullFun[T] = _nullFun.asInstanceOf[Any => T] - val zeroLong = (_: Any) ⇒ 0L + val zeroLong = (_: Any) => 0L - val oneLong = (_: Any) ⇒ 1L + val oneLong = (_: Any) => 1L - val oneInt = (_: Any) ⇒ 1 + val oneInt = (_: Any) => 1 - val unitToUnit = () ⇒ () + val unitToUnit = () => () - private val _nullFun = (_: Any) ⇒ null + private val _nullFun = (_: Any) => null - private val conforms = (a: Any) ⇒ a + private val conforms = (a: Any) => a - private val unit = (_: Any) ⇒ () + private val unit = (_: Any) => () - private val none = (_: Any) ⇒ None + private val none = (_: Any) => None - private val two2none = (_: Any, _: Any) ⇒ None + private val two2none = (_: Any, _: Any) => None - private val two2true = (_: Any, _: Any) ⇒ true + private val two2true = (_: Any, _: Any) => true - private val two2unit = (_: Any, _: Any) ⇒ () + private val two2unit = (_: Any, _: Any) => () - private val three2unit = (_: Any, _: Any, _: Any) ⇒ () + private val three2unit = (_: Any, _: Any, _: Any) => () - private val three2false = (_: Any, _: Any, _: Any) ⇒ false + private val three2false = (_: Any, _: Any, _: Any) => false - private val three2third = (_: Any, _: Any, third: Any) ⇒ third + private val three2third = (_: Any, _: Any, third: Any) => third } diff --git a/akka-actor/src/main/scala/akka/util/HashCode.scala b/akka-actor/src/main/scala/akka/util/HashCode.scala index 974d621b7a..272bdef54a 100644 --- a/akka-actor/src/main/scala/akka/util/HashCode.scala +++ b/akka-actor/src/main/scala/akka/util/HashCode.scala @@ -4,8 +4,8 @@ package akka.util -import java.lang.reflect.{ Array ⇒ JArray } -import java.lang.{ Float ⇒ JFloat, Double ⇒ JDouble } +import java.lang.reflect.{ Array => JArray } +import java.lang.{ Float => JFloat, Double => JDouble } /** * Set of methods which allow easy implementation of hashCode. @@ -26,19 +26,19 @@ object HashCode { val SEED = 23 def hash(seed: Int, any: Any): Int = any match { - case value: Boolean ⇒ hash(seed, value) - case value: Char ⇒ hash(seed, value) - case value: Short ⇒ hash(seed, value) - case value: Int ⇒ hash(seed, value) - case value: Long ⇒ hash(seed, value) - case value: Float ⇒ hash(seed, value) - case value: Double ⇒ hash(seed, value) - case value: Byte ⇒ hash(seed, value) - case value: AnyRef ⇒ + case value: Boolean => hash(seed, value) + case value: Char => hash(seed, value) + case value: Short => hash(seed, value) + case value: Int => hash(seed, value) + case value: Long => hash(seed, value) + case value: Float => hash(seed, value) + case value: Double => hash(seed, value) + case value: Byte => hash(seed, value) + case value: AnyRef => var result = seed if (value eq null) result = hash(result, 0) else if (!isArray(value)) result = hash(result, value.hashCode()) - else for (id ← 0 until JArray.getLength(value)) result = hash(result, JArray.get(value, id)) // is an array + else for (id <- 0 until JArray.getLength(value)) result = hash(result, JArray.get(value, id)) // is an array result } def hash(seed: Int, value: Boolean): Int = firstTerm(seed) + (if (value) 1 else 0) diff --git a/akka-actor/src/main/scala/akka/util/Helpers.scala b/akka-actor/src/main/scala/akka/util/Helpers.scala index cfec69aa7e..bc082b44bc 100644 --- a/akka-actor/src/main/scala/akka/util/Helpers.scala +++ b/akka-actor/src/main/scala/akka/util/Helpers.scala @@ -42,8 +42,8 @@ object Helpers { */ def identityHashComparator[T <: AnyRef](comp: Comparator[T]): Comparator[T] = new Comparator[T] { def compare(a: T, b: T): Int = compareIdentityHash(a, b) match { - case 0 if a != b ⇒ comp.compare(a, b) - case x ⇒ x + case 0 if a != b => comp.compare(a, b) + case x => x } } @@ -108,7 +108,7 @@ object Helpers { * @param cond The condition to check. * @param msg The message to report if the condition isn't met. */ - @inline def requiring(cond: Boolean, msg: ⇒ Any): A = { + @inline def requiring(cond: Boolean, msg: => Any): A = { require(cond, msg) value } @@ -120,7 +120,7 @@ object Helpers { * @param cond The function used to check the `value`. * @param msg The message to report if the condition isn't met. */ - @inline def requiring(cond: A ⇒ Boolean, msg: ⇒ Any): A = { + @inline def requiring(cond: A => Boolean, msg: => Any): A = { require(cond(value), msg) value } diff --git a/akka-actor/src/main/scala/akka/util/ImmutableIntMap.scala b/akka-actor/src/main/scala/akka/util/ImmutableIntMap.scala index 05449203e4..dc52042145 100644 --- a/akka-actor/src/main/scala/akka/util/ImmutableIntMap.scala +++ b/akka-actor/src/main/scala/akka/util/ImmutableIntMap.scala @@ -72,7 +72,7 @@ import scala.annotation.tailrec * Worst case `O(n)`, creates new `ImmutableIntMap` * with the given key and value if that key is not yet present in the map. */ - final def updateIfAbsent(key: Int, value: ⇒ Int): ImmutableIntMap = + final def updateIfAbsent(key: Int, value: => Int): ImmutableIntMap = if (size > 0) { val i = indexForKey(key) if (i >= 0) this @@ -135,12 +135,12 @@ import scala.annotation.tailrec override final def toString: String = if (size < 1) "ImmutableIntMap()" - else Iterator.range(0, kvs.length - 1, 2).map(i ⇒ s"${kvs(i)} -> ${kvs(i + 1)}").mkString("ImmutableIntMap(", ", ", ")") + else Iterator.range(0, kvs.length - 1, 2).map(i => s"${kvs(i)} -> ${kvs(i + 1)}").mkString("ImmutableIntMap(", ", ", ")") override final def hashCode: Int = Arrays.hashCode(kvs) override final def equals(obj: Any): Boolean = obj match { - case other: ImmutableIntMap ⇒ Arrays.equals(kvs, other.kvs) // No need to test `this eq obj` since this is done for the kvs arrays anyway - case _ ⇒ false + case other: ImmutableIntMap => Arrays.equals(kvs, other.kvs) // No need to test `this eq obj` since this is done for the kvs arrays anyway + case _ => false } } diff --git a/akka-actor/src/main/scala/akka/util/Index.scala b/akka-actor/src/main/scala/akka/util/Index.scala index f5db16781c..b024aee039 100644 --- a/akka-actor/src/main/scala/akka/util/Index.scala +++ b/akka-actor/src/main/scala/akka/util/Index.scala @@ -17,7 +17,7 @@ import scala.collection.JavaConverters.{ asScalaIteratorConverter, collectionAsS */ class Index[K, V](val mapSize: Int, val valueComparator: Comparator[V]) { - def this(mapSize: Int, cmp: (V, V) ⇒ Int) = this(mapSize, new Comparator[V] { + def this(mapSize: Int, cmp: (V, V) => Int) = this(mapSize, new Comparator[V] { def compare(a: V, b: V): Int = cmp(a, b) }) @@ -72,10 +72,10 @@ class Index[K, V](val mapSize: Int, val valueComparator: Comparator[V]) { * @return Some(value) for the first matching value where the supplied function returns true for the given key, * if no matches it returns None */ - def findValue(key: K)(f: (V) ⇒ Boolean): Option[V] = + def findValue(key: K)(f: (V) => Boolean): Option[V] = container get key match { - case null ⇒ None - case set ⇒ set.iterator.asScala find f + case null => None + case set => set.iterator.asScala find f } /** @@ -83,16 +83,16 @@ class Index[K, V](val mapSize: Int, val valueComparator: Comparator[V]) { */ def valueIterator(key: K): scala.Iterator[V] = { container.get(key) match { - case null ⇒ Iterator.empty - case some ⇒ some.iterator.asScala + case null => Iterator.empty + case some => some.iterator.asScala } } /** * Applies the supplied function to all keys and their values */ - def foreach(fun: (K, V) ⇒ Unit): Unit = - container.entrySet.iterator.asScala foreach { e ⇒ e.getValue.iterator.asScala.foreach(fun(e.getKey, _)) } + def foreach(fun: (K, V) => Unit): Unit = + container.entrySet.iterator.asScala foreach { e => e.getValue.iterator.asScala.foreach(fun(e.getKey, _)) } /** * Returns the union of all value sets. @@ -100,8 +100,8 @@ class Index[K, V](val mapSize: Int, val valueComparator: Comparator[V]) { def values: Set[V] = { val builder = Set.newBuilder[V] for { - values ← container.values.iterator.asScala - v ← values.iterator.asScala + values <- container.values.iterator.asScala + v <- values.iterator.asScala } builder += v builder.result() } diff --git a/akka-actor/src/main/scala/akka/util/JavaDurationConverters.scala b/akka-actor/src/main/scala/akka/util/JavaDurationConverters.scala index 45c6aa5ef4..6718528317 100644 --- a/akka-actor/src/main/scala/akka/util/JavaDurationConverters.scala +++ b/akka-actor/src/main/scala/akka/util/JavaDurationConverters.scala @@ -3,7 +3,7 @@ */ package akka.util -import java.time.{ Duration ⇒ JDuration } +import java.time.{ Duration => JDuration } import scala.concurrent.duration.{ Duration, FiniteDuration } /** diff --git a/akka-actor/src/main/scala/akka/util/LineNumbers.scala b/akka-actor/src/main/scala/akka/util/LineNumbers.scala index 2d8aa14f25..5f1b3479f7 100644 --- a/akka-actor/src/main/scala/akka/util/LineNumbers.scala +++ b/akka-actor/src/main/scala/akka/util/LineNumbers.scala @@ -61,10 +61,10 @@ object LineNumbers { */ def prettyName(obj: AnyRef): String = apply(obj) match { - case NoSourceInfo ⇒ obj.getClass.getName - case UnknownSourceFormat(msg) ⇒ s"${obj.getClass.getName}($msg)" - case SourceFile(f) ⇒ s"${obj.getClass.getName}($f)" - case l: SourceFileLines ⇒ s"${obj.getClass.getPackage.getName}/$l" + case NoSourceInfo => obj.getClass.getName + case UnknownSourceFormat(msg) => s"${obj.getClass.getName}($msg)" + case SourceFile(f) => s"${obj.getClass.getName}($f)" + case l: SourceFileLines => s"${obj.getClass.getPackage.getName}/$l" } /* @@ -90,7 +90,7 @@ object LineNumbers { def apply(idx: Int): String = _fwd(idx) def apply(str: String): Int = _rev(str) - def resolve(): Unit = _xref foreach (p ⇒ put(p._1, apply(p._2))) + def resolve(): Unit = _xref foreach (p => put(p._1, apply(p._2))) def contains(str: String): Boolean = _rev contains str private def put(idx: Int, str: String): Unit = { @@ -100,48 +100,48 @@ object LineNumbers { def readOne(d: DataInputStream): Unit = (d.readByte(): @switch) match { - case 1 ⇒ // Utf8 + case 1 => // Utf8 val str = d.readUTF() put(nextIdx, str) nextIdx += 1 - case 3 ⇒ // Integer + case 3 => // Integer skip(d, 4) nextIdx += 1 - case 4 ⇒ // Float + case 4 => // Float skip(d, 4) nextIdx += 1 - case 5 ⇒ // Long + case 5 => // Long skip(d, 8) nextIdx += 2 - case 6 ⇒ // Double + case 6 => // Double skip(d, 8) nextIdx += 2 - case 7 ⇒ // Class + case 7 => // Class val other = d.readUnsignedShort() _xref = _xref.updated(nextIdx, other) nextIdx += 1 - case 8 ⇒ // String + case 8 => // String skip(d, 2) nextIdx += 1 - case 9 ⇒ // FieldRef + case 9 => // FieldRef skip(d, 4) // two shorts nextIdx += 1 - case 10 ⇒ // MethodRef + case 10 => // MethodRef skip(d, 4) // two shorts nextIdx += 1 - case 11 ⇒ // InterfaceMethodRef + case 11 => // InterfaceMethodRef skip(d, 4) // two shorts nextIdx += 1 - case 12 ⇒ // NameAndType + case 12 => // NameAndType skip(d, 4) // two shorts nextIdx += 1 - case 15 ⇒ // MethodHandle + case 15 => // MethodHandle skip(d, 3) // a byte and a short nextIdx += 1 - case 16 ⇒ // MethodType + case 16 => // MethodType skip(d, 2) nextIdx += 1 - case 18 ⇒ // InvokeDynamic + case 18 => // InvokeDynamic skip(d, 4) // two shorts nextIdx += 1 } @@ -150,8 +150,8 @@ object LineNumbers { private def forObject(obj: AnyRef): Result = getStreamForClass(obj.getClass).orElse(getStreamForLambda(obj)) match { - case None ⇒ NoSourceInfo - case Some((stream, filter)) ⇒ getInfo(stream, filter) + case None => NoSourceInfo + case Some((stream, filter)) => getInfo(stream, filter) } private def getInfo(stream: InputStream, filter: Option[String]): Result = { @@ -170,16 +170,16 @@ object LineNumbers { if (source.isEmpty) NoSourceInfo else lines match { - case None ⇒ SourceFile(source.get) - case Some((from, to)) ⇒ SourceFileLines(source.get, from, to) + case None => SourceFile(source.get) + case Some((from, to)) => SourceFileLines(source.get, from, to) } } catch { - case NonFatal(ex) ⇒ UnknownSourceFormat(s"parse error: ${ex.getMessage}") + case NonFatal(ex) => UnknownSourceFormat(s"parse error: ${ex.getMessage}") } finally { try dis.close() catch { - case ex: InterruptedException ⇒ throw ex - case NonFatal(_) ⇒ // ignore + case ex: InterruptedException => throw ex + case NonFatal(_) => // ignore } } } @@ -189,7 +189,7 @@ object LineNumbers { val cl = c.getClassLoader val r = cl.getResourceAsStream(resource) if (debug) println(s"LNB: resource '$resource' resolved to stream $r") - Option(r).map(_ → None) + Option(r).map(_ -> None) } private def getStreamForLambda(l: AnyRef): Option[(InputStream, Some[String])] = @@ -198,14 +198,14 @@ object LineNumbers { val writeReplace = c.getDeclaredMethod("writeReplace") writeReplace.setAccessible(true) writeReplace.invoke(l) match { - case serialized: SerializedLambda ⇒ + case serialized: SerializedLambda => if (debug) println(s"LNB: found Lambda implemented in ${serialized.getImplClass}:${serialized.getImplMethodName}") Option(c.getClassLoader.getResourceAsStream(serialized.getImplClass + ".class")) .map(_ -> Some(serialized.getImplMethodName)) - case _ ⇒ None + case _ => None } } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => if (debug) ex.printStackTrace() None } @@ -240,7 +240,7 @@ object LineNumbers { private def skipInterfaceInfo(d: DataInputStream)(implicit c: Constants): Unit = { val count = d.readUnsignedShort() - for (_ ← 1 to count) { + for (_ <- 1 to count) { val intf = d.readUnsignedShort() if (debug) println(s"LNB: implements ${c(intf)}") } @@ -249,7 +249,7 @@ object LineNumbers { private def skipFields(d: DataInputStream)(implicit c: Constants): Unit = { val count = d.readUnsignedShort() if (debug) println(s"LNB: reading $count fields:") - for (_ ← 1 to count) skipMethodOrField(d) + for (_ <- 1 to count) skipMethodOrField(d) } private def skipMethodOrField(d: DataInputStream)(implicit c: Constants): Unit = { @@ -257,7 +257,7 @@ object LineNumbers { val name = d.readUnsignedShort() // name skip(d, 2) // signature val attributes = d.readUnsignedShort() - for (_ ← 1 to attributes) skipAttribute(d) + for (_ <- 1 to attributes) skipAttribute(d) if (debug) println(s"LNB: ${c(name)} ($attributes attributes)") } @@ -271,15 +271,15 @@ object LineNumbers { val count = d.readUnsignedShort() if (debug) println(s"LNB: reading $count methods") if (c.contains("Code") && c.contains("LineNumberTable")) { - (1 to count).map(_ ⇒ readMethod(d, c("Code"), c("LineNumberTable"), filter)).flatten.foldLeft(Int.MaxValue → 0) { - case ((low, high), (start, end)) ⇒ (Math.min(low, start), Math.max(high, end)) + (1 to count).map(_ => readMethod(d, c("Code"), c("LineNumberTable"), filter)).flatten.foldLeft(Int.MaxValue -> 0) { + case ((low, high), (start, end)) => (Math.min(low, start), Math.max(high, end)) } match { - case (Int.MaxValue, 0) ⇒ None - case other ⇒ Some(other) + case (Int.MaxValue, 0) => None + case other => Some(other) } } else { if (debug) println(s"LNB: (skipped)") - for (_ ← 1 to count) skipMethodOrField(d) + for (_ <- 1 to count) skipMethodOrField(d) None } } @@ -294,7 +294,7 @@ object LineNumbers { skip(d, 2) // signature if (debug) println(s"LNB: ${c(name)}") val attributes = - for (_ ← 1 to d.readUnsignedShort()) yield { + for (_ <- 1 to d.readUnsignedShort()) yield { val tag = d.readUnsignedShort() val length = d.readInt() if (tag != codeTag || (filter.isDefined && c(name) != filter.get)) { @@ -306,7 +306,7 @@ object LineNumbers { // skip exception table: N records of 4 shorts (start PC, end PC, handler PC, catch type) skip(d, 8 * d.readUnsignedShort()) val possibleLines = - for (_ ← 1 to d.readUnsignedShort()) yield { + for (_ <- 1 to d.readUnsignedShort()) yield { val tag = d.readUnsignedShort() val length = d.readInt() if (tag != lineNumberTableTag) { @@ -314,11 +314,11 @@ object LineNumbers { None } else { val lines = - for (_ ← 1 to d.readUnsignedShort()) yield { + for (_ <- 1 to d.readUnsignedShort()) yield { skip(d, 2) // start PC d.readUnsignedShort() // finally: the line number } - Some(lines.min → lines.max) + Some(lines.min -> lines.max) } } if (debug) println(s"LNB: nested attributes yielded: $possibleLines") @@ -334,7 +334,7 @@ object LineNumbers { if (c contains "SourceFile") { val s = c("SourceFile") val attributes = - for (_ ← 1 to count) yield { + for (_ <- 1 to count) yield { val tag = d.readUnsignedShort() val length = d.readInt() if (debug) println(s"LNB: tag ${c(tag)} ($length bytes)") diff --git a/akka-actor/src/main/scala/akka/util/LockUtil.scala b/akka-actor/src/main/scala/akka/util/LockUtil.scala index ab686f0d28..3204104f79 100644 --- a/akka-actor/src/main/scala/akka/util/LockUtil.scala +++ b/akka-actor/src/main/scala/akka/util/LockUtil.scala @@ -10,7 +10,7 @@ import java.util.concurrent.atomic.{ AtomicBoolean } final class ReentrantGuard extends ReentrantLock { @inline - final def withGuard[T](body: ⇒ T): T = { + final def withGuard[T](body: => T): T = { lock() try body finally unlock() } @@ -22,10 +22,10 @@ final class ReentrantGuard extends ReentrantLock { class Switch(startAsOn: Boolean = false) { private val switch = new AtomicBoolean(startAsOn) // FIXME switch to AQS - protected def transcend(from: Boolean, action: ⇒ Unit): Boolean = synchronized { + protected def transcend(from: Boolean, action: => Unit): Boolean = synchronized { if (switch.compareAndSet(from, !from)) { try action catch { - case t: Throwable ⇒ + case t: Throwable => switch.compareAndSet(!from, from) // revert status throw t } @@ -38,14 +38,14 @@ class Switch(startAsOn: Boolean = false) { * Only executes the action if the switch is on, and switches it off immediately after obtaining the lock * Will switch it back on if the provided action throws an exception */ - def switchOff(action: ⇒ Unit): Boolean = transcend(from = true, action) + def switchOff(action: => Unit): Boolean = transcend(from = true, action) /** * Executes the provided action if the lock is off under a lock, so be _very_ careful with longrunning/blocking operations in it * Only executes the action if the switch is off, and switches it on immediately after obtaining the lock * Will switch it back off if the provided action throws an exception */ - def switchOn(action: ⇒ Unit): Boolean = transcend(from = false, action) + def switchOn(action: => Unit): Boolean = transcend(from = false, action) /** * Switches the switch off (if on), uses locking @@ -60,17 +60,17 @@ class Switch(startAsOn: Boolean = false) { /** * Executes the provided action and returns its value if the switch is IMMEDIATELY on (i.e. no lock involved) */ - def ifOnYield[T](action: ⇒ T): Option[T] = if (switch.get) Some(action) else None + def ifOnYield[T](action: => T): Option[T] = if (switch.get) Some(action) else None /** * Executes the provided action and returns its value if the switch is IMMEDIATELY off (i.e. no lock involved) */ - def ifOffYield[T](action: ⇒ T): Option[T] = if (!switch.get) Some(action) else None + def ifOffYield[T](action: => T): Option[T] = if (!switch.get) Some(action) else None /** * Executes the provided action and returns if the action was executed or not, if the switch is IMMEDIATELY on (i.e. no lock involved) */ - def ifOn(action: ⇒ Unit): Boolean = { + def ifOn(action: => Unit): Boolean = { if (switch.get) { action true @@ -80,7 +80,7 @@ class Switch(startAsOn: Boolean = false) { /** * Executes the provided action and returns if the action was executed or not, if the switch is IMMEDIATELY off (i.e. no lock involved) */ - def ifOff(action: ⇒ Unit): Boolean = { + def ifOff(action: => Unit): Boolean = { if (!switch.get) { action true @@ -91,19 +91,19 @@ class Switch(startAsOn: Boolean = false) { * Executes the provided action and returns its value if the switch is on, waiting for any pending changes to happen before (locking) * Be careful of longrunning or blocking within the provided action as it can lead to deadlocks or bad performance */ - def whileOnYield[T](action: ⇒ T): Option[T] = synchronized { if (switch.get) Some(action) else None } + def whileOnYield[T](action: => T): Option[T] = synchronized { if (switch.get) Some(action) else None } /** * Executes the provided action and returns its value if the switch is off, waiting for any pending changes to happen before (locking) * Be careful of longrunning or blocking within the provided action as it can lead to deadlocks or bad performance */ - def whileOffYield[T](action: ⇒ T): Option[T] = synchronized { if (!switch.get) Some(action) else None } + def whileOffYield[T](action: => T): Option[T] = synchronized { if (!switch.get) Some(action) else None } /** * Executes the provided action and returns if the action was executed or not, if the switch is on, waiting for any pending changes to happen before (locking) * Be careful of longrunning or blocking within the provided action as it can lead to deadlocks or bad performance */ - def whileOn(action: ⇒ Unit): Boolean = synchronized { + def whileOn(action: => Unit): Boolean = synchronized { if (switch.get) { action true @@ -114,7 +114,7 @@ class Switch(startAsOn: Boolean = false) { * Executes the provided action and returns if the action was executed or not, if the switch is off, waiting for any pending changes to happen before (locking) * Be careful of longrunning or blocking within the provided action as it can lead to deadlocks or bad performance */ - def whileOff(action: ⇒ Unit): Boolean = synchronized { + def whileOff(action: => Unit): Boolean = synchronized { if (!switch.get) { action true @@ -125,12 +125,12 @@ class Switch(startAsOn: Boolean = false) { * Executes the provided callbacks depending on if the switch is either on or off waiting for any pending changes to happen before (locking) * Be careful of longrunning or blocking within the provided action as it can lead to deadlocks or bad performance */ - def fold[T](on: ⇒ T)(off: ⇒ T): T = synchronized { if (switch.get) on else off } + def fold[T](on: => T)(off: => T): T = synchronized { if (switch.get) on else off } /** * Executes the given code while holding this switch’s lock, i.e. protected from concurrent modification of the switch status. */ - def locked[T](code: ⇒ T): T = synchronized { code } + def locked[T](code: => T): T = synchronized { code } /** * Returns whether the switch is IMMEDIATELY on (no locking) diff --git a/akka-actor/src/main/scala/akka/util/ManifestInfo.scala b/akka-actor/src/main/scala/akka/util/ManifestInfo.scala index 5882a93961..27b8342560 100644 --- a/akka-actor/src/main/scala/akka/util/ManifestInfo.scala +++ b/akka-actor/src/main/scala/akka/util/ManifestInfo.scala @@ -59,7 +59,7 @@ object ManifestInfo extends ExtensionId[ManifestInfo] with ExtensionIdProvider { numbers(numbersPos) = segments(segmentPos).toInt segmentPos += 1 } catch { - case _: NumberFormatException ⇒ + case _: NumberFormatException => // This means that we have a trailing part on the version string and // less than 3 numbers, so we assume that this is a "newer" version numbers(numbersPos) = Integer.MAX_VALUE @@ -90,8 +90,8 @@ object ManifestInfo extends ExtensionId[ManifestInfo] with ExtensionIdProvider { } override def equals(o: Any): Boolean = o match { - case v: Version ⇒ compareTo(v) == 0 - case _ ⇒ false + case v: Version => compareTo(v) == 0 + case _ => false } override def hashCode(): Int = { @@ -130,16 +130,16 @@ final class ManifestInfo(val system: ExtendedActorSystem) extends Extension { val manifest = new Manifest(ios) val attributes = manifest.getMainAttributes val title = attributes.getValue(new Attributes.Name(ImplTitle)) match { - case null ⇒ attributes.getValue(new Attributes.Name(BundleName)) - case t ⇒ t + case null => attributes.getValue(new Attributes.Name(BundleName)) + case t => t } val version = attributes.getValue(new Attributes.Name(ImplVersion)) match { - case null ⇒ attributes.getValue(new Attributes.Name(BundleVersion)) - case v ⇒ v + case null => attributes.getValue(new Attributes.Name(BundleVersion)) + case v => v } val vendor = attributes.getValue(new Attributes.Name(ImplVendor)) match { - case null ⇒ attributes.getValue(new Attributes.Name(BundleVendor)) - case v ⇒ v + case null => attributes.getValue(new Attributes.Name(BundleVendor)) + case v => v } if (title != null @@ -153,7 +153,7 @@ final class ManifestInfo(val system: ExtendedActorSystem) extends Extension { } } } catch { - case ioe: IOException ⇒ + case ioe: IOException => Logging(system, getClass).warning("Could not read manifest information. {}", ioe) } manifests @@ -168,7 +168,7 @@ final class ManifestInfo(val system: ExtendedActorSystem) extends Extension { if (values.size > 1) { if (logWarning) { val conflictingVersions = values.mkString(", ") - val fullInfo = filteredVersions.map { case (k, v) ⇒ s"$k:$v" }.mkString(", ") + val fullInfo = filteredVersions.map { case (k, v) => s"$k:$v" }.mkString(", ") val highestVersion = values.max Logging(system, getClass).warning( "Detected possible incompatible versions on the classpath. " + diff --git a/akka-actor/src/main/scala/akka/util/MessageBuffer.scala b/akka-actor/src/main/scala/akka/util/MessageBuffer.scala index 6963a0ee22..1c7404072b 100644 --- a/akka-actor/src/main/scala/akka/util/MessageBuffer.scala +++ b/akka-actor/src/main/scala/akka/util/MessageBuffer.scala @@ -95,7 +95,7 @@ final class MessageBuffer private ( * * @param f the function to apply to each element */ - def foreach(f: (Any, ActorRef) ⇒ Unit): Unit = { + def foreach(f: (Any, ActorRef) => Unit): Unit = { var node = _head while (node ne null) { node(f) @@ -110,12 +110,12 @@ final class MessageBuffer private ( * * @param f the function to apply to each element */ - def forEach(f: Procedure2[Any, ActorRef]): Unit = foreach { case (message, ref) ⇒ f(message, ref) } + def forEach(f: Procedure2[Any, ActorRef]): Unit = foreach { case (message, ref) => f(message, ref) } } object MessageBuffer { private final class Node(var next: Node, val message: Any, val ref: ActorRef) { - def apply(f: (Any, ActorRef) ⇒ Unit): Unit = { + def apply(f: (Any, ActorRef) => Unit): Unit = { f(message, ref) } } @@ -134,7 +134,7 @@ object MessageBuffer { * @tparam I (Id type) */ final class MessageBufferMap[I] { - import java.{ util ⇒ jutil } + import java.{ util => jutil } private val bufferMap = new jutil.HashMap[I, MessageBuffer] @@ -236,7 +236,7 @@ final class MessageBufferMap[I] { * * @param f the function to apply to each element */ - def foreach(f: (I, MessageBuffer) ⇒ Unit): Unit = { + def foreach(f: (I, MessageBuffer) => Unit): Unit = { val entries = bufferMap.entrySet().iterator() while (entries.hasNext) { val entry = entries.next() @@ -251,5 +251,5 @@ final class MessageBufferMap[I] { * * @param f the function to apply to each element */ - def forEach(f: Procedure2[I, MessageBuffer]): Unit = foreach { case (id, buffer) ⇒ f(id, buffer) } + def forEach(f: Procedure2[I, MessageBuffer]): Unit = foreach { case (id, buffer) => f(id, buffer) } } diff --git a/akka-actor/src/main/scala/akka/util/PrettyDuration.scala b/akka-actor/src/main/scala/akka/util/PrettyDuration.scala index 49a1486a26..0c9280e586 100644 --- a/akka-actor/src/main/scala/akka/util/PrettyDuration.scala +++ b/akka-actor/src/main/scala/akka/util/PrettyDuration.scala @@ -33,16 +33,16 @@ private[akka] object PrettyDuration { require(precision > 0, "precision must be > 0") duration match { - case d: FiniteDuration ⇒ + case d: FiniteDuration => val nanos = d.toNanos val unit = chooseUnit(nanos) val value = nanos.toDouble / NANOSECONDS.convert(1, unit) s"%.${precision}g %s%s".formatLocal(Locale.ROOT, value, abbreviate(unit), if (includeNanos) s" ($nanos ns)" else "") - case Duration.MinusInf ⇒ s"-∞ (minus infinity)" - case Duration.Inf ⇒ s"∞ (infinity)" - case _ ⇒ "undefined" + case Duration.MinusInf => s"-∞ (minus infinity)" + case Duration.Inf => s"∞ (infinity)" + case _ => "undefined" } } @@ -59,13 +59,13 @@ private[akka] object PrettyDuration { } def abbreviate(unit: TimeUnit): String = unit match { - case NANOSECONDS ⇒ "ns" - case MICROSECONDS ⇒ "μs" - case MILLISECONDS ⇒ "ms" - case SECONDS ⇒ "s" - case MINUTES ⇒ "min" - case HOURS ⇒ "h" - case DAYS ⇒ "d" + case NANOSECONDS => "ns" + case MICROSECONDS => "μs" + case MILLISECONDS => "ms" + case SECONDS => "s" + case MINUTES => "min" + case HOURS => "h" + case DAYS => "d" } } diff --git a/akka-actor/src/main/scala/akka/util/Reflect.scala b/akka-actor/src/main/scala/akka/util/Reflect.scala index 82999df85e..16c94ae591 100644 --- a/akka-actor/src/main/scala/akka/util/Reflect.scala +++ b/akka-actor/src/main/scala/akka/util/Reflect.scala @@ -27,13 +27,13 @@ private[akka] object Reflect { * * Hint: when comparing to Thread.currentThread.getStackTrace, add two levels. */ - val getCallerClass: Option[Int ⇒ Class[_]] = { + val getCallerClass: Option[Int => Class[_]] = { try { val c = Class.forName("sun.reflect.Reflection") val m = c.getMethod("getCallerClass", Array(classOf[Int]): _*) - Some((i: Int) ⇒ m.invoke(null, Array[AnyRef](i.asInstanceOf[java.lang.Integer]): _*).asInstanceOf[Class[_]]) + Some((i: Int) => m.invoke(null, Array[AnyRef](i.asInstanceOf[java.lang.Integer]): _*).asInstanceOf[Class[_]]) } catch { - case NonFatal(_) ⇒ None + case NonFatal(_) => None } } @@ -43,7 +43,7 @@ private[akka] object Reflect { * @return a new instance from the default constructor of the given class */ private[akka] def instantiate[T](clazz: Class[T]): T = try clazz.newInstance catch { - case _: IllegalAccessException ⇒ + case _: IllegalAccessException => val ctor = clazz.getDeclaredConstructor() ctor.setAccessible(true) ctor.newInstance() @@ -65,7 +65,7 @@ private[akka] object Reflect { constructor.setAccessible(true) try constructor.newInstance(args.asInstanceOf[Seq[AnyRef]]: _*) catch { - case e: IllegalArgumentException ⇒ + case e: IllegalArgumentException => val argString = args map safeGetClass mkString ("[", ", ", "]") throw new IllegalArgumentException(s"constructor $constructor is incompatible with arguments $argString", e) } @@ -87,11 +87,11 @@ private[akka] object Reflect { else { val length = args.length val candidates = - clazz.getDeclaredConstructors.asInstanceOf[Array[Constructor[T]]].iterator filter { c ⇒ + clazz.getDeclaredConstructors.asInstanceOf[Array[Constructor[T]]].iterator filter { c => val parameterTypes = c.getParameterTypes parameterTypes.length == length && (parameterTypes.iterator zip args.iterator forall { - case (found, required) ⇒ + case (found, required) => found.isInstance(required) || BoxedType(found).isInstance(required) || (required == null && !found.isPrimitive) }) @@ -115,19 +115,19 @@ private[akka] object Reflect { * @param clazz the class which to instantiate an instance of * @return a function which when applied will create a new instance from the default constructor of the given class */ - private[akka] def instantiator[T](clazz: Class[T]): () ⇒ T = () ⇒ instantiate(clazz) + private[akka] def instantiator[T](clazz: Class[T]): () => T = () => instantiate(clazz) def findMarker(root: Class[_], marker: Class[_]): Type = { @tailrec def rec(curr: Class[_]): Type = { if (curr.getSuperclass != null && marker.isAssignableFrom(curr.getSuperclass)) rec(curr.getSuperclass) else curr.getGenericInterfaces collectFirst { - case c: Class[_] if marker isAssignableFrom c ⇒ c - case t: ParameterizedType if marker isAssignableFrom t.getRawType.asInstanceOf[Class[_]] ⇒ t + case c: Class[_] if marker isAssignableFrom c => c + case t: ParameterizedType if marker isAssignableFrom t.getRawType.asInstanceOf[Class[_]] => t } match { - case None ⇒ throw new IllegalArgumentException(s"cannot find [$marker] in ancestors of [$root]") - case Some(c: Class[_]) ⇒ if (c == marker) c else rec(c) - case Some(t: ParameterizedType) ⇒ if (t.getRawType == marker) t else rec(t.getRawType.asInstanceOf[Class[_]]) - case _ ⇒ ??? // cannot happen due to collectFirst + case None => throw new IllegalArgumentException(s"cannot find [$marker] in ancestors of [$root]") + case Some(c: Class[_]) => if (c == marker) c else rec(c) + case Some(t: ParameterizedType) => if (t.getRawType == marker) t else rec(t.getRawType.asInstanceOf[Class[_]]) + case _ => ??? // cannot happen due to collectFirst } } rec(root) @@ -150,8 +150,8 @@ private[akka] object Reflect { clearFirst(clazz.getDeclaredFields, 0) || { clazz.getSuperclass match { - case null ⇒ false // clazz == classOf[AnyRef] - case sc ⇒ lookupAndSetField(sc, instance, name, value) + case null => false // clazz == classOf[AnyRef] + case sc => lookupAndSetField(sc, instance, name, value) } } } @@ -160,16 +160,16 @@ private[akka] object Reflect { * INTERNAL API */ private[akka] def findClassLoader(): ClassLoader = { - def findCaller(get: Int ⇒ Class[_]): ClassLoader = - Iterator.from(2 /*is the magic number, promise*/ ).map(get) dropWhile { c ⇒ + def findCaller(get: Int => Class[_]): ClassLoader = + Iterator.from(2 /*is the magic number, promise*/ ).map(get) dropWhile { c => c != null && (c.getName.startsWith("akka.actor.ActorSystem") || c.getName.startsWith("scala.Option") || c.getName.startsWith("scala.collection.Iterator") || c.getName.startsWith("akka.util.Reflect")) } next () match { - case null ⇒ getClass.getClassLoader - case c ⇒ c.getClassLoader + case null => getClass.getClassLoader + case c => c.getClassLoader } Option(Thread.currentThread.getContextClassLoader) orElse diff --git a/akka-actor/src/main/scala/akka/util/SerializedSuspendableExecutionContext.scala b/akka-actor/src/main/scala/akka/util/SerializedSuspendableExecutionContext.scala index 2c96120e3c..647e10ba83 100644 --- a/akka-actor/src/main/scala/akka/util/SerializedSuspendableExecutionContext.scala +++ b/akka-actor/src/main/scala/akka/util/SerializedSuspendableExecutionContext.scala @@ -17,8 +17,8 @@ private[akka] object SerializedSuspendableExecutionContext { def apply(throughput: Int)(implicit context: ExecutionContext): SerializedSuspendableExecutionContext = new SerializedSuspendableExecutionContext(throughput)(context match { - case s: SerializedSuspendableExecutionContext ⇒ s.context - case other ⇒ other + case s: SerializedSuspendableExecutionContext => s.context + case other => other }) } @@ -63,9 +63,9 @@ private[akka] final class SerializedSuspendableExecutionContext(throughput: Int) @tailrec def run(done: Int): Unit = if (done < throughput && state.get == On) { poll() match { - case null ⇒ () - case some ⇒ - try some.run() catch { case NonFatal(t) ⇒ context reportFailure t } + case null => () + case some => + try some.run() catch { case NonFatal(t) => context reportFailure t } run(done + 1) } } @@ -83,9 +83,9 @@ private[akka] final class SerializedSuspendableExecutionContext(throughput: Int) final def size(): Int = count() override final def toString: String = (state.get: @switch) match { - case 0 ⇒ "Off" - case 1 ⇒ "On" - case 2 ⇒ "Off & Suspended" - case 3 ⇒ "On & Suspended" + case 0 => "Off" + case 1 => "On" + case 2 => "Off & Suspended" + case 3 => "On & Suspended" } } diff --git a/akka-actor/src/main/scala/akka/util/SubclassifiedIndex.scala b/akka-actor/src/main/scala/akka/util/SubclassifiedIndex.scala index 05c5854022..8f37162664 100644 --- a/akka-actor/src/main/scala/akka/util/SubclassifiedIndex.scala +++ b/akka-actor/src/main/scala/akka/util/SubclassifiedIndex.scala @@ -96,7 +96,7 @@ private[akka] class SubclassifiedIndex[K, V] private (protected var values: Set[ protected def innerAddKey(key: K): Changes = { var found = false - val ch = subkeys flatMap { n ⇒ + val ch = subkeys flatMap { n => if (sc.isEqual(key, n.key)) { found = true Nil @@ -120,7 +120,7 @@ private[akka] class SubclassifiedIndex[K, V] private (protected var values: Set[ protected def innerAddValue(key: K, value: V): Changes = { var found = false - val ch = subkeys flatMap { n ⇒ + val ch = subkeys flatMap { n => if (sc.isSubclass(key, n.key)) { found = true n.innerAddValue(key, value) @@ -129,7 +129,7 @@ private[akka] class SubclassifiedIndex[K, V] private (protected var values: Set[ if (!found) { val v = values + value val n = new Nonroot(root, key, v) - integrate(n) ++ n.innerAddValue(key, value) :+ (key → v) + integrate(n) ++ n.innerAddValue(key, value) :+ (key -> v) } else ch } @@ -143,13 +143,13 @@ private[akka] class SubclassifiedIndex[K, V] private (protected var values: Set[ // go through the whole tree to find all values for the "changed" keys in other // parts of the tree as well, since new nodes might have been created mergeChangesByKey(innerRemoveValue(key, value)) map { - case (k, _) ⇒ (k, findValues(k)) + case (k, _) => (k, findValues(k)) } // this will return the keys and values to be removed from the cache protected def innerRemoveValue(key: K, value: V): Changes = { var found = false - val ch = subkeys flatMap { n ⇒ + val ch = subkeys flatMap { n => if (sc.isSubclass(key, n.key)) { found = true n.innerRemoveValue(key, value) @@ -173,7 +173,7 @@ private[akka] class SubclassifiedIndex[K, V] private (protected var values: Set[ */ protected final def findValues(key: K): Set[V] = root.innerFindValues(key) protected def innerFindValues(key: K): Set[V] = - subkeys.foldLeft(Set.empty[V]) { (s, n) ⇒ + subkeys.foldLeft(Set.empty[V]) { (s, n) => if (sc.isSubclass(key, n.key)) s ++ n.innerFindValues(key) else @@ -185,10 +185,10 @@ private[akka] class SubclassifiedIndex[K, V] private (protected var values: Set[ */ protected final def findSubKeysExcept(key: K, except: Vector[Nonroot[K, V]]): Set[K] = root.innerFindSubKeys(key, except) protected def innerFindSubKeys(key: K, except: Vector[Nonroot[K, V]]): Set[K] = - subkeys.foldLeft(Set.empty[K]) { (s, n) ⇒ + subkeys.foldLeft(Set.empty[K]) { (s, n) => if (sc.isEqual(key, n.key)) s else n.innerFindSubKeys(key, except) ++ { - if (sc.isSubclass(n.key, key) && !except.exists(e ⇒ sc.isEqual(key, e.key))) + if (sc.isSubclass(n.key, key) && !except.exists(e => sc.isEqual(key, e.key))) s + n.key else s @@ -202,15 +202,15 @@ private[akka] class SubclassifiedIndex[K, V] private (protected var values: Set[ * Also needs to find subkeys in other parts of the tree to compensate for multiple inheritance. */ private def integrate(n: Nonroot[K, V]): Changes = { - val (subsub, sub) = subkeys partition (k ⇒ sc.isSubclass(k.key, n.key)) + val (subsub, sub) = subkeys partition (k => sc.isSubclass(k.key, n.key)) subkeys = sub :+ n n.subkeys = if (subsub.nonEmpty) subsub else n.subkeys - n.subkeys ++= findSubKeysExcept(n.key, n.subkeys).map(k ⇒ new Nonroot(root, k, values)) - n.subkeys.map(n ⇒ (n.key, n.values.toSet)) + n.subkeys ++= findSubKeysExcept(n.key, n.subkeys).map(k => new Nonroot(root, k, values)) + n.subkeys.map(n => (n.key, n.values.toSet)) } private def mergeChangesByKey(changes: Changes): Changes = changes.foldLeft(emptyMergeMap[K, V]) { - case (m, (k, s)) ⇒ m.updated(k, m(k) ++ s) + case (m, (k, s)) => m.updated(k, m(k) ++ s) }.to(immutable.Seq) } diff --git a/akka-actor/src/main/scala/akka/util/TypedMultiMap.scala b/akka-actor/src/main/scala/akka/util/TypedMultiMap.scala index 7d727c2422..278275c330 100644 --- a/akka-actor/src/main/scala/akka/util/TypedMultiMap.scala +++ b/akka-actor/src/main/scala/akka/util/TypedMultiMap.scala @@ -43,8 +43,8 @@ class TypedMultiMap[T <: AnyRef, K[_ <: T]] private (private val map: Map[T, Set */ def inserted(key: T)(value: K[key.type]): TypedMultiMap[T, K] = { val set = map.get(key) match { - case Some(s) ⇒ s - case None ⇒ Set.empty[Any] + case Some(s) => s + case None => Set.empty[Any] } new TypedMultiMap[T, K](map.updated(key, set + value)) } @@ -54,8 +54,8 @@ class TypedMultiMap[T <: AnyRef, K[_ <: T]] private (private val map: Map[T, Set */ def get(key: T): Set[K[key.type]] = map.get(key) match { - case Some(s) ⇒ s.asInstanceOf[Set[K[key.type]]] - case None ⇒ Set.empty + case Some(s) => s.asInstanceOf[Set[K[key.type]]] + case None => Set.empty } /** @@ -64,7 +64,7 @@ class TypedMultiMap[T <: AnyRef, K[_ <: T]] private (private val map: Map[T, Set def valueRemoved(value: Any): TypedMultiMap[T, K] = { val s = Set(value) val m = map.collect { - case (k, set) if set != s ⇒ (k, set - value) + case (k, set) if set != s => (k, set - value) } new TypedMultiMap[T, K](m) } @@ -79,8 +79,8 @@ class TypedMultiMap[T <: AnyRef, K[_ <: T]] private (private val map: Map[T, Set */ def removed(key: T)(value: K[key.type]): TypedMultiMap[T, K] = { map.get(key) match { - case None ⇒ this - case Some(set) ⇒ + case None => this + case Some(set) => if (set(value)) { val newset = set - value val newmap = if (newset.isEmpty) map - key else map.updated(key, newset) @@ -102,8 +102,8 @@ class TypedMultiMap[T <: AnyRef, K[_ <: T]] private (private val map: Map[T, Set override def toString: String = s"TypedMultiMap($map)" override def equals(other: Any) = other match { - case o: TypedMultiMap[_, _] ⇒ map == o.map - case _ ⇒ false + case o: TypedMultiMap[_, _] => map == o.map + case _ => false } override def hashCode: Int = map.hashCode } diff --git a/akka-actor/src/main/scala/akka/util/WildcardIndex.scala b/akka-actor/src/main/scala/akka/util/WildcardIndex.scala index 8b781707c2..dc79f9f468 100644 --- a/akka-actor/src/main/scala/akka/util/WildcardIndex.scala +++ b/akka-actor/src/main/scala/akka/util/WildcardIndex.scala @@ -10,9 +10,9 @@ import scala.collection.immutable.HashMap private[akka] final case class WildcardIndex[T](wildcardTree: WildcardTree[T] = WildcardTree[T](), doubleWildcardTree: WildcardTree[T] = WildcardTree[T]()) { def insert(elems: Array[String], d: T): WildcardIndex[T] = elems.lastOption match { - case Some("**") ⇒ copy(doubleWildcardTree = doubleWildcardTree.insert(elems.iterator, d)) - case Some(_) ⇒ copy(wildcardTree = wildcardTree.insert(elems.iterator, d)) - case _ ⇒ this + case Some("**") => copy(doubleWildcardTree = doubleWildcardTree.insert(elems.iterator, d)) + case Some(_) => copy(wildcardTree = wildcardTree.insert(elems.iterator, d)) + case _ => this } def find(elems: Iterable[String]): Option[T] = @@ -56,10 +56,10 @@ private[akka] final case class WildcardTree[T](data: Option[T] = None, children: if (!elems.hasNext) this else { children.get(elems.next()) match { - case Some(branch) ⇒ branch.findWithSingleWildcard(elems) - case None ⇒ children.get("*") match { - case Some(branch) ⇒ branch.findWithSingleWildcard(elems) - case None ⇒ WildcardTree[T]() + case Some(branch) => branch.findWithSingleWildcard(elems) + case None => children.get("*") match { + case Some(branch) => branch.findWithSingleWildcard(elems) + case None => WildcardTree[T]() } } } @@ -69,10 +69,10 @@ private[akka] final case class WildcardTree[T](data: Option[T] = None, children: else { val newAlt = children.getOrElse("**", alt) children.get(elems.next()) match { - case Some(branch) ⇒ branch.findWithTerminalDoubleWildcard(elems, newAlt) - case None ⇒ children.get("*") match { - case Some(branch) ⇒ branch.findWithTerminalDoubleWildcard(elems, newAlt) - case None ⇒ newAlt + case Some(branch) => branch.findWithTerminalDoubleWildcard(elems, newAlt) + case None => children.get("*") match { + case Some(branch) => branch.findWithTerminalDoubleWildcard(elems, newAlt) + case None => newAlt } } } diff --git a/akka-agent/src/main/scala/akka/agent/Agent.scala b/akka-agent/src/main/scala/akka/agent/Agent.scala index 62b40f67bd..b8ece0e6b3 100644 --- a/akka-agent/src/main/scala/akka/agent/Agent.scala +++ b/akka-agent/src/main/scala/akka/agent/Agent.scala @@ -35,9 +35,9 @@ object Agent { def send(newValue: T): Unit = withinTransaction(new Runnable { def run = ref.single.update(newValue) }) - def send(f: T ⇒ T): Unit = withinTransaction(new Runnable { def run = ref.single.transform(f) }) + def send(f: T => T): Unit = withinTransaction(new Runnable { def run = ref.single.transform(f) }) - def sendOff(f: T ⇒ T)(implicit ec: ExecutionContext): Unit = withinTransaction( + def sendOff(f: T => T)(implicit ec: ExecutionContext): Unit = withinTransaction( new Runnable { def run = try updater.suspend() finally ec.execute(new Runnable { def run = try ref.single.transform(f) finally updater.resume() }) @@ -45,9 +45,9 @@ object Agent { def alter(newValue: T): Future[T] = doAlter({ ref.single.update(newValue); newValue }) - def alter(f: T ⇒ T): Future[T] = doAlter(ref.single.transformAndGet(f)) + def alter(f: T => T): Future[T] = doAlter(ref.single.transformAndGet(f)) - def alterOff(f: T ⇒ T)(implicit ec: ExecutionContext): Future[T] = { + def alterOff(f: T => T)(implicit ec: ExecutionContext): Future[T] = { val result = Promise[T]() withinTransaction(new Runnable { def run = { @@ -63,31 +63,31 @@ object Agent { */ private final def withinTransaction(run: Runnable): Unit = { Txn.findCurrent match { - case Some(txn) ⇒ Txn.afterCommit(_ ⇒ updater.execute(run))(txn) - case _ ⇒ updater.execute(run) + case Some(txn) => Txn.afterCommit(_ => updater.execute(run))(txn) + case _ => updater.execute(run) } } /** * Internal helper method */ - private final def doAlter(f: ⇒ T): Future[T] = { + private final def doAlter(f: => T): Future[T] = { Txn.findCurrent match { - case Some(txn) ⇒ + case Some(txn) => val result = Promise[T]() - Txn.afterCommit(status ⇒ result completeWith Future(f)(updater))(txn) + Txn.afterCommit(status => result completeWith Future(f)(updater))(txn) result.future - case _ ⇒ Future(f)(updater) + case _ => Future(f)(updater) } } def future(): Future[T] = Future(ref.single.get)(updater) - def map[B](f: T ⇒ B): Agent[B] = Agent(f(get))(updater) + def map[B](f: T => B): Agent[B] = Agent(f(get))(updater) - def flatMap[B](f: T ⇒ Agent[B]): Agent[B] = f(get) + def flatMap[B](f: T => Agent[B]): Agent[B] = f(get) - def foreach[U](f: T ⇒ U): Unit = f(get) + def foreach[U](f: T => U): Unit = f(get) } } @@ -182,7 +182,7 @@ abstract class Agent[T] { * Dispatch a function to update the internal state. * In Java, pass in an instance of `akka.dispatch.Mapper`. */ - def send(f: T ⇒ T): Unit + def send(f: T => T): Unit /** * Dispatch a function to update the internal state but on its own thread. @@ -191,7 +191,7 @@ abstract class Agent[T] { * still be executed in order. * In Java, pass in an instance of `akka.dispatch.Mapper`. */ - def sendOff(f: T ⇒ T)(implicit ec: ExecutionContext): Unit + def sendOff(f: T => T)(implicit ec: ExecutionContext): Unit /** * Dispatch an update to the internal state, and return a Future where @@ -205,7 +205,7 @@ abstract class Agent[T] { * that new state can be obtained. * In Java, pass in an instance of `akka.dispatch.Mapper`. */ - def alter(f: T ⇒ T): Future[T] + def alter(f: T => T): Future[T] /** * Dispatch a function to update the internal state but on its own thread, @@ -215,7 +215,7 @@ abstract class Agent[T] { * still be executed in order. * In Java, pass in an instance of `akka.dispatch.Mapper`. */ - def alterOff(f: T ⇒ T)(implicit ec: ExecutionContext): Future[T] + def alterOff(f: T => T)(implicit ec: ExecutionContext): Future[T] /** * A future to the current value that will be completed after any currently @@ -228,18 +228,18 @@ abstract class Agent[T] { * Does not change the value of this agent. * In Java, pass in an instance of `akka.dispatch.Mapper`. */ - def map[B](f: T ⇒ B): Agent[B] + def map[B](f: T => B): Agent[B] /** * Flatmap this agent to a new agent, applying the function to the internal state. * Does not change the value of this agent. * In Java, pass in an instance of `akka.dispatch.Mapper`. */ - def flatMap[B](f: T ⇒ Agent[B]): Agent[B] + def flatMap[B](f: T => Agent[B]): Agent[B] /** * Applies the function to the internal state. Does not change the value of this agent. * In Java, pass in an instance of `akka.dispatch.Foreach`. */ - def foreach[U](f: T ⇒ U): Unit + def foreach[U](f: T => U): Unit } diff --git a/akka-agent/src/test/scala/akka/agent/AgentSpec.scala b/akka-agent/src/test/scala/akka/agent/AgentSpec.scala index 68a9edeab9..1cb89a008c 100644 --- a/akka-agent/src/test/scala/akka/agent/AgentSpec.scala +++ b/akka-agent/src/test/scala/akka/agent/AgentSpec.scala @@ -43,7 +43,7 @@ class AgentSpec extends AkkaSpec { val l1, l2 = new TestLatch(1) val agent = Agent("a") agent send (_ + "b") - agent.sendOff((s: String) ⇒ { l1.countDown; Await.ready(l2, timeout.duration); s + "c" }) + agent.sendOff((s: String) => { l1.countDown; Await.ready(l2, timeout.duration); s + "c" }) Await.ready(l1, timeout.duration) agent send (_ + "d") agent send countDown @@ -57,7 +57,7 @@ class AgentSpec extends AkkaSpec { val agent = Agent("a") val r1 = agent.alter(_ + "b") - val r2 = agent.alterOff(s ⇒ { l1.countDown; Await.ready(l2, timeout.duration); s + "c" }) + val r2 = agent.alterOff(s => { l1.countDown; Await.ready(l2, timeout.duration); s + "c" }) Await.ready(l1, timeout.duration) val r3 = agent.alter(_ + "d") val result = Future.sequence(Seq(r1, r2, r3)).map(_.mkString(":")) @@ -74,7 +74,7 @@ class AgentSpec extends AkkaSpec { val readTimeout = 5 seconds val agent = Agent(5) - val f1 = (i: Int) ⇒ { + val f1 = (i: Int) => { Await.ready(readLatch, readTimeout) i + 5 } @@ -90,7 +90,7 @@ class AgentSpec extends AkkaSpec { "be readable within a transaction" in { val agent = Agent(5) - val value = atomic { t ⇒ agent() } + val value = atomic { t => agent() } value should ===(5) } @@ -98,7 +98,7 @@ class AgentSpec extends AkkaSpec { val countDown = new CountDownFunction[Int] val agent = Agent(5) - atomic { t ⇒ + atomic { t => agent send (_ * 2) } agent send countDown @@ -113,11 +113,11 @@ class AgentSpec extends AkkaSpec { val agent = Agent(5) try { - atomic { t ⇒ + atomic { t => agent send (_ * 2) throw new RuntimeException("Expected failure") } - } catch { case NonFatal(_) ⇒ } + } catch { case NonFatal(_) => } agent send countDown @@ -153,7 +153,7 @@ class AgentSpec extends AkkaSpec { val agent = Agent(3) var result = 0 - for (value ← agent) { + for (value <- agent) { result += value } @@ -162,7 +162,7 @@ class AgentSpec extends AkkaSpec { "be able to be used in a 'map' for comprehension" in { val agent1 = Agent(5) - val agent2 = for (value ← agent1) yield value * 2 + val agent2 = for (value <- agent1) yield value * 2 agent1() should ===(5) agent2() should ===(10) @@ -173,8 +173,8 @@ class AgentSpec extends AkkaSpec { val agent2 = Agent(2) val agent3 = for { - value1 ← agent1 - value2 ← agent2 + value1 <- agent1 + value2 <- agent2 } yield value1 + value2 agent1() should ===(1) diff --git a/akka-bench-jmh-typed/src/main/scala/akka/BenchRunner.scala b/akka-bench-jmh-typed/src/main/scala/akka/BenchRunner.scala index 89fde0bdad..9b2b04a615 100644 --- a/akka-bench-jmh-typed/src/main/scala/akka/BenchRunner.scala +++ b/akka-bench-jmh-typed/src/main/scala/akka/BenchRunner.scala @@ -13,18 +13,18 @@ object BenchRunner { import scala.collection.JavaConverters._ val args2 = args.toList.flatMap { - case "quick" ⇒ "-i 1 -wi 1 -f1 -t1".split(" ").toList - case "full" ⇒ "-i 10 -wi 4 -f3 -t1".split(" ").toList - case "jitwatch" ⇒ "-jvmArgs=-XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation" :: Nil - case other ⇒ other :: Nil + case "quick" => "-i 1 -wi 1 -f1 -t1".split(" ").toList + case "full" => "-i 10 -wi 4 -f3 -t1".split(" ").toList + case "jitwatch" => "-jvmArgs=-XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation" :: Nil + case other => other :: Nil } val opts = new CommandLineOptions(args2: _*) val results = new Runner(opts).run() - val report = results.asScala.map { result: RunResult ⇒ + val report = results.asScala.map { result: RunResult => val bench = result.getParams.getBenchmark - val params = result.getParams.getParamsKeys.asScala.map(key ⇒ s"$key=${result.getParams.getParam(key)}").mkString("_") + val params = result.getParams.getParamsKeys.asScala.map(key => s"$key=${result.getParams.getParam(key)}").mkString("_") val score = result.getAggregatedResult.getPrimaryResult.getScore.round val unit = result.getAggregatedResult.getPrimaryResult.getScoreUnit s"\t${bench}_${params}\t$score\t$unit" diff --git a/akka-bench-jmh-typed/src/main/scala/akka/actor/typed/TypedBenchmarkActors.scala b/akka-bench-jmh-typed/src/main/scala/akka/actor/typed/TypedBenchmarkActors.scala index cf7a385e06..195c4c8b1f 100644 --- a/akka-bench-jmh-typed/src/main/scala/akka/actor/typed/TypedBenchmarkActors.scala +++ b/akka-bench-jmh-typed/src/main/scala/akka/actor/typed/TypedBenchmarkActors.scala @@ -14,13 +14,13 @@ object TypedBenchmarkActors { // we pass the respondTo actor ref into the behavior final case object Message - private def echoBehavior(respondTo: ActorRef[Message.type]): Behavior[Message.type] = Behaviors.receive { (ctx, msg) ⇒ + private def echoBehavior(respondTo: ActorRef[Message.type]): Behavior[Message.type] = Behaviors.receive { (ctx, msg) => respondTo ! Message Behaviors.same } private def echoSender(messagesPerPair: Int, onDone: ActorRef[Done], batchSize: Int, childProps: Props): Behavior[Message.type] = - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => val echo = ctx.spawn(echoBehavior(ctx.self), "echo", childProps) var left = messagesPerPair / 2 var batch = 0 @@ -39,7 +39,7 @@ object TypedBenchmarkActors { false } - Behaviors.receiveMessage { msg ⇒ + Behaviors.receiveMessage { msg => batch -= 1 if (batch <= 0 && !sendBatch()) { onDone ! Done @@ -55,9 +55,9 @@ object TypedBenchmarkActors { def echoActorsSupervisor(numMessagesPerActorPair: Int, numActors: Int, dispatcher: String, batchSize: Int, shutdownTimeout: FiniteDuration): Behavior[Start] = - Behaviors.receive { (ctx, msg) ⇒ + Behaviors.receive { (ctx, msg) => msg match { - case Start(respondTo) ⇒ + case Start(respondTo) => // note: no protection against accidentally running bench sessions in parallel val sessionBehavior = startEchoBenchSession(numMessagesPerActorPair, numActors, dispatcher, batchSize, respondTo) ctx.spawnAnonymous(sessionBehavior) @@ -70,16 +70,16 @@ object TypedBenchmarkActors { val numPairs = numActors / 2 - Behaviors.setup[Any] { ctx ⇒ + Behaviors.setup[Any] { ctx => val props = Props.empty.withDispatcherFromConfig("akka.actor." + dispatcher) - val pairs = (1 to numPairs).map { _ ⇒ + val pairs = (1 to numPairs).map { _ => ctx.spawnAnonymous(echoSender(messagesPerPair, ctx.self.narrow[Done], batchSize, props), props) } val startNanoTime = System.nanoTime() pairs.foreach(_ ! Message) var interactionsLeft = numPairs Behaviors.receiveMessage { - case Done ⇒ + case Done => interactionsLeft -= 1 if (interactionsLeft == 0) { val totalNumMessages = numPairs * messagesPerPair diff --git a/akka-bench-jmh/src/main/scala/akka/BenchRunner.scala b/akka-bench-jmh/src/main/scala/akka/BenchRunner.scala index 89fde0bdad..9b2b04a615 100644 --- a/akka-bench-jmh/src/main/scala/akka/BenchRunner.scala +++ b/akka-bench-jmh/src/main/scala/akka/BenchRunner.scala @@ -13,18 +13,18 @@ object BenchRunner { import scala.collection.JavaConverters._ val args2 = args.toList.flatMap { - case "quick" ⇒ "-i 1 -wi 1 -f1 -t1".split(" ").toList - case "full" ⇒ "-i 10 -wi 4 -f3 -t1".split(" ").toList - case "jitwatch" ⇒ "-jvmArgs=-XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation" :: Nil - case other ⇒ other :: Nil + case "quick" => "-i 1 -wi 1 -f1 -t1".split(" ").toList + case "full" => "-i 10 -wi 4 -f3 -t1".split(" ").toList + case "jitwatch" => "-jvmArgs=-XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation" :: Nil + case other => other :: Nil } val opts = new CommandLineOptions(args2: _*) val results = new Runner(opts).run() - val report = results.asScala.map { result: RunResult ⇒ + val report = results.asScala.map { result: RunResult => val bench = result.getParams.getBenchmark - val params = result.getParams.getParamsKeys.asScala.map(key ⇒ s"$key=${result.getParams.getParam(key)}").mkString("_") + val params = result.getParams.getParamsKeys.asScala.map(key => s"$key=${result.getParams.getParam(key)}").mkString("_") val score = result.getAggregatedResult.getPrimaryResult.getScore.round val unit = result.getAggregatedResult.getPrimaryResult.getScoreUnit s"\t${bench}_${params}\t$score\t$unit" diff --git a/akka-bench-jmh/src/main/scala/akka/actor/ActorCreationBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/actor/ActorCreationBenchmark.scala index dcd666796b..33c2b0b8a2 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/ActorCreationBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/ActorCreationBenchmark.scala @@ -48,6 +48,6 @@ class ActorCreationBenchmark { class MyActor extends Actor { override def receive: Receive = { - case _ ⇒ + case _ => } } diff --git a/akka-bench-jmh/src/main/scala/akka/actor/ActorPathValidationBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/actor/ActorPathValidationBenchmark.scala index 41f200bb6e..41d60da533 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/ActorPathValidationBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/ActorPathValidationBenchmark.scala @@ -12,7 +12,7 @@ import org.openjdk.jmh.annotations.Fork import org.openjdk.jmh.annotations.Measurement import org.openjdk.jmh.annotations.Mode import org.openjdk.jmh.annotations.OutputTimeUnit -import org.openjdk.jmh.annotations.{ Scope ⇒ JmhScope } +import org.openjdk.jmh.annotations.{ Scope => JmhScope } import org.openjdk.jmh.annotations.State import org.openjdk.jmh.annotations.Warmup diff --git a/akka-bench-jmh/src/main/scala/akka/actor/AffinityPoolComparativeBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/actor/AffinityPoolComparativeBenchmark.scala index 68b26af501..44dd34119e 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/AffinityPoolComparativeBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/AffinityPoolComparativeBenchmark.scala @@ -40,8 +40,8 @@ class AffinityPoolComparativeBenchmark { requireRightNumberOfCores(cores) val mailboxConf = mailbox match { - case "default" ⇒ "" - case "SingleConsumerOnlyUnboundedMailbox" ⇒ + case "default" => "" + case "SingleConsumerOnlyUnboundedMailbox" => s"""default-mailbox.mailbox-type = "${classOf[akka.dispatch.SingleConsumerOnlyUnboundedMailbox].getName}"""" } diff --git a/akka-bench-jmh/src/main/scala/akka/actor/AffinityPoolRequestResponseBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/actor/AffinityPoolRequestResponseBenchmark.scala index 4057154fa6..fbb4f6d2a9 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/AffinityPoolRequestResponseBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/AffinityPoolRequestResponseBenchmark.scala @@ -44,8 +44,8 @@ class AffinityPoolRequestResponseBenchmark { requireRightNumberOfCores(cores) val mailboxConf = mailbox match { - case "default" ⇒ "" - case "SingleConsumerOnlyUnboundedMailbox" ⇒ + case "default" => "" + case "SingleConsumerOnlyUnboundedMailbox" => s"""default-mailbox.mailbox-type = "${classOf[akka.dispatch.SingleConsumerOnlyUnboundedMailbox].getName}"""" } diff --git a/akka-bench-jmh/src/main/scala/akka/actor/BenchmarkActors.scala b/akka-bench-jmh/src/main/scala/akka/actor/BenchmarkActors.scala index 857f767c78..33d536a038 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/BenchmarkActors.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/BenchmarkActors.scala @@ -20,7 +20,7 @@ object BenchmarkActors { class PingPong(val messagesPerPair: Int, latch: CountDownLatch) extends Actor { var left = messagesPerPair / 2 def receive = { - case Message ⇒ + case Message => if (left == 0) { latch.countDown() @@ -38,7 +38,7 @@ object BenchmarkActors { class Echo extends Actor { def receive = { - case Message ⇒ + case Message => sender() ! Message } } @@ -55,7 +55,7 @@ object BenchmarkActors { private var batch = 0 def receive = { - case Message ⇒ + case Message => batch -= 1 if (batch <= 0) { if (!sendBatch()) { @@ -82,9 +82,9 @@ object BenchmarkActors { class Pipe(next: Option[ActorRef]) extends Actor { def receive = { - case Message ⇒ + case Message => if (next.isDefined) next.get forward Message - case Stop ⇒ + case Stop => context stop self if (next.isDefined) next.get forward Stop } @@ -98,7 +98,7 @@ object BenchmarkActors { val fullPathToDispatcher = "akka.actor." + dispatcher val latch = new CountDownLatch(numPairs * 2) val actors = for { - i ← (1 to numPairs).toVector + i <- (1 to numPairs).toVector } yield { val ping = system.actorOf(PingPong.props(messagesPerPair, latch).withDispatcher(fullPathToDispatcher)) val pong = system.actorOf(PingPong.props(messagesPerPair, latch).withDispatcher(fullPathToDispatcher)) @@ -109,8 +109,8 @@ object BenchmarkActors { private def initiatePingPongForPairs(refs: Vector[(ActorRef, ActorRef)], inFlight: Int) = { for { - (ping, pong) ← refs - _ ← 1 to inFlight + (ping, pong) <- refs + _ <- 1 to inFlight } { ping.tell(Message, pong) } @@ -121,7 +121,7 @@ object BenchmarkActors { val fullPathToDispatcher = "akka.actor." + dispatcher val latch = new CountDownLatch(numPairs) - val actors = (1 to numPairs).map { _ ⇒ + val actors = (1 to numPairs).map { _ => system.actorOf(EchoSender.props(messagesPerPair, latch, batchSize).withDispatcher(fullPathToDispatcher)) }.toVector (actors, latch) diff --git a/akka-bench-jmh/src/main/scala/akka/actor/RequestResponseActors.scala b/akka-bench-jmh/src/main/scala/akka/actor/RequestResponseActors.scala index 7c38fe0698..737a752e6d 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/RequestResponseActors.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/RequestResponseActors.scala @@ -21,7 +21,7 @@ object RequestResponseActors { private val randGenerator = new Random() override def receive: Receive = { - case u: User ⇒ { + case u: User => { receivedUsers.put(u.userId, u) if (left == 0) { latch.countDown() @@ -43,10 +43,10 @@ object RequestResponseActors { class UserServiceActor(userDb: Map[Int, User], latch: CountDownLatch, numQueries: Int) extends Actor { private var left = numQueries def receive = { - case Request(id) ⇒ + case Request(id) => userDb.get(id) match { - case Some(u) ⇒ sender() ! u - case None ⇒ + case Some(u) => sender() ! u + case None => } if (left == 0) { latch.countDown() @@ -61,11 +61,11 @@ object RequestResponseActors { def props(latch: CountDownLatch, numQueries: Int, numUsersInDB: Int) = { val r = new Random() val users = for { - id ← 0 until numUsersInDB + id <- 0 until numUsersInDB firstName = r.nextString(5) lastName = r.nextString(7) ssn = r.nextInt() - friendIds = for { _ ← 0 until 5 } yield r.nextInt(numUsersInDB) + friendIds = for { _ <- 0 until 5 } yield r.nextInt(numUsersInDB) } yield id -> User(id, firstName, lastName, ssn, friendIds) Props(new UserServiceActor(users.toMap, latch, numQueries)) } @@ -75,7 +75,7 @@ object RequestResponseActors { val fullPathToDispatcher = "akka.actor." + dispatcher val latch = new CountDownLatch(numActors) val actorsPairs = for { - i ← (1 to (numActors / 2)).toVector + i <- (1 to (numActors / 2)).toVector userQueryActor = system.actorOf(UserQueryActor.props(latch, numQueriesPerActor, numUsersInDBPerActor).withDispatcher(fullPathToDispatcher)) userServiceActor = system.actorOf(UserServiceActor.props(latch, numQueriesPerActor, numUsersInDBPerActor).withDispatcher(fullPathToDispatcher)) } yield (userQueryActor, userServiceActor) @@ -84,8 +84,8 @@ object RequestResponseActors { def initiateQuerySimulation(requestResponseActorPairs: Seq[(ActorRef, ActorRef)], inFlight: Int) = { for { - (queryActor, serviceActor) ← requestResponseActorPairs - i ← 1 to inFlight + (queryActor, serviceActor) <- requestResponseActorPairs + i <- 1 to inFlight } { serviceActor.tell(Request(i), queryActor) } diff --git a/akka-bench-jmh/src/main/scala/akka/actor/ScheduleBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/actor/ScheduleBenchmark.scala index dcbe7302b1..0aa9be291f 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/ScheduleBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/ScheduleBenchmark.scala @@ -78,7 +78,7 @@ class ScheduleBenchmark { if (idx <= to) op(idx) } promise.future.onComplete { - case _ ⇒ + case _ => tryWithNext.cancel() } Await.result(promise.future, within) @@ -87,13 +87,13 @@ class ScheduleBenchmark { @Benchmark def multipleScheduleOnce(): Unit = { val tryWithNext = (1 to to).foldLeft(0.millis -> List[Cancellable]()) { - case ((interv, c), idx) ⇒ + case ((interv, c), idx) => (interv + interval, scheduler.scheduleOnce(interv) { op(idx) } :: c) }._2 promise.future.onComplete { - case _ ⇒ + case _ => tryWithNext.foreach(_.cancel()) } Await.result(promise.future, within) diff --git a/akka-bench-jmh/src/main/scala/akka/actor/StashCreationBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/actor/StashCreationBenchmark.scala index f336d601af..b784b56d62 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/StashCreationBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/StashCreationBenchmark.scala @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit object StashCreationBenchmark { class StashingActor extends Actor with Stash { def receive = { - case msg ⇒ sender() ! msg + case msg => sender() ! msg } } diff --git a/akka-bench-jmh/src/main/scala/akka/actor/TellOnlyBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/actor/TellOnlyBenchmark.scala index c9b070b639..b6e94b1ea0 100644 --- a/akka-bench-jmh/src/main/scala/akka/actor/TellOnlyBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/actor/TellOnlyBenchmark.scala @@ -97,9 +97,9 @@ object TellOnlyBenchmark { class Echo extends Actor { def receive = { - case s @ `stop` ⇒ + case s @ `stop` => context stop self - case m ⇒ sender ! m + case m => sender ! m } } @@ -134,8 +134,8 @@ object TellOnlyBenchmark { val mbox = receiver.mailbox mbox.enqueue(receiver.self, invocation) mbox.messageQueue match { - case mb: DroppingMessageQueue if mb.dropping ⇒ // do nothing - case _ ⇒ registerForExecution(mbox, true, false) + case mb: DroppingMessageQueue if mb.dropping => // do nothing + case _ => registerForExecution(mbox, true, false) } } } diff --git a/akka-bench-jmh/src/main/scala/akka/cluster/ddata/ORSetMergeBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/cluster/ddata/ORSetMergeBenchmark.scala index dc1439b8dc..447dff70cb 100644 --- a/akka-bench-jmh/src/main/scala/akka/cluster/ddata/ORSetMergeBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/cluster/ddata/ORSetMergeBenchmark.scala @@ -11,7 +11,7 @@ import org.openjdk.jmh.annotations.Fork import org.openjdk.jmh.annotations.Measurement import org.openjdk.jmh.annotations.Mode import org.openjdk.jmh.annotations.OutputTimeUnit -import org.openjdk.jmh.annotations.{ Scope ⇒ JmhScope } +import org.openjdk.jmh.annotations.{ Scope => JmhScope } import org.openjdk.jmh.annotations.State import org.openjdk.jmh.annotations.Warmup import akka.cluster.UniqueAddress @@ -50,7 +50,7 @@ class ORSetMergeBenchmark { @Setup(Level.Trial) def setup(): Unit = { - set1 = (1 to set1Size).foldLeft(ORSet.empty[String])((s, n) ⇒ s.add(nextNode(), "elem" + n)) + set1 = (1 to set1Size).foldLeft(ORSet.empty[String])((s, n) => s.add(nextNode(), "elem" + n)) addFromSameNode = set1.add(nodeA, "elem" + set1Size + 1).merge(set1) addFromOtherNode = set1.add(nodeB, "elem" + set1Size + 1).merge(set1) complex1 = set1.add(nodeB, "a").add(nodeC, "b").remove(nodeD, "elem" + set1Size).merge(set1) diff --git a/akka-bench-jmh/src/main/scala/akka/cluster/ddata/ORSetSerializationBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/cluster/ddata/ORSetSerializationBenchmark.scala index 88bfb88808..a24604dd98 100644 --- a/akka-bench-jmh/src/main/scala/akka/cluster/ddata/ORSetSerializationBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/cluster/ddata/ORSetSerializationBenchmark.scala @@ -25,7 +25,7 @@ import org.openjdk.jmh.annotations.OutputTimeUnit import org.openjdk.jmh.annotations.State import org.openjdk.jmh.annotations.TearDown import org.openjdk.jmh.annotations.Warmup -import org.openjdk.jmh.annotations.{ Scope ⇒ JmhScope } +import org.openjdk.jmh.annotations.{ Scope => JmhScope } @Fork(2) @State(JmhScope.Benchmark) @@ -50,12 +50,12 @@ class ORSetSerializationBenchmark { private val system1 = ActorSystem("ORSetSerializationBenchmark", config) private val system2 = ActorSystem("ORSetSerializationBenchmark", config) - private val ref1 = (1 to 10).map(n ⇒ system1.actorOf(Props.empty, s"ref1-$n")) - private val ref2 = (1 to 10).map(n ⇒ system2.actorOf(Props.empty, s"ref2-$n")) + private val ref1 = (1 to 10).map(n => system1.actorOf(Props.empty, s"ref1-$n")) + private val ref2 = (1 to 10).map(n => system2.actorOf(Props.empty, s"ref2-$n")) private val orSet = { - val set1 = ref1.foldLeft(ORSet.empty[ActorRef]) { case (acc, r) ⇒ acc.add(Cluster(system1), r) } - val set2 = ref2.foldLeft(ORSet.empty[ActorRef]) { case (acc, r) ⇒ acc.add(Cluster(system2), r) } + val set1 = ref1.foldLeft(ORSet.empty[ActorRef]) { case (acc, r) => acc.add(Cluster(system1), r) } + val set2 = ref2.foldLeft(ORSet.empty[ActorRef]) { case (acc, r) => acc.add(Cluster(system2), r) } set1.merge(set2) } diff --git a/akka-bench-jmh/src/main/scala/akka/cluster/ddata/VersionVectorBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/cluster/ddata/VersionVectorBenchmark.scala index e2425717e0..4aefd4bfbe 100644 --- a/akka-bench-jmh/src/main/scala/akka/cluster/ddata/VersionVectorBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/cluster/ddata/VersionVectorBenchmark.scala @@ -11,7 +11,7 @@ import org.openjdk.jmh.annotations.Fork import org.openjdk.jmh.annotations.Measurement import org.openjdk.jmh.annotations.Mode import org.openjdk.jmh.annotations.OutputTimeUnit -import org.openjdk.jmh.annotations.{ Scope ⇒ JmhScope } +import org.openjdk.jmh.annotations.{ Scope => JmhScope } import org.openjdk.jmh.annotations.State import org.openjdk.jmh.annotations.Warmup import akka.cluster.UniqueAddress @@ -47,7 +47,7 @@ class VersionVectorBenchmark { @Setup(Level.Trial) def setup(): Unit = { - vv1 = (1 to size).foldLeft(VersionVector.empty)((vv, n) ⇒ vv + nextNode()) + vv1 = (1 to size).foldLeft(VersionVector.empty)((vv, n) => vv + nextNode()) vv2 = vv1 + nextNode() vv3 = vv1 + nextNode() dot1 = VersionVector(nodeA, vv1.versionAt(nodeA)) diff --git a/akka-bench-jmh/src/main/scala/akka/dispatch/NodeQueueBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/dispatch/NodeQueueBenchmark.scala index 5ed4dc37f7..585482351f 100644 --- a/akka-bench-jmh/src/main/scala/akka/dispatch/NodeQueueBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/dispatch/NodeQueueBenchmark.scala @@ -42,8 +42,8 @@ mailbox { implicit val sys = ActorSystem("ANQ", config) val ref = sys.actorOf(Props(new Actor { def receive = { - case Stop ⇒ sender() ! Stop - case _ ⇒ + case Stop => sender() ! Stop + case _ => } }).withDispatcher("dispatcher").withMailbox("mailbox"), "receiver") diff --git a/akka-bench-jmh/src/main/scala/akka/persistence/Common.scala b/akka-bench-jmh/src/main/scala/akka/persistence/Common.scala index b208293133..bddaae96f2 100644 --- a/akka-bench-jmh/src/main/scala/akka/persistence/Common.scala +++ b/akka-bench-jmh/src/main/scala/akka/persistence/Common.scala @@ -9,7 +9,7 @@ import akka.actor.Actor /** only as a "the best we could possibly get" baseline, does not persist anything */ class BaselineActor(respondAfter: Int) extends Actor { override def receive = { - case n: Int ⇒ if (n == respondAfter) sender() ! n + case n: Int => if (n == respondAfter) sender() ! n } } diff --git a/akka-bench-jmh/src/main/scala/akka/persistence/LevelDbBatchingBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/persistence/LevelDbBatchingBenchmark.scala index 834fd3fc1b..b9c789c5d3 100644 --- a/akka-bench-jmh/src/main/scala/akka/persistence/LevelDbBatchingBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/persistence/LevelDbBatchingBenchmark.scala @@ -103,7 +103,7 @@ class LevelDbBatchingBenchmark { "akka.persistence.journal.leveldb.dir", "akka.persistence.journal.leveldb-shared.store.dir", "akka.persistence.snapshot-store.local.dir" - ).map(s ⇒ new File(sys.settings.config.getString(s))) + ).map(s => new File(sys.settings.config.getString(s))) storageLocations.foreach(FileUtils.deleteDirectory) } diff --git a/akka-bench-jmh/src/main/scala/akka/persistence/PersistenceActorDeferBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/persistence/PersistenceActorDeferBenchmark.scala index 17ba1bb63d..71821b6e3a 100644 --- a/akka-bench-jmh/src/main/scala/akka/persistence/PersistenceActorDeferBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/persistence/PersistenceActorDeferBenchmark.scala @@ -34,7 +34,7 @@ class PersistentActorDeferBenchmark { "akka.persistence.journal.leveldb.dir", "akka.persistence.journal.leveldb-shared.store.dir", "akka.persistence.snapshot-store.local.dir" - ).map(s ⇒ new File(system.settings.config.getString(s))) + ).map(s => new File(system.settings.config.getString(s))) var system: ActorSystem = _ @@ -66,7 +66,7 @@ class PersistentActorDeferBenchmark { @Benchmark @OperationsPerInvocation(10000) def tell_persistAsync_defer_persistAsync_reply(): Unit = { - for (i ← data10k) persistAsync_defer.tell(i, probe.ref) + for (i <- data10k) persistAsync_defer.tell(i, probe.ref) probe.expectMsg(data10k.last) } @@ -74,7 +74,7 @@ class PersistentActorDeferBenchmark { @Benchmark @OperationsPerInvocation(10000) def tell_persistAsync_defer_persistAsync_replyASAP(): Unit = { - for (i ← data10k) persistAsync_defer_replyASAP.tell(i, probe.ref) + for (i <- data10k) persistAsync_defer_replyASAP.tell(i, probe.ref) probe.expectMsg(data10k.last) } @@ -86,12 +86,12 @@ class `persistAsync, defer`(respondAfter: Int) extends PersistentActor { override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ - persistAsync(Evt(n)) { e ⇒ } - deferAsync(Evt(n)) { e ⇒ if (e.i == respondAfter) sender() ! e.i } + case n: Int => + persistAsync(Evt(n)) { e => } + deferAsync(Evt(n)) { e => if (e.i == respondAfter) sender() ! e.i } } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } } class `persistAsync, defer, respond ASAP`(respondAfter: Int) extends PersistentActor { @@ -99,12 +99,12 @@ class `persistAsync, defer, respond ASAP`(respondAfter: Int) extends PersistentA override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ - persistAsync(Evt(n)) { e ⇒ } - deferAsync(Evt(n)) { e ⇒ } + case n: Int => + persistAsync(Evt(n)) { e => } + deferAsync(Evt(n)) { e => } if (n == respondAfter) sender() ! n } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } } diff --git a/akka-bench-jmh/src/main/scala/akka/persistence/PersistentActorBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/persistence/PersistentActorBenchmark.scala index 5d403e3b0b..344a1bd05e 100644 --- a/akka-bench-jmh/src/main/scala/akka/persistence/PersistentActorBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/persistence/PersistentActorBenchmark.scala @@ -23,7 +23,7 @@ class PersistentActorThroughputBenchmark { "akka.persistence.journal.leveldb.dir", "akka.persistence.journal.leveldb-shared.store.dir", "akka.persistence.snapshot-store.local.dir" - ).map(s ⇒ new File(system.settings.config.getString(s))) + ).map(s => new File(system.settings.config.getString(s))) var system: ActorSystem = _ @@ -64,7 +64,7 @@ class PersistentActorThroughputBenchmark { @Benchmark @OperationsPerInvocation(10000) def actor_normalActor_reply_baseline(): Unit = { - for (i ← data10k) actor.tell(i, probe.ref) + for (i <- data10k) actor.tell(i, probe.ref) probe.expectMsg(data10k.last) } @@ -72,7 +72,7 @@ class PersistentActorThroughputBenchmark { @Benchmark @OperationsPerInvocation(10000) def persistentActor_persist_reply(): Unit = { - for (i ← data10k) persistPersistentActor.tell(i, probe.ref) + for (i <- data10k) persistPersistentActor.tell(i, probe.ref) probe.expectMsg(Evt(data10k.last)) } @@ -80,7 +80,7 @@ class PersistentActorThroughputBenchmark { @Benchmark @OperationsPerInvocation(10000) def persistentActor_persistAsync_reply(): Unit = { - for (i ← data10k) persistAsync1PersistentActor.tell(i, probe.ref) + for (i <- data10k) persistAsync1PersistentActor.tell(i, probe.ref) probe.expectMsg(Evt(data10k.last)) } @@ -88,7 +88,7 @@ class PersistentActorThroughputBenchmark { @Benchmark @OperationsPerInvocation(10000) def persistentActor_noPersist_reply(): Unit = { - for (i ← data10k) noPersistPersistentActor.tell(i, probe.ref) + for (i <- data10k) noPersistPersistentActor.tell(i, probe.ref) probe.expectMsg(Evt(data10k.last)) } @@ -96,7 +96,7 @@ class PersistentActorThroughputBenchmark { @Benchmark @OperationsPerInvocation(10000) def persistentActor_persistAsync_replyRightOnCommandReceive(): Unit = { - for (i ← data10k) persistAsyncQuickReplyPersistentActor.tell(i, probe.ref) + for (i <- data10k) persistAsyncQuickReplyPersistentActor.tell(i, probe.ref) probe.expectMsg(Evt(data10k.last)) } @@ -108,10 +108,10 @@ class NoPersistPersistentActor(respondAfter: Int) extends PersistentActor { override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ if (n == respondAfter) sender() ! Evt(n) + case n: Int => if (n == respondAfter) sender() ! Evt(n) } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } } @@ -120,10 +120,10 @@ class PersistPersistentActor(respondAfter: Int) extends PersistentActor { override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ persist(Evt(n)) { e ⇒ if (e.i == respondAfter) sender() ! e } + case n: Int => persist(Evt(n)) { e => if (e.i == respondAfter) sender() ! e } } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } } @@ -132,11 +132,11 @@ class PersistAsyncPersistentActor(respondAfter: Int) extends PersistentActor { override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ - persistAsync(Evt(n)) { e ⇒ if (e.i == respondAfter) sender() ! e } + case n: Int => + persistAsync(Evt(n)) { e => if (e.i == respondAfter) sender() ! e } } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } } @@ -145,12 +145,12 @@ class PersistAsyncQuickReplyPersistentActor(respondAfter: Int) extends Persisten override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ + case n: Int => val e = Evt(n) if (n == respondAfter) sender() ! e persistAsync(e)(identity) } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } } diff --git a/akka-bench-jmh/src/main/scala/akka/persistence/PersistentActorWithAtLeastOnceDeliveryBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/persistence/PersistentActorWithAtLeastOnceDeliveryBenchmark.scala index b6ad6a650c..9d09c7c8fe 100644 --- a/akka-bench-jmh/src/main/scala/akka/persistence/PersistentActorWithAtLeastOnceDeliveryBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/persistence/PersistentActorWithAtLeastOnceDeliveryBenchmark.scala @@ -24,7 +24,7 @@ class PersistentActorWithAtLeastOnceDeliveryBenchmark { "akka.persistence.journal.leveldb.dir", "akka.persistence.journal.leveldb-shared.store.dir", "akka.persistence.snapshot-store.local.dir" - ).map(s ⇒ new File(system.settings.config.getString(s))) + ).map(s => new File(system.settings.config.getString(s))) var system: ActorSystem = _ @@ -63,7 +63,7 @@ class PersistentActorWithAtLeastOnceDeliveryBenchmark { @Benchmark @OperationsPerInvocation(10000) def persistentActor_persistAsync_with_AtLeastOnceDelivery(): Unit = { - for (i ← 1 to dataCount) + for (i <- 1 to dataCount) persistAsyncPersistentActorWithAtLeastOnceDelivery.tell(i, probe.ref) probe.expectMsg(20.seconds, Evt(dataCount)) } @@ -71,7 +71,7 @@ class PersistentActorWithAtLeastOnceDeliveryBenchmark { @Benchmark @OperationsPerInvocation(10000) def persistentActor_persist_with_AtLeastOnceDelivery(): Unit = { - for (i ← 1 to dataCount) + for (i <- 1 to dataCount) persistPersistentActorWithAtLeastOnceDelivery.tell(i, probe.ref) probe.expectMsg(2.minutes, Evt(dataCount)) } @@ -79,7 +79,7 @@ class PersistentActorWithAtLeastOnceDeliveryBenchmark { @Benchmark @OperationsPerInvocation(10000) def persistentActor_noPersist_with_AtLeastOnceDelivery(): Unit = { - for (i ← 1 to dataCount) + for (i <- 1 to dataCount) noPersistPersistentActorWithAtLeastOnceDelivery.tell(i, probe.ref) probe.expectMsg(20.seconds, Evt(dataCount)) } @@ -92,28 +92,28 @@ class NoPersistPersistentActorWithAtLeastOnceDelivery(respondAfter: Int, val upS override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ - deliver(downStream)(deliveryId ⇒ Msg(deliveryId, n)) + case n: Int => + deliver(downStream)(deliveryId => Msg(deliveryId, n)) if (n == respondAfter) //switch to wait all message confirmed context.become(waitConfirm) - case Confirm(deliveryId) ⇒ + case Confirm(deliveryId) => confirmDelivery(deliveryId) - case _ ⇒ // do nothing + case _ => // do nothing } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } val waitConfirm: Actor.Receive = { - case Confirm(deliveryId) ⇒ + case Confirm(deliveryId) => confirmDelivery(deliveryId) if (numberOfUnconfirmed == 0) { upStream ! Evt(respondAfter) context.unbecome() } - case _ ⇒ // do nothing + case _ => // do nothing } } @@ -124,30 +124,30 @@ class PersistPersistentActorWithAtLeastOnceDelivery(respondAfter: Int, val upStr override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ - persist(MsgSent(n)) { e ⇒ - deliver(downStream)(deliveryId ⇒ Msg(deliveryId, n)) + case n: Int => + persist(MsgSent(n)) { e => + deliver(downStream)(deliveryId => Msg(deliveryId, n)) if (n == respondAfter) //switch to wait all message confirmed context.become(waitConfirm) } - case Confirm(deliveryId) ⇒ + case Confirm(deliveryId) => confirmDelivery(deliveryId) - case _ ⇒ // do nothing + case _ => // do nothing } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } val waitConfirm: Actor.Receive = { - case Confirm(deliveryId) ⇒ + case Confirm(deliveryId) => confirmDelivery(deliveryId) if (numberOfUnconfirmed == 0) { upStream ! Evt(respondAfter) context.unbecome() } - case _ ⇒ // do nothing + case _ => // do nothing } } @@ -158,30 +158,30 @@ class PersistAsyncPersistentActorWithAtLeastOnceDelivery(respondAfter: Int, val override def persistenceId: String = self.path.name override def receiveCommand = { - case n: Int ⇒ - persistAsync(MsgSent(n)) { e ⇒ - deliver(downStream)(deliveryId ⇒ Msg(deliveryId, n)) + case n: Int => + persistAsync(MsgSent(n)) { e => + deliver(downStream)(deliveryId => Msg(deliveryId, n)) if (n == respondAfter) //switch to wait all message confirmed context.become(waitConfirm) } - case Confirm(deliveryId) ⇒ + case Confirm(deliveryId) => confirmDelivery(deliveryId) - case _ ⇒ // do nothing + case _ => // do nothing } override def receiveRecover = { - case _ ⇒ // do nothing + case _ => // do nothing } val waitConfirm: Actor.Receive = { - case Confirm(deliveryId) ⇒ + case Confirm(deliveryId) => confirmDelivery(deliveryId) if (numberOfUnconfirmed == 0) { upStream ! Evt(respondAfter) context.unbecome() } - case _ ⇒ // do nothing + case _ => // do nothing } } @@ -199,15 +199,15 @@ class DestinationActor extends Actor { var seqNr = 0L override def receive = { - case n: Int ⇒ + case n: Int => sender() ! Confirm(n) - case Msg(deliveryId, _) ⇒ + case Msg(deliveryId, _) => seqNr += 1 if (seqNr % 11 == 0) { //drop it } else { sender() ! Confirm(deliveryId) } - case _ ⇒ // do nothing + case _ => // do nothing } } diff --git a/akka-bench-jmh/src/main/scala/akka/remote/artery/BenchTestSource.scala b/akka-bench-jmh/src/main/scala/akka/remote/artery/BenchTestSource.scala index 2b3c8f9e14..811662f0be 100644 --- a/akka-bench-jmh/src/main/scala/akka/remote/artery/BenchTestSource.scala +++ b/akka-bench-jmh/src/main/scala/akka/remote/artery/BenchTestSource.scala @@ -19,7 +19,7 @@ import akka.stream.stage.OutHandler class BenchTestSource(elementCount: Int) extends GraphStage[SourceShape[java.lang.Integer]] { private val elements = new Array[java.lang.Integer](elementCount) - (1 to elementCount).map(n ⇒ elements(n - 1) = n) + (1 to elementCount).map(n => elements(n - 1) = n) val out: Outlet[java.lang.Integer] = Outlet("BenchTestSource") override val shape: SourceShape[java.lang.Integer] = SourceShape(out) diff --git a/akka-bench-jmh/src/main/scala/akka/remote/artery/CodecBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/remote/artery/CodecBenchmark.scala index 7ed4607d9a..498fe6a9bf 100644 --- a/akka-bench-jmh/src/main/scala/akka/remote/artery/CodecBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/remote/artery/CodecBenchmark.scala @@ -92,11 +92,11 @@ class CodecBenchmark { """ ) val config = configType match { - case RemoteInstrument ⇒ + case RemoteInstrument => ConfigFactory.parseString( s"""akka.remote.artery.advanced.instruments = [ "${classOf[DummyRemoteInstrument].getName}" ]""" ).withFallback(commonConfig) - case _ ⇒ + case _ => commonConfig } @@ -142,7 +142,7 @@ class CodecBenchmark { Flow.fromGraph(new Encoder(uniqueLocalAddress, system.asInstanceOf[ExtendedActorSystem], outboundEnvelopePool, envelopePool, streamId = 1, debugLogSend = false, version = ArteryTransport.HighestVersion)) val encoderInput: Flow[String, OutboundEnvelope, NotUsed] = - Flow[String].map(msg ⇒ outboundEnvelopePool.acquire().init(OptionVal.None, payload, OptionVal.Some(remoteRefB))) + Flow[String].map(msg => outboundEnvelopePool.acquire().init(OptionVal.None, payload, OptionVal.Some(remoteRefB))) val compressions = new InboundCompressionsImpl(system, inboundContext, inboundContext.settings.Advanced.Compression) val decoder: Flow[EnvelopeBuffer, InboundEnvelope, InboundCompressionAccess] = Flow.fromGraph(new Decoder(inboundContext, system.asInstanceOf[ExtendedActorSystem], @@ -150,7 +150,7 @@ class CodecBenchmark { val deserializer: Flow[InboundEnvelope, InboundEnvelope, NotUsed] = Flow.fromGraph(new Deserializer(inboundContext, system.asInstanceOf[ExtendedActorSystem], envelopePool)) val decoderInput: Flow[String, EnvelopeBuffer, NotUsed] = Flow[String] - .map { _ ⇒ + .map { _ => val envelope = envelopePool.acquire() envelopeTemplateBuffer.rewind() envelope.byteBuffer.put(envelopeTemplateBuffer) @@ -160,14 +160,14 @@ class CodecBenchmark { encodeGraph = encoderInput .via(encoder) - .map(envelope ⇒ envelopePool.release(envelope)) + .map(envelope => envelopePool.release(envelope)) decodeGraph = decoderInput .via(decoder) .via(deserializer) .map { - case env: ReusableInboundEnvelope ⇒ inboundEnvelopePool.release(env) - case _ ⇒ + case env: ReusableInboundEnvelope => inboundEnvelopePool.release(env) + case _ => } encodeDecodeGraph = encoderInput @@ -175,8 +175,8 @@ class CodecBenchmark { .via(decoder) .via(deserializer) .map { - case env: ReusableInboundEnvelope ⇒ inboundEnvelopePool.release(env) - case _ ⇒ + case env: ReusableInboundEnvelope => inboundEnvelopePool.release(env) + case _ => } } diff --git a/akka-bench-jmh/src/main/scala/akka/remote/artery/FlightRecorderBench.scala b/akka-bench-jmh/src/main/scala/akka/remote/artery/FlightRecorderBench.scala index f88083feea..0f3ce9da4d 100644 --- a/akka-bench-jmh/src/main/scala/akka/remote/artery/FlightRecorderBench.scala +++ b/akka-bench-jmh/src/main/scala/akka/remote/artery/FlightRecorderBench.scala @@ -46,7 +46,7 @@ class FlightRecorderBench { @OperationsPerInvocation(10000000) def flight_recorder_writes(): Unit = { val latch = new CountDownLatch(writers) - (1 to writers).foreach { _ ⇒ + (1 to writers).foreach { _ => val sink = recorder.createEventSink() new Thread { override def run(): Unit = { diff --git a/akka-bench-jmh/src/main/scala/akka/remote/artery/SendQueueBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/remote/artery/SendQueueBenchmark.scala index 719bede5c1..dc41041255 100644 --- a/akka-bench-jmh/src/main/scala/akka/remote/artery/SendQueueBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/remote/artery/SendQueueBenchmark.scala @@ -110,7 +110,7 @@ class SendQueueBenchmark { val burstSize = 1000 val queue = new ManyToOneConcurrentArrayQueue[Int](1024) - val source = Source.fromGraph(new SendQueue[Int](_ ⇒ ())) + val source = Source.fromGraph(new SendQueue[Int](_ => ())) val (sendQueue, killSwitch) = source.viaMat(KillSwitches.single)(Keep.both) .toMat(new BarrierSink(N, latch, burstSize, barrier))(Keep.left).run()(materializer) diff --git a/akka-bench-jmh/src/main/scala/akka/remote/artery/compress/CountMinSketchBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/remote/artery/compress/CountMinSketchBenchmark.scala index 6f825cb12d..4136cf4fb4 100644 --- a/akka-bench-jmh/src/main/scala/akka/remote/artery/compress/CountMinSketchBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/remote/artery/compress/CountMinSketchBenchmark.scala @@ -32,7 +32,7 @@ class CountMinSketchBenchmark { @Setup def init(): Unit = { countMinSketch = new CountMinSketch(d, w, seed) - (0 to 8191).foreach { index ⇒ + (0 to 8191).foreach { index => preallocateIds(index) = rand.nextInt() preallocateValues(index) = Math.abs(rand.nextInt()) } diff --git a/akka-bench-jmh/src/main/scala/akka/stream/FlatMapConcatBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/FlatMapConcatBenchmark.scala index bae6344828..db2564e3b2 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/FlatMapConcatBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/FlatMapConcatBenchmark.scala @@ -76,7 +76,7 @@ class FlatMapConcatBenchmark { val latch = new CountDownLatch(1) testSource - .flatMapConcat(elem ⇒ new GraphStages.SingleSource(elem)) + .flatMapConcat(elem => new GraphStages.SingleSource(elem)) .runWith(new LatchSink(OperationsPerInvocation, latch))(materializer) awaitLatch(latch) @@ -88,7 +88,7 @@ class FlatMapConcatBenchmark { val latch = new CountDownLatch(1) testSource - .flatMapConcat(n ⇒ Source(n :: Nil)) + .flatMapConcat(n => Source(n :: Nil)) .runWith(new LatchSink(OperationsPerInvocation, latch))(materializer) awaitLatch(latch) @@ -100,7 +100,7 @@ class FlatMapConcatBenchmark { val latch = new CountDownLatch(1) testSource - .map(elem ⇒ elem) + .map(elem => elem) .runWith(new LatchSink(OperationsPerInvocation, latch))(materializer) awaitLatch(latch) diff --git a/akka-bench-jmh/src/main/scala/akka/stream/FlatMapMergeBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/FlatMapMergeBenchmark.scala index 2c21d2f37a..e31cf55eba 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/FlatMapMergeBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/FlatMapMergeBenchmark.scala @@ -33,11 +33,11 @@ class FlatMapMergeBenchmark { def setup(): Unit = { val source = NumberOfStreams match { // Base line: process NumberOfElements-many elements from a single source without using flatMapMerge - case 0 ⇒ createSource(NumberOfElements) + case 0 => createSource(NumberOfElements) // Stream merging: process NumberOfElements-many elements from n sources, each producing (NumberOfElements/n)-many elements - case n ⇒ + case n => val subSource = createSource(NumberOfElements / n) - Source.repeat(()).take(n).flatMapMerge(n, _ ⇒ subSource) + Source.repeat(()).take(n).flatMapMerge(n, _ => subSource) } graph = Source.fromGraph(source).toMat(Sink.ignore)(Keep.right) } diff --git a/akka-bench-jmh/src/main/scala/akka/stream/FlowMapBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/FlowMapBenchmark.scala index 4a7ccbf65f..bb68ed9912 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/FlowMapBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/FlowMapBenchmark.scala @@ -122,15 +122,15 @@ class FlowMapBenchmark { val lock = new Semaphore(1) // todo rethink what is the most lightweight way to await for a streams completion lock.acquire() - flow.runWith(Sink.onComplete(_ ⇒ lock.release()))(materializer) + flow.runWith(Sink.onComplete(_ => lock.release()))(materializer) lock.acquire() } // source setup - private def mkMaps[O, Mat](source: Source[O, Mat], count: Int)(flow: ⇒ Graph[FlowShape[O, O], _]): Source[O, Mat] = { + private def mkMaps[O, Mat](source: Source[O, Mat], count: Int)(flow: => Graph[FlowShape[O, O], _]): Source[O, Mat] = { var f = source - for (i ← 1 to count) + for (i <- 1 to count) f = f.via(flow) f } diff --git a/akka-bench-jmh/src/main/scala/akka/stream/FramingBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/FramingBenchmark.scala index 7e9a25685b..b9da316347 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/FramingBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/FramingBenchmark.scala @@ -65,8 +65,8 @@ class FramingBenchmark { def setup(): Unit = { materializer = ActorMaterializer() - val frame = List.range(0, messageSize, 1).map(_ ⇒ Random.nextPrintableChar()).mkString + "\n" - flow = Source.repeat(ByteString(List.range(0, framePerSeq, 1).map(_ ⇒ frame).mkString)).take(100000) + val frame = List.range(0, messageSize, 1).map(_ => Random.nextPrintableChar()).mkString + "\n" + flow = Source.repeat(ByteString(List.range(0, framePerSeq, 1).map(_ => frame).mkString)).take(100000) .via(Framing.delimiter(ByteString("\n"), Int.MaxValue)) } @@ -80,7 +80,7 @@ class FramingBenchmark { def framing(): Unit = { val lock = new Semaphore(1) lock.acquire() - flow.runWith(Sink.onComplete(_ ⇒ lock.release()))(materializer) + flow.runWith(Sink.onComplete(_ => lock.release()))(materializer) lock.acquire() } diff --git a/akka-bench-jmh/src/main/scala/akka/stream/FusedGraphsBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/FusedGraphsBenchmark.scala index 9547f0ce7c..3f89f5329c 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/FusedGraphsBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/FusedGraphsBenchmark.scala @@ -115,7 +115,7 @@ class FusedGraphsBenchmark { materializer = ActorMaterializer(settings) testElements = Array.fill(ElementCount)(new MutableElement(0)) - val addFunc = (x: MutableElement) ⇒ { x.value += 1; x } + val addFunc = (x: MutableElement) => { x.value += 1; x } val testSource = Source.fromGraph(new TestSource(testElements)) val testSink = Sink.fromGraph(new JitSafeCompletionLatch) @@ -178,7 +178,7 @@ class FusedGraphsBenchmark { .take(ElementCount) .map(addFunc) .map(addFunc) - .fold(new MutableElement(0))((acc, x) ⇒ { acc.value += x.value; acc }) + .fold(new MutableElement(0))((acc, x) => { acc.value += x.value; acc }) .toMat(testSink)(Keep.right) ) @@ -205,7 +205,7 @@ class FusedGraphsBenchmark { .toMat(testSink)(Keep.right) ) - val broadcastZipFlow: Flow[MutableElement, MutableElement, NotUsed] = Flow.fromGraph(GraphDSL.create() { implicit b ⇒ + val broadcastZipFlow: Flow[MutableElement, MutableElement, NotUsed] = Flow.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val bcast = b.add(Broadcast[MutableElement](2)) @@ -217,7 +217,7 @@ class FusedGraphsBenchmark { FlowShape(bcast.in, zip.out.map(_._1).outlet) }) - val balanceMergeFlow: Flow[MutableElement, MutableElement, NotUsed] = Flow.fromGraph(GraphDSL.create() { implicit b ⇒ + val balanceMergeFlow: Flow[MutableElement, MutableElement, NotUsed] = Flow.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val balance = b.add(Balance[MutableElement](2)) diff --git a/akka-bench-jmh/src/main/scala/akka/stream/InterpreterBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/InterpreterBenchmark.scala index 5594626051..c3bd93565d 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/InterpreterBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/InterpreterBenchmark.scala @@ -39,7 +39,7 @@ class InterpreterBenchmark { .connect(identities.last.out, sink) // FIXME: This should not be here, this is pure setup overhead - for (i ← (0 until identities.size - 1)) { + for (i <- (0 until identities.size - 1)) { b.connect(identities(i).out, identities(i + 1).in) } diff --git a/akka-bench-jmh/src/main/scala/akka/stream/InvokeWithFeedbackBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/InvokeWithFeedbackBenchmark.scala index e58de1c7f2..8f6413597d 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/InvokeWithFeedbackBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/InvokeWithFeedbackBenchmark.scala @@ -45,7 +45,7 @@ class InvokeWithFeedbackBenchmark { @OperationsPerInvocation(100000) @Benchmark def pass_through_100k_elements(): Unit = { - (0 to 100000).foreach { n ⇒ + (0 to 100000).foreach { n => val f = sinkQueue.pull() Await.result(sourceQueue.offer(n), waitForResult) Await.result(f, waitForResult) diff --git a/akka-bench-jmh/src/main/scala/akka/stream/MapAsyncBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/MapAsyncBenchmark.scala index 6dfd6aa041..dc8766bf9b 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/MapAsyncBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/MapAsyncBenchmark.scala @@ -70,7 +70,7 @@ class MapAsyncBenchmark { val latch = new CountDownLatch(1) testSource - .mapAsync(parallelism)(elem ⇒ if (spawn) Future(elem) else Future.successful(elem)) + .mapAsync(parallelism)(elem => if (spawn) Future(elem) else Future.successful(elem)) .runWith(new LatchSink(OperationsPerInvocation, latch))(materializer) awaitLatch(latch) @@ -82,7 +82,7 @@ class MapAsyncBenchmark { val latch = new CountDownLatch(1) testSource - .mapAsyncUnordered(parallelism)(elem ⇒ if (spawn) Future(elem) else Future.successful(elem)) + .mapAsyncUnordered(parallelism)(elem => if (spawn) Future(elem) else Future.successful(elem)) .runWith(new LatchSink(OperationsPerInvocation, latch))(materializer) awaitLatch(latch) diff --git a/akka-bench-jmh/src/main/scala/akka/stream/MaterializationBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/MaterializationBenchmark.scala index 5d883165b3..09ac0e134a 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/MaterializationBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/MaterializationBenchmark.scala @@ -16,21 +16,21 @@ import akka.Done object MaterializationBenchmark { - val flowWithMapBuilder = (numOfOperators: Int) ⇒ { + val flowWithMapBuilder = (numOfOperators: Int) => { var source = Source.single(()) - for (_ ← 1 to numOfOperators) { + for (_ <- 1 to numOfOperators) { source = source.map(identity) } source.to(Sink.ignore) } - val graphWithJunctionsGradualBuilder = (numOfJunctions: Int) ⇒ - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + val graphWithJunctionsGradualBuilder = (numOfJunctions: Int) => + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val broadcast = b.add(Broadcast[Unit](numOfJunctions)) var outlet = broadcast.out(0) - for (i ← 1 until numOfJunctions) { + for (i <- 1 until numOfJunctions) { val merge = b.add(Merge[Unit](2)) outlet ~> merge broadcast.out(i) ~> merge @@ -42,13 +42,13 @@ object MaterializationBenchmark { ClosedShape }) - val graphWithJunctionsImmediateBuilder = (numOfJunctions: Int) ⇒ - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + val graphWithJunctionsImmediateBuilder = (numOfJunctions: Int) => + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val broadcast = b.add(Broadcast[Unit](numOfJunctions)) val merge = b.add(Merge[Unit](numOfJunctions)) - for (i ← 0 until numOfJunctions) { + for (i <- 0 until numOfJunctions) { broadcast ~> merge } @@ -57,12 +57,12 @@ object MaterializationBenchmark { ClosedShape }) - val graphWithImportedFlowBuilder = (numOfFlows: Int) ⇒ - RunnableGraph.fromGraph(GraphDSL.create(Source.single(())) { implicit b ⇒ source ⇒ + val graphWithImportedFlowBuilder = (numOfFlows: Int) => + RunnableGraph.fromGraph(GraphDSL.create(Source.single(())) { implicit b => source => import GraphDSL.Implicits._ val flow = Flow[Unit].map(identity) var out: Outlet[Unit] = source.out - for (i ← 0 until numOfFlows) { + for (i <- 0 until numOfFlows) { val flowShape = b.add(flow) out ~> flowShape out = flowShape.outlet @@ -73,11 +73,11 @@ object MaterializationBenchmark { final val subStreamCount = 10000 - val subStreamBuilder: Int ⇒ RunnableGraph[Future[Unit]] = numOfOperators ⇒ { + val subStreamBuilder: Int => RunnableGraph[Future[Unit]] = numOfOperators => { val subFlow = { var flow = Flow[Unit] - for (_ ← 1 to numOfOperators) { + for (_ <- 1 to numOfOperators) { flow = flow.map(identity) } flow diff --git a/akka-bench-jmh/src/main/scala/akka/stream/NewLayoutBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/NewLayoutBenchmark.scala index d48293c8ed..ef520adc7d 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/NewLayoutBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/NewLayoutBenchmark.scala @@ -179,7 +179,7 @@ class NewLayoutBenchmark { while (current ne EmptyTraversal) { current match { - case MaterializeAtomic(mod, outToSlot) ⇒ + case MaterializeAtomic(mod, outToSlot) => var i = 0 val inletsIter = mod.shape.inlets.iterator while (inletsIter.hasNext) { @@ -196,10 +196,10 @@ class NewLayoutBenchmark { inOffs += mod.shape.inlets.size current = current.next // And that's it ;) - case Concat(first, next) ⇒ + case Concat(first, next) => traversalStack.add(next) current = first - case _ ⇒ + case _ => current = current.next } } @@ -212,7 +212,7 @@ class NewLayoutBenchmark { var downstreamPort: InPort = _ override def subscribe(s: Subscriber[_ >: Any]): Unit = s match { - case TestSubscriber(o, p) ⇒ + case TestSubscriber(o, p) => downstreamModule = o downstreamPort = p s.onSubscribe(this) @@ -227,7 +227,7 @@ class NewLayoutBenchmark { var upstreamPort: OutPort = _ override def onSubscribe(s: Subscription): Unit = s match { - case TestPublisher(o, p) ⇒ + case TestPublisher(o, p) => upstreamModule = o upstreamPort = p } @@ -244,13 +244,13 @@ class NewLayoutBenchmark { override protected def materializeAtomic(atomic: AtomicModule, effectiveAttributes: Attributes, matVal: java.util.Map[Module, Any]): Unit = { - for (inPort ← atomic.inPorts) { + for (inPort <- atomic.inPorts) { val subscriber = TestSubscriber(atomic, inPort) subscribers(i) = subscriber i += 1 assignPort(inPort, subscriber) } - for (outPort ← atomic.outPorts) { + for (outPort <- atomic.outPorts) { val publisher = TestPublisher(atomic, outPort) publishers(i) = publisher i += 1 diff --git a/akka-bench-jmh/src/main/scala/akka/stream/PartitionHubBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/PartitionHubBenchmark.scala index 68be1a7813..e27551581e 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/PartitionHubBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/PartitionHubBenchmark.scala @@ -71,11 +71,11 @@ class PartitionHubBenchmark { val source = testSource .runWith(PartitionHub.sink[java.lang.Integer]( - (size, elem) ⇒ elem.intValue % NumberOfStreams, + (size, elem) => elem.intValue % NumberOfStreams, startAfterNrOfConsumers = NumberOfStreams, bufferSize = BufferSize ))(materializer) - for (_ ← 0 until NumberOfStreams) + for (_ <- 0 until NumberOfStreams) source.runWith(new LatchSink(N / NumberOfStreams, latch))(materializer) if (!latch.await(30, TimeUnit.SECONDS)) { @@ -98,7 +98,7 @@ class PartitionHubBenchmark { )) )(materializer) - for (_ ← 0 until NumberOfStreams) + for (_ <- 0 until NumberOfStreams) source.runWith(new LatchSink(N / NumberOfStreams, latch))(materializer) if (!latch.await(30, TimeUnit.SECONDS)) { diff --git a/akka-bench-jmh/src/main/scala/akka/stream/SourceRefBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/SourceRefBenchmark.scala index 7b8cd0fd3b..fb53861f66 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/SourceRefBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/SourceRefBenchmark.scala @@ -88,7 +88,7 @@ class SourceRefBenchmark { val lock = new Semaphore(1) // todo rethink what is the most lightweight way to await for a streams completion lock.acquire() - sourceRef.source.runWith(Sink.onComplete(_ ⇒ lock.release())) + sourceRef.source.runWith(Sink.onComplete(_ => lock.release())) lock.acquire() } diff --git a/akka-bench-jmh/src/main/scala/akka/stream/io/FileSourcesBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/io/FileSourcesBenchmark.scala index 4eb2990d5e..fbd9feaf37 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/io/FileSourcesBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/io/FileSourcesBenchmark.scala @@ -33,7 +33,7 @@ class FileSourcesBenchmark { val f = Files.createTempFile(getClass.getName, ".bench.tmp") - val ft = Source.fromIterator(() ⇒ Iterator.continually(line)) + val ft = Source.fromIterator(() => Iterator.continually(line)) .take(10 * 39062) // adjust as needed .runWith(FileIO.toPath(f)) Await.result(ft, 30.seconds) @@ -51,8 +51,8 @@ class FileSourcesBenchmark { @Setup def setup(): Unit = { fileChannelSource = FileIO.fromPath(file, bufSize) - fileInputStreamSource = StreamConverters.fromInputStream(() ⇒ Files.newInputStream(file), bufSize) - ioSourceLinesIterator = Source.fromIterator(() ⇒ scala.io.Source.fromFile(file.toFile).getLines()).map(ByteString(_)) + fileInputStreamSource = StreamConverters.fromInputStream(() => Files.newInputStream(file), bufSize) + ioSourceLinesIterator = Source.fromIterator(() => scala.io.Source.fromFile(file.toFile).getLines()).map(ByteString(_)) } @TearDown diff --git a/akka-bench-jmh/src/main/scala/akka/stream/io/FileSourcesScaleBenchmark.scala b/akka-bench-jmh/src/main/scala/akka/stream/io/FileSourcesScaleBenchmark.scala index 8038ee55b8..0a51500ef0 100644 --- a/akka-bench-jmh/src/main/scala/akka/stream/io/FileSourcesScaleBenchmark.scala +++ b/akka-bench-jmh/src/main/scala/akka/stream/io/FileSourcesScaleBenchmark.scala @@ -33,10 +33,10 @@ class FileSourcesScaleBenchmark { val FILES_NUMBER = 40 val files: Seq[Path] = { val line = ByteString("x" * 2048 + "\n") - (1 to FILES_NUMBER).map(i ⇒ { + (1 to FILES_NUMBER).map(i => { val f = Files.createTempFile(getClass.getName, i + ".bench.tmp") - val ft = Source.fromIterator(() ⇒ Iterator.continually(line)) + val ft = Source.fromIterator(() => Iterator.continually(line)) .take(20000) // adjust as needed .runWith(FileIO.toPath(f)) Await.result(ft, 300.seconds) @@ -66,16 +66,16 @@ class FileSourcesScaleBenchmark { @Benchmark def flatMapMerge(): Unit = { - val h = Source.fromIterator(() ⇒ files.iterator) - .flatMapMerge(FILES_NUMBER, path ⇒ FileIO.fromPath(path, bufSize)).runWith(Sink.ignore) + val h = Source.fromIterator(() => files.iterator) + .flatMapMerge(FILES_NUMBER, path => FileIO.fromPath(path, bufSize)).runWith(Sink.ignore) Await.result(h, 300.seconds) } @Benchmark def mapAsync(): Unit = { - val h = Source.fromIterator(() ⇒ files.iterator) - .mapAsync(FILES_NUMBER)(path ⇒ FileIO.fromPath(path, bufSize).runWith(Sink.ignore)).runWith(Sink.ignore) + val h = Source.fromIterator(() => files.iterator) + .mapAsync(FILES_NUMBER)(path => FileIO.fromPath(path, bufSize).runWith(Sink.ignore)).runWith(Sink.ignore) Await.result(h, 300.seconds) } diff --git a/akka-bench-jmh/src/main/scala/akka/util/ImmutableIntMapBench.scala b/akka-bench-jmh/src/main/scala/akka/util/ImmutableIntMapBench.scala index 8778b246d7..7870af73aa 100644 --- a/akka-bench-jmh/src/main/scala/akka/util/ImmutableIntMapBench.scala +++ b/akka-bench-jmh/src/main/scala/akka/util/ImmutableIntMapBench.scala @@ -49,7 +49,7 @@ class ImmutableIntMapBench { } else from } - val odd1000 = (0 to 1000).iterator.filter(_ % 2 == 1).foldLeft(ImmutableIntMap.empty)((l, i) ⇒ l.updated(i, i)) + val odd1000 = (0 to 1000).iterator.filter(_ % 2 == 1).foldLeft(ImmutableIntMap.empty)((l, i) => l.updated(i, i)) @Benchmark @OperationsPerInvocation(1) diff --git a/akka-bench-jmh/src/main/scala/akka/util/LruBoundedCacheBench.scala b/akka-bench-jmh/src/main/scala/akka/util/LruBoundedCacheBench.scala index b17d4218ff..0d3ad10ba5 100644 --- a/akka-bench-jmh/src/main/scala/akka/util/LruBoundedCacheBench.scala +++ b/akka-bench-jmh/src/main/scala/akka/util/LruBoundedCacheBench.scala @@ -46,7 +46,7 @@ class LruBoundedCacheBench { } // Loading - for (i ← 1 to threshold) { + for (i <- 1 to threshold) { val value = random.nextString(stringSize) if (i == 1) toGet = value toRemove = value diff --git a/akka-camel/src/main/scala/akka/camel/Camel.scala b/akka-camel/src/main/scala/akka/camel/Camel.scala index 62ddf42bfd..e9dfe0ed7a 100644 --- a/akka-camel/src/main/scala/akka/camel/Camel.scala +++ b/akka-camel/src/main/scala/akka/camel/Camel.scala @@ -89,20 +89,20 @@ class CamelSettings private[camel] (config: Config, dynamicAccess: DynamicAccess final val ProducerChildDispatcher: String = config.getString("akka.camel.producer.use-dispatcher") - final val Conversions: (String, RouteDefinition) ⇒ RouteDefinition = { + final val Conversions: (String, RouteDefinition) => RouteDefinition = { val specifiedConversions = { import scala.collection.JavaConverters.asScalaSetConverter val section = config.getConfig("akka.camel.conversions") - section.entrySet.asScala.map(e ⇒ (e.getKey, section.getString(e.getKey))) + section.entrySet.asScala.map(e => (e.getKey, section.getString(e.getKey))) } val conversions = specifiedConversions.foldLeft(Map[String, Class[_ <: AnyRef]]()) { - case (m, (key, fqcn)) ⇒ + case (m, (key, fqcn)) => m.updated(key, dynamicAccess.getClassFor[AnyRef](fqcn).recover { - case e ⇒ throw new ConfigurationException("Could not find/load Camel Converter class [" + fqcn + "]", e) + case e => throw new ConfigurationException("Could not find/load Camel Converter class [" + fqcn + "]", e) }.get) } - (s: String, r: RouteDefinition) ⇒ conversions.get(s).fold(r)(r.convertBodyTo) + (s: String, r: RouteDefinition) => conversions.get(s).fold(r)(r.convertBodyTo) } /** * Configured setting, determine the class used to load/retrieve the instance of the Camel Context @@ -110,7 +110,7 @@ class CamelSettings private[camel] (config: Config, dynamicAccess: DynamicAccess final val ContextProvider: ContextProvider = { val fqcn = config.getString("akka.camel.context-provider") dynamicAccess.createInstanceFor[ContextProvider](fqcn, immutable.Seq.empty).recover { - case e ⇒ throw new ConfigurationException("Could not find/load Context Provider class [" + fqcn + "]", e) + case e => throw new ConfigurationException("Could not find/load Context Provider class [" + fqcn + "]", e) }.get } } diff --git a/akka-camel/src/main/scala/akka/camel/CamelMessage.scala b/akka-camel/src/main/scala/akka/camel/CamelMessage.scala index 380a67e920..42a689099d 100644 --- a/akka-camel/src/main/scala/akka/camel/CamelMessage.scala +++ b/akka-camel/src/main/scala/akka/camel/CamelMessage.scala @@ -4,9 +4,9 @@ package akka.camel -import java.util.{ Map ⇒ JMap, Set ⇒ JSet } +import java.util.{ Map => JMap, Set => JSet } import javax.activation.DataHandler -import org.apache.camel.{ CamelContext, Message ⇒ JCamelMessage, StreamCache } +import org.apache.camel.{ CamelContext, Message => JCamelMessage, StreamCache } import akka.AkkaException import scala.reflect.ClassTag import scala.runtime.ScalaRunTime @@ -76,7 +76,7 @@ class CamelMessage(val body: Any, val headers: Map[String, Any], val attachments * Returns a new CamelMessage with a transformed body using a transformer function. * This method will throw a [[java.lang.ClassCastException]] if the body cannot be mapped to type A. */ - def mapBody[A, B](transformer: A ⇒ B): CamelMessage = copy(body = transformer(body.asInstanceOf[A])) + def mapBody[A, B](transformer: A => B): CamelMessage = copy(body = transformer(body.asInstanceOf[A])) /** * Java API: Returns a new CamelMessage with a transformed body using a transformer function. @@ -112,8 +112,8 @@ class CamelMessage(val body: Any, val headers: Map[String, Any], val attachments * See http://camel.apache.org/stream-caching.html */ def resetStreamCache(): Unit = body match { - case stream: StreamCache ⇒ stream.reset - case _ ⇒ + case stream: StreamCache => stream.reset + case _ => } /** @@ -169,11 +169,11 @@ class CamelMessage(val body: Any, val headers: Map[String, Any], val attachments */ override def equals(that: Any): Boolean = that match { - case that: CamelMessage if canEqual(that) ⇒ + case that: CamelMessage if canEqual(that) => this.body == that.body && this.headers == that.headers && this.attachments == that.attachments - case _ ⇒ false + case _ => false } /** @@ -185,9 +185,9 @@ class CamelMessage(val body: Any, val headers: Map[String, Any], val attachments * Returns the n-th element of this product, 0-based. */ override def productElement(n: Int): Any = n match { - case 0 ⇒ body - case 1 ⇒ headers - case 2 ⇒ attachments + case 0 => body + case 1 => headers + case 2 => attachments } /** @@ -200,15 +200,15 @@ class CamelMessage(val body: Any, val headers: Map[String, Any], val attachments * This method should be called from every well-designed equals method that is open to be overridden in a subclass. */ override def canEqual(that: Any): Boolean = that match { - case _: CamelMessage ⇒ true - case _ ⇒ false + case _: CamelMessage => true + case _ => false } } /** * Companion object of CamelMessage class. */ -object CamelMessage extends ((Any, Map[String, Any]) ⇒ CamelMessage) { +object CamelMessage extends ((Any, Map[String, Any]) => CamelMessage) { /** * Returns a new CamelMessage based on the body and headers. @@ -239,8 +239,8 @@ object CamelMessage extends ((Any, Map[String, Any]) ⇒ CamelMessage) { * newly created CamelMessage object. */ private[camel] def canonicalize(msg: Any) = msg match { - case mobj: CamelMessage ⇒ mobj - case body ⇒ CamelMessage(body, Map.empty[String, Any]) + case mobj: CamelMessage => mobj + case body => CamelMessage(body, Map.empty[String, Any]) } /** @@ -269,7 +269,7 @@ object CamelMessage extends ((Any, Map[String, Any]) ⇒ CamelMessage) { */ private[camel] def copyContent(from: CamelMessage, to: JCamelMessage): Unit = { to.setBody(from.body) - for ((name, value) ← from.headers) to.getHeaders.put(name, value.asInstanceOf[AnyRef]) + for ((name, value) <- from.headers) to.getHeaders.put(name, value.asInstanceOf[AnyRef]) to.getAttachments.putAll(from.getAttachments) } } diff --git a/akka-camel/src/main/scala/akka/camel/CamelSupport.scala b/akka-camel/src/main/scala/akka/camel/CamelSupport.scala index baff9dd160..1c2592c490 100644 --- a/akka-camel/src/main/scala/akka/camel/CamelSupport.scala +++ b/akka-camel/src/main/scala/akka/camel/CamelSupport.scala @@ -6,7 +6,7 @@ package akka.camel import akka.actor.Actor -private[camel] trait CamelSupport { this: Actor ⇒ +private[camel] trait CamelSupport { this: Actor => /** * INTERNAL API diff --git a/akka-camel/src/main/scala/akka/camel/Consumer.scala b/akka-camel/src/main/scala/akka/camel/Consumer.scala index a6343e3fd6..74effbe041 100644 --- a/akka-camel/src/main/scala/akka/camel/Consumer.scala +++ b/akka-camel/src/main/scala/akka/camel/Consumer.scala @@ -63,7 +63,7 @@ trait Consumer extends Actor with CamelSupport { * return a custom route definition handler. The returned function is not allowed to close over 'this', meaning it is * not allowed to refer to the actor instance itself, since that can easily cause concurrent shared state issues. */ - def onRouteDefinition: RouteDefinition ⇒ ProcessorDefinition[_] = { + def onRouteDefinition: RouteDefinition => ProcessorDefinition[_] = { val mapper = getRouteDefinitionHandler if (mapper != identityRouteMapper) mapper.apply _ else identityRouteMapper @@ -93,10 +93,10 @@ private[camel] object Consumer { * * Was a case class but has been split up as a workaround for SI-8283 */ -private[camel] class ConsumerConfig(val activationTimeout: FiniteDuration, val replyTimeout: FiniteDuration, val autoAck: Boolean, val onRouteDefinition: RouteDefinition ⇒ ProcessorDefinition[_]) extends NoSerializationVerificationNeeded +private[camel] class ConsumerConfig(val activationTimeout: FiniteDuration, val replyTimeout: FiniteDuration, val autoAck: Boolean, val onRouteDefinition: RouteDefinition => ProcessorDefinition[_]) extends NoSerializationVerificationNeeded with scala.Serializable private[camel] object ConsumerConfig { - def apply(activationTimeout: FiniteDuration, replyTimeout: FiniteDuration, autoAck: Boolean, onRouteDefinition: RouteDefinition ⇒ ProcessorDefinition[_]): ConsumerConfig = + def apply(activationTimeout: FiniteDuration, replyTimeout: FiniteDuration, autoAck: Boolean, onRouteDefinition: RouteDefinition => ProcessorDefinition[_]): ConsumerConfig = new ConsumerConfig(activationTimeout, replyTimeout, autoAck, onRouteDefinition) } diff --git a/akka-camel/src/main/scala/akka/camel/Producer.scala b/akka-camel/src/main/scala/akka/camel/Producer.scala index 634da25892..ad7bcfc8bc 100644 --- a/akka-camel/src/main/scala/akka/camel/Producer.scala +++ b/akka-camel/src/main/scala/akka/camel/Producer.scala @@ -57,31 +57,31 @@ trait ProducerSupport extends Actor with CamelSupport { * @see Producer#produce */ protected def produce: Receive = { - case CamelProducerObjects(endpoint, processor) ⇒ + case CamelProducerObjects(endpoint, processor) => if (producerChild.isEmpty) { val disp = camel.settings.ProducerChildDispatcher match { - case "" ⇒ context.props.dispatcher - case d ⇒ d + case "" => context.props.dispatcher + case d => d } producerChild = Some(context.actorOf(Props(new ProducerChild(endpoint, processor)).withDispatcher(disp))) messages = { for ( - child ← producerChild; - (snd, msg) ← messages + child <- producerChild; + (snd, msg) <- messages ) child.tell(transformOutgoingMessage(msg), snd) Vector.empty } } - case res: MessageResult ⇒ routeResponse(res.message) - case res: FailureResult ⇒ + case res: MessageResult => routeResponse(res.message) + case res: FailureResult => val e = new AkkaCamelException(res.cause, res.headers) routeResponse(Failure(e)) throw e - case msg ⇒ + case msg => producerChild match { - case Some(child) ⇒ child forward transformOutgoingMessage(msg) - case None ⇒ messages :+= ((sender(), msg)) + case Some(child) => child forward transformOutgoingMessage(msg) + case None => messages :+= ((sender(), msg)) } } @@ -111,8 +111,8 @@ trait ProducerSupport extends Actor with CamelSupport { private class ProducerChild(endpoint: Endpoint, processor: SendProcessor) extends Actor { def receive = { - case msg @ (_: FailureResult | _: MessageResult) ⇒ context.parent forward msg - case msg ⇒ produce(endpoint, processor, msg, if (oneway) ExchangePattern.InOnly else ExchangePattern.InOut) + case msg @ (_: FailureResult | _: MessageResult) => context.parent forward msg + case msg => produce(endpoint, processor, msg, if (oneway) ExchangePattern.InOnly else ExchangePattern.InOut) } /** * Initiates a message exchange of given pattern with the endpoint specified by @@ -151,7 +151,7 @@ trait ProducerSupport extends Actor with CamelSupport { * Mixed in by Actor implementations to produce messages to Camel endpoints. */ @deprecated("Akka Camel is deprecated in favour of 'Alpakka', the Akka Streams based collection of integrations to various endpoints (including Camel).", since = "2.5.0") -trait Producer extends ProducerSupport { this: Actor ⇒ +trait Producer extends ProducerSupport { this: Actor => /** * Implementation of Actor.receive. Any messages received by this actor @@ -176,7 +176,7 @@ private final case class FailureResult(cause: Throwable, headers: Map[String, An * */ @deprecated("Akka Camel is deprecated in favour of 'Alpakka', the Akka Streams based collection of integrations to various endpoints (including Camel).", since = "2.5.0") -trait Oneway extends Producer { this: Actor ⇒ +trait Oneway extends Producer { this: Actor => override def oneway: Boolean = true } diff --git a/akka-camel/src/main/scala/akka/camel/internal/ActivationTracker.scala b/akka-camel/src/main/scala/akka/camel/internal/ActivationTracker.scala index 39e5532232..f898c93a72 100644 --- a/akka-camel/src/main/scala/akka/camel/internal/ActivationTracker.scala +++ b/akka-camel/src/main/scala/akka/camel/internal/ActivationTracker.scala @@ -31,12 +31,12 @@ private[camel] class ActivationTracker extends Actor with ActorLogging { var awaitingDeActivation = List[ActorRef]() { - case AwaitActivation(ref) ⇒ awaitingActivation ::= sender() - case AwaitDeActivation(ref) ⇒ awaitingDeActivation ::= sender() - case msg @ EndpointActivated(ref) ⇒ + case AwaitActivation(ref) => awaitingActivation ::= sender() + case AwaitDeActivation(ref) => awaitingDeActivation ::= sender() + case msg @ EndpointActivated(ref) => awaitingActivation.foreach(_ ! msg) receive = activated(awaitingDeActivation) - case EndpointFailedToActivate(ref, cause) ⇒ + case EndpointFailedToActivate(ref, cause) => awaitingActivation.foreach(_ ! EndpointFailedToActivate(ref, cause)) receive = failedToActivate(cause) } @@ -51,12 +51,12 @@ private[camel] class ActivationTracker extends Actor with ActorLogging { var awaitingDeActivation = currentAwaitingDeActivation { - case AwaitActivation(ref) ⇒ sender() ! EndpointActivated(ref) - case AwaitDeActivation(ref) ⇒ awaitingDeActivation ::= sender() - case msg @ EndpointDeActivated(ref) ⇒ + case AwaitActivation(ref) => sender() ! EndpointActivated(ref) + case AwaitDeActivation(ref) => awaitingDeActivation ::= sender() + case msg @ EndpointDeActivated(ref) => awaitingDeActivation foreach (_ ! msg) receive = deactivated - case msg @ EndpointFailedToDeActivate(ref, cause) ⇒ + case msg @ EndpointFailedToDeActivate(ref, cause) => awaitingDeActivation foreach (_ ! msg) receive = failedToDeActivate(cause) } @@ -68,10 +68,10 @@ private[camel] class ActivationTracker extends Actor with ActorLogging { */ def deactivated: State = { // deactivated means it was activated at some point, so tell sender() it was activated - case AwaitActivation(ref) ⇒ sender() ! EndpointActivated(ref) - case AwaitDeActivation(ref) ⇒ sender() ! EndpointDeActivated(ref) + case AwaitActivation(ref) => sender() ! EndpointActivated(ref) + case AwaitDeActivation(ref) => sender() ! EndpointDeActivated(ref) //resurrected at restart. - case msg @ EndpointActivated(ref) ⇒ + case msg @ EndpointActivated(ref) => receive = activated(Nil) } @@ -81,9 +81,9 @@ private[camel] class ActivationTracker extends Actor with ActorLogging { * @return a partial function that handles messages in 'failed to activate' state */ def failedToActivate(cause: Throwable): State = { - case AwaitActivation(ref) ⇒ sender() ! EndpointFailedToActivate(ref, cause) - case AwaitDeActivation(ref) ⇒ sender() ! EndpointFailedToActivate(ref, cause) - case EndpointDeActivated(_) ⇒ // the de-register at termination always sends a de-activated when the cleanup is done. ignoring. + case AwaitActivation(ref) => sender() ! EndpointFailedToActivate(ref, cause) + case AwaitDeActivation(ref) => sender() ! EndpointFailedToActivate(ref, cause) + case EndpointDeActivated(_) => // the de-register at termination always sends a de-activated when the cleanup is done. ignoring. } /** @@ -92,20 +92,20 @@ private[camel] class ActivationTracker extends Actor with ActorLogging { * @return a partial function that handles messages in 'failed to de-activate' state */ def failedToDeActivate(cause: Throwable): State = { - case AwaitActivation(ref) ⇒ sender() ! EndpointActivated(ref) - case AwaitDeActivation(ref) ⇒ sender() ! EndpointFailedToDeActivate(ref, cause) - case EndpointDeActivated(_) ⇒ // the de-register at termination always sends a de-activated when the cleanup is done. ignoring. + case AwaitActivation(ref) => sender() ! EndpointActivated(ref) + case AwaitDeActivation(ref) => sender() ! EndpointFailedToDeActivate(ref, cause) + case EndpointDeActivated(_) => // the de-register at termination always sends a de-activated when the cleanup is done. ignoring. } } override def receive = { - case msg @ ActivationMessage(ref) ⇒ + case msg @ ActivationMessage(ref) => (activations.getOrElseUpdate(ref, new ActivationStateMachine).receive orElse logStateWarning(ref))(msg) } private[this] def logStateWarning(actorRef: ActorRef): Receive = - { case msg ⇒ log.warning("Message [{}] not expected in current state of actor [{}]", msg, actorRef) } + { case msg => log.warning("Message [{}] not expected in current state of actor [{}]", msg, actorRef) } } /** diff --git a/akka-camel/src/main/scala/akka/camel/internal/CamelExchangeAdapter.scala b/akka-camel/src/main/scala/akka/camel/internal/CamelExchangeAdapter.scala index 23003181b8..d9d948c30a 100644 --- a/akka-camel/src/main/scala/akka/camel/internal/CamelExchangeAdapter.scala +++ b/akka-camel/src/main/scala/akka/camel/internal/CamelExchangeAdapter.scala @@ -5,7 +5,7 @@ package akka.camel.internal import org.apache.camel.util.ExchangeHelper -import org.apache.camel.{ Exchange, Message ⇒ JCamelMessage } +import org.apache.camel.{ Exchange, Message => JCamelMessage } import akka.camel.{ FailureResult, AkkaCamelException, CamelMessage } /** diff --git a/akka-camel/src/main/scala/akka/camel/internal/CamelSupervisor.scala b/akka-camel/src/main/scala/akka/camel/internal/CamelSupervisor.scala index cf372d4f99..bdf1ddba21 100644 --- a/akka-camel/src/main/scala/akka/camel/internal/CamelSupervisor.scala +++ b/akka-camel/src/main/scala/akka/camel/internal/CamelSupervisor.scala @@ -25,15 +25,15 @@ private[camel] class CamelSupervisor extends Actor with CamelSupport { private val registry: ActorRef = context.actorOf(Props(classOf[Registry], activationTracker), "registry") override val supervisorStrategy = OneForOneStrategy() { - case NonFatal(e) ⇒ + case NonFatal(e) => Resume } def receive = { - case AddWatch(actorRef) ⇒ context.watch(actorRef) - case Terminated(actorRef) ⇒ registry ! DeRegister(actorRef) - case msg: ActivationMessage ⇒ activationTracker forward msg - case msg ⇒ registry forward (msg) + case AddWatch(actorRef) => context.watch(actorRef) + case Terminated(actorRef) => registry ! DeRegister(actorRef) + case msg: ActivationMessage => activationTracker forward msg + case msg => registry forward (msg) } } @@ -101,46 +101,46 @@ private[camel] class Registry(activationTracker: ActorRef) extends Actor with Ca override def logFailure(context: ActorContext, child: ActorRef, cause: Throwable, decision: SupervisorStrategy.Directive): Unit = cause match { - case _: ActorActivationException | _: ActorDeActivationException ⇒ + case _: ActorActivationException | _: ActorDeActivationException => try context.system.eventStream.publish { Logging.Error(cause.getCause, child.path.toString, getClass, cause.getMessage) - } catch { case NonFatal(_) ⇒ } - case _ ⇒ super.logFailure(context, child, cause, decision) + } catch { case NonFatal(_) => } + case _ => super.logFailure(context, child, cause, decision) } } override val supervisorStrategy = new RegistryLogStrategy()({ - case e: ActorActivationException ⇒ + case e: ActorActivationException => activationTracker ! EndpointFailedToActivate(e.actorRef, e.getCause) stop(e.actorRef) Resume - case e: ActorDeActivationException ⇒ + case e: ActorDeActivationException => activationTracker ! EndpointFailedToDeActivate(e.actorRef, e.getCause) stop(e.actorRef) Resume - case NonFatal(e) ⇒ + case NonFatal(e) => Resume }) def receive = { - case msg @ Register(consumer, _, Some(_)) ⇒ + case msg @ Register(consumer, _, Some(_)) => if (!consumers(consumer)) { consumers += consumer consumerRegistrar forward msg parent ! AddWatch(consumer) } - case msg @ Register(producer, _, None) ⇒ + case msg @ Register(producer, _, None) => if (!producers(producer)) { producers += producer parent ! AddWatch(producer) } producerRegistrar forward msg - case DeRegister(actorRef) ⇒ - producers.find(_ == actorRef).foreach { p ⇒ + case DeRegister(actorRef) => + producers.find(_ == actorRef).foreach { p => deRegisterProducer(p) producers -= p } - consumers.find(_ == actorRef).foreach { c ⇒ + consumers.find(_ == actorRef).foreach { c => deRegisterConsumer(c) consumers -= c } @@ -159,31 +159,31 @@ private[camel] class ProducerRegistrar(activationTracker: ActorRef) extends Acto private var camelObjects = Map[ActorRef, (Endpoint, SendProcessor)]() def receive = { - case Register(producer, endpointUri, _) ⇒ + case Register(producer, endpointUri, _) => if (!camelObjects.contains(producer)) { try { val endpoint = camelContext.getEndpoint(endpointUri) val processor = new SendProcessor(endpoint) - camelObjects = camelObjects.updated(producer, endpoint → processor) + camelObjects = camelObjects.updated(producer, endpoint -> processor) // if this throws, the supervisor stops the producer and de-registers it on termination processor.start() producer ! CamelProducerObjects(endpoint, processor) activationTracker ! EndpointActivated(producer) } catch { - case NonFatal(e) ⇒ throw new ActorActivationException(producer, e) + case NonFatal(e) => throw new ActorActivationException(producer, e) } } else { - camelObjects.get(producer) foreach { case (endpoint, processor) ⇒ producer ! CamelProducerObjects(endpoint, processor) } + camelObjects.get(producer) foreach { case (endpoint, processor) => producer ! CamelProducerObjects(endpoint, processor) } } - case DeRegister(producer) ⇒ + case DeRegister(producer) => camelObjects.get(producer) foreach { - case (_, processor) ⇒ + case (_, processor) => try { camelObjects.get(producer).foreach(_._2.stop()) camelObjects -= producer activationTracker ! EndpointDeActivated(producer) } catch { - case NonFatal(e) ⇒ throw new ActorDeActivationException(producer, e) + case NonFatal(e) => throw new ActorDeActivationException(producer, e) } } } @@ -195,22 +195,22 @@ private[camel] class ProducerRegistrar(activationTracker: ActorRef) extends Acto */ private[camel] class ConsumerRegistrar(activationTracker: ActorRef) extends Actor with CamelSupport { def receive = { - case Register(consumer, endpointUri, Some(consumerConfig)) ⇒ + case Register(consumer, endpointUri, Some(consumerConfig)) => try { // if this throws, the supervisor stops the consumer and de-registers it on termination camelContext.addRoutes(new ConsumerActorRouteBuilder(endpointUri, consumer, consumerConfig, camel.settings)) activationTracker ! EndpointActivated(consumer) } catch { - case NonFatal(e) ⇒ throw new ActorActivationException(consumer, e) + case NonFatal(e) => throw new ActorActivationException(consumer, e) } - case DeRegister(consumer) ⇒ + case DeRegister(consumer) => try { val route = consumer.path.toString camelContext.stopRoute(route) camelContext.removeRoute(route) activationTracker ! EndpointDeActivated(consumer) } catch { - case NonFatal(e) ⇒ throw new ActorDeActivationException(consumer, e) + case NonFatal(e) => throw new ActorDeActivationException(consumer, e) } } } diff --git a/akka-camel/src/main/scala/akka/camel/internal/DefaultCamel.scala b/akka-camel/src/main/scala/akka/camel/internal/DefaultCamel.scala index 7e77fb279f..841b8953da 100644 --- a/akka-camel/src/main/scala/akka/camel/internal/DefaultCamel.scala +++ b/akka-camel/src/main/scala/akka/camel/internal/DefaultCamel.scala @@ -52,7 +52,7 @@ private[camel] class DefaultCamel(val system: ExtendedActorSystem) extends Camel */ def start(): this.type = { context.start() - try template.start() catch { case NonFatal(e) ⇒ context.stop(); throw e } + try template.start() catch { case NonFatal(e) => context.stop(); throw e } log.debug("Started CamelContext[{}] for ActorSystem[{}]", context.getName, system.name) this } @@ -66,7 +66,7 @@ private[camel] class DefaultCamel(val system: ExtendedActorSystem) extends Camel */ def shutdown(): Unit = { try context.stop() finally { - try template.stop() catch { case NonFatal(e) ⇒ log.debug("Swallowing non-fatal exception [{}] on stopping Camel producer template", e) } + try template.stop() catch { case NonFatal(e) => log.debug("Swallowing non-fatal exception [{}] on stopping Camel producer template", e) } } log.debug("Stopped CamelContext[{}] for ActorSystem[{}]", context.getName, system.name) } @@ -81,8 +81,8 @@ private[camel] class DefaultCamel(val system: ExtendedActorSystem) extends Camel def activationFutureFor(endpoint: ActorRef)(implicit timeout: Timeout, executor: ExecutionContext): Future[ActorRef] = (supervisor.ask(AwaitActivation(endpoint))(timeout)).map[ActorRef]({ - case EndpointActivated(`endpoint`) ⇒ endpoint - case EndpointFailedToActivate(`endpoint`, cause) ⇒ throw cause + case EndpointActivated(`endpoint`) => endpoint + case EndpointFailedToActivate(`endpoint`, cause) => throw cause }) /** @@ -94,7 +94,7 @@ private[camel] class DefaultCamel(val system: ExtendedActorSystem) extends Camel */ def deactivationFutureFor(endpoint: ActorRef)(implicit timeout: Timeout, executor: ExecutionContext): Future[ActorRef] = (supervisor.ask(AwaitDeActivation(endpoint))(timeout)).map[ActorRef]({ - case EndpointDeActivated(`endpoint`) ⇒ endpoint - case EndpointFailedToDeActivate(`endpoint`, cause) ⇒ throw cause + case EndpointDeActivated(`endpoint`) => endpoint + case EndpointFailedToDeActivate(`endpoint`, cause) => throw cause }) } diff --git a/akka-camel/src/main/scala/akka/camel/internal/component/ActorComponent.scala b/akka-camel/src/main/scala/akka/camel/internal/component/ActorComponent.scala index f00df76d1d..a24dcd709f 100644 --- a/akka-camel/src/main/scala/akka/camel/internal/component/ActorComponent.scala +++ b/akka-camel/src/main/scala/akka/camel/internal/component/ActorComponent.scala @@ -4,7 +4,7 @@ package akka.camel.internal.component -import java.util.{ Map ⇒ JMap } +import java.util.{ Map => JMap } import org.apache.camel._ import org.apache.camel.impl.{ DefaultProducer, DefaultEndpoint, DefaultComponent } import akka.actor._ @@ -146,22 +146,22 @@ private[camel] class ActorProducer(val endpoint: ActorEndpoint, camel: Camel) ex } else { val action: PartialFunction[Try[Any], Unit] = if (exchange.isOutCapable) { - case Success(failure: FailureResult) ⇒ exchange.setFailure(failure) - case Success(msg) ⇒ exchange.setResponse(CamelMessage.canonicalize(msg)) - case Failure(e: TimeoutException) ⇒ exchange.setFailure(FailureResult(new TimeoutException("Failed to get response from the actor [%s] within timeout [%s]. Check replyTimeout and blocking settings [%s]" format (endpoint.path, endpoint.replyTimeout, endpoint)))) - case Failure(throwable) ⇒ exchange.setFailure(FailureResult(throwable)) + case Success(failure: FailureResult) => exchange.setFailure(failure) + case Success(msg) => exchange.setResponse(CamelMessage.canonicalize(msg)) + case Failure(e: TimeoutException) => exchange.setFailure(FailureResult(new TimeoutException("Failed to get response from the actor [%s] within timeout [%s]. Check replyTimeout and blocking settings [%s]" format (endpoint.path, endpoint.replyTimeout, endpoint)))) + case Failure(throwable) => exchange.setFailure(FailureResult(throwable)) } else { - case Success(Ack) ⇒ () /* no response message to set */ - case Success(failure: FailureResult) ⇒ exchange.setFailure(failure) - case Success(msg) ⇒ exchange.setFailure(FailureResult(new IllegalArgumentException("Expected Ack or Failure message, but got: [%s] from actor [%s]" format (msg, endpoint.path)))) - case Failure(e: TimeoutException) ⇒ exchange.setFailure(FailureResult(new TimeoutException("Failed to get Ack or Failure response from the actor [%s] within timeout [%s]. Check replyTimeout and blocking settings [%s]" format (endpoint.path, endpoint.replyTimeout, endpoint)))) - case Failure(throwable) ⇒ exchange.setFailure(FailureResult(throwable)) + case Success(Ack) => () /* no response message to set */ + case Success(failure: FailureResult) => exchange.setFailure(failure) + case Success(msg) => exchange.setFailure(FailureResult(new IllegalArgumentException("Expected Ack or Failure message, but got: [%s] from actor [%s]" format (msg, endpoint.path)))) + case Failure(e: TimeoutException) => exchange.setFailure(FailureResult(new TimeoutException("Failed to get Ack or Failure response from the actor [%s] within timeout [%s]. Check replyTimeout and blocking settings [%s]" format (endpoint.path, endpoint.replyTimeout, endpoint)))) + case Failure(throwable) => exchange.setFailure(FailureResult(throwable)) } // FIXME #3074 how do we solve this with actorSelection? - val async = try actorFor(endpoint.path).ask(messageFor(exchange))(Timeout(endpoint.replyTimeout)) catch { case NonFatal(e) ⇒ Future.failed(e) } + val async = try actorFor(endpoint.path).ask(messageFor(exchange))(Timeout(endpoint.replyTimeout)) catch { case NonFatal(e) => Future.failed(e) } implicit val ec = camel.system.dispatcher // FIXME which ExecutionContext should be used here? - async.onComplete(action andThen { _ ⇒ callback.done(false) }) + async.onComplete(action andThen { _ => callback.done(false) }) false } @@ -169,13 +169,13 @@ private[camel] class ActorProducer(val endpoint: ActorEndpoint, camel: Camel) ex // FIXME #3074 how do we solve this with actorSelection? private def fireAndForget(message: CamelMessage, exchange: CamelExchangeAdapter): Unit = - try { actorFor(endpoint.path) ! message } catch { case NonFatal(e) ⇒ exchange.setFailure(new FailureResult(e)) } + try { actorFor(endpoint.path) ! message } catch { case NonFatal(e) => exchange.setFailure(new FailureResult(e)) } private[this] def actorFor(path: ActorEndpointPath): ActorRef = path.findActorIn(camel.system) getOrElse (throw new ActorNotRegisteredException(path.actorPath)) private[this] def messageFor(exchange: CamelExchangeAdapter) = - exchange.toRequestMessage(Map(CamelMessage.MessageExchangeId → exchange.getExchangeId)) + exchange.toRequestMessage(Map(CamelMessage.MessageExchangeId -> exchange.getExchangeId)) } /** @@ -189,7 +189,7 @@ private[camel] object DurationTypeConverter extends TypeConverterSupport { val d = Duration(value.toString) if (valueType.isInstance(d)) d else null } catch { - case NonFatal(throwable) ⇒ throw new TypeConversionException(value, valueType, throwable) + case NonFatal(throwable) => throw new TypeConversionException(value, valueType, throwable) }) } @@ -252,7 +252,7 @@ private[camel] case object ActorEndpointPath { * parameters can be optionally added to the actor path to indicate auto-acknowledgement and replyTimeout for a [[akka.camel.Consumer]] actor. */ def fromCamelPath(camelPath: String): ActorEndpointPath = camelPath match { - case id if id startsWith "akka://" ⇒ new ActorEndpointPath(id.split('?')(0)) - case _ ⇒ throw new IllegalArgumentException("Invalid path: [%s] - should be an actorPath starting with 'akka://', optionally followed by options" format camelPath) + case id if id startsWith "akka://" => new ActorEndpointPath(id.split('?')(0)) + case _ => throw new IllegalArgumentException("Invalid path: [%s] - should be an actorPath starting with 'akka://', optionally followed by options" format camelPath) } } diff --git a/akka-camel/src/test/scala/akka/camel/ActivationIntegrationTest.scala b/akka-camel/src/test/scala/akka/camel/ActivationIntegrationTest.scala index e2a8485ce9..0969ea0e23 100644 --- a/akka-camel/src/test/scala/akka/camel/ActivationIntegrationTest.scala +++ b/akka-camel/src/test/scala/akka/camel/ActivationIntegrationTest.scala @@ -35,7 +35,7 @@ class ActivationIntegrationTest extends WordSpec with Matchers with SharedCamelS val latch = TestLatch(1) val actor = start(new Consumer { def endpointUri = "direct:a3" - def receive = { case _ ⇒ {} } + def receive = { case _ => {} } override def postStop(): Unit = { super.postStop() @@ -75,7 +75,7 @@ class ActivationIntegrationTest extends WordSpec with Matchers with SharedCamelS } override def receive = { - case msg: CamelMessage ⇒ sender() ! "received " + msg.body + case msg: CamelMessage => sender() ! "received " + msg.body } } diff --git a/akka-camel/src/test/scala/akka/camel/CamelExchangeAdapterTest.scala b/akka-camel/src/test/scala/akka/camel/CamelExchangeAdapterTest.scala index 4acd627769..d14c859942 100644 --- a/akka-camel/src/test/scala/akka/camel/CamelExchangeAdapterTest.scala +++ b/akka-camel/src/test/scala/akka/camel/CamelExchangeAdapterTest.scala @@ -44,17 +44,17 @@ class CamelExchangeAdapterTest extends FunSuite with SharedCamelSystem { test("mustCreateRequestMessageFromInMessage") { val m = exchangeToAdapter(sampleInOnly).toRequestMessage - assert(m === CamelMessage("test-in", Map("key-in" → "val-in"))) + assert(m === CamelMessage("test-in", Map("key-in" -> "val-in"))) } test("mustCreateResponseMessageFromInMessage") { val m = exchangeToAdapter(sampleInOnly).toResponseMessage - assert(m === CamelMessage("test-in", Map("key-in" → "val-in"))) + assert(m === CamelMessage("test-in", Map("key-in" -> "val-in"))) } test("mustCreateResponseMessageFromOutMessage") { val m = exchangeToAdapter(sampleInOut).toResponseMessage - assert(m === CamelMessage("test-out", Map("key-out" → "val-out"))) + assert(m === CamelMessage("test-out", Map("key-out" -> "val-out"))) } test("mustCreateFailureMessageFromExceptionAndInMessage") { @@ -78,18 +78,18 @@ class CamelExchangeAdapterTest extends FunSuite with SharedCamelSystem { } test("mustCreateRequestMessageFromInMessageWithAdditionalHeader") { - val m = exchangeToAdapter(sampleInOnly).toRequestMessage(Map("x" → "y")) - assert(m === CamelMessage("test-in", Map("key-in" → "val-in", "x" → "y"))) + val m = exchangeToAdapter(sampleInOnly).toRequestMessage(Map("x" -> "y")) + assert(m === CamelMessage("test-in", Map("key-in" -> "val-in", "x" -> "y"))) } test("mustCreateResponseMessageFromInMessageWithAdditionalHeader") { - val m = exchangeToAdapter(sampleInOnly).toResponseMessage(Map("x" → "y")) - assert(m === CamelMessage("test-in", Map("key-in" → "val-in", "x" → "y"))) + val m = exchangeToAdapter(sampleInOnly).toResponseMessage(Map("x" -> "y")) + assert(m === CamelMessage("test-in", Map("key-in" -> "val-in", "x" -> "y"))) } test("mustCreateResponseMessageFromOutMessageWithAdditionalHeader") { - val m = exchangeToAdapter(sampleInOut).toResponseMessage(Map("x" → "y")) - assert(m === CamelMessage("test-out", Map("key-out" → "val-out", "x" → "y"))) + val m = exchangeToAdapter(sampleInOut).toResponseMessage(Map("x" -> "y")) + assert(m === CamelMessage("test-out", Map("key-out" -> "val-out", "x" -> "y"))) } test("mustCreateFailureMessageFromExceptionAndInMessageWithAdditionalHeader") { @@ -97,13 +97,13 @@ class CamelExchangeAdapterTest extends FunSuite with SharedCamelSystem { e1.setException(new Exception("test1")) val a1 = exchangeToAdapter(e1) assert(a1.toAkkaCamelException.getMessage === "test1") - val headers = a1.toAkkaCamelException(Map("x" → "y")).headers + val headers = a1.toAkkaCamelException(Map("x" -> "y")).headers assert(headers("key-in") === "val-in") assert(headers("x") === "y") val a2 = exchangeToAdapter(e1) assert(a2.toFailureMessage.cause.getMessage === "test1") - val failureHeaders = a2.toFailureResult(Map("x" → "y")).headers + val failureHeaders = a2.toFailureResult(Map("x" -> "y")).headers assert(failureHeaders("key-in") === "val-in") assert(failureHeaders("x") === "y") @@ -114,13 +114,13 @@ class CamelExchangeAdapterTest extends FunSuite with SharedCamelSystem { e1.setException(new Exception("test2")) val a1 = exchangeToAdapter(e1) assert(a1.toAkkaCamelException.getMessage === "test2") - val headers = a1.toAkkaCamelException(Map("x" → "y")).headers + val headers = a1.toAkkaCamelException(Map("x" -> "y")).headers assert(headers("key-out") === "val-out") assert(headers("x") === "y") val a2 = exchangeToAdapter(e1) assert(a2.toFailureMessage.cause.getMessage === "test2") - val failureHeaders = a2.toFailureResult(Map("x" → "y")).headers + val failureHeaders = a2.toFailureResult(Map("x" -> "y")).headers assert(failureHeaders("key-out") === "val-out") assert(failureHeaders("x") === "y") } diff --git a/akka-camel/src/test/scala/akka/camel/CamelMessageTest.scala b/akka-camel/src/test/scala/akka/camel/CamelMessageTest.scala index fe0415dbed..823eec24ed 100644 --- a/akka-camel/src/test/scala/akka/camel/CamelMessageTest.scala +++ b/akka-camel/src/test/scala/akka/camel/CamelMessageTest.scala @@ -25,7 +25,7 @@ class CamelMessageTest extends Matchers with WordSpecLike with SharedCamelSystem message.setExchange(new DefaultExchange(camel.context)) val attachmentToAdd = new DataHandler(new URL("https://another.url")) - CamelMessage.copyContent(new CamelMessage("body", Map("key" → "baz"), Map("key" → attachmentToAdd)), message) + CamelMessage.copyContent(new CamelMessage("body", Map("key" -> "baz"), Map("key" -> attachmentToAdd)), message) assert(message.getBody === "body") assert(message.getHeader("foo") === "bar") diff --git a/akka-camel/src/test/scala/akka/camel/ConcurrentActivationTest.scala b/akka-camel/src/test/scala/akka/camel/ConcurrentActivationTest.scala index 10ea2372db..264dd77aff 100644 --- a/akka-camel/src/test/scala/akka/camel/ConcurrentActivationTest.scala +++ b/akka-camel/src/test/scala/akka/camel/ConcurrentActivationTest.scala @@ -42,7 +42,7 @@ class ConcurrentActivationTest extends WordSpec with Matchers with NonSharedCame ref ! CreateRegistrars(number) // send a broadcast to all registrars, so that number * number messages are sent // every Register registers a consumer and a producer - (1 to number).map(i ⇒ ref ! RegisterConsumersAndProducers("direct:concurrent-")) + (1 to number).map(i => ref ! RegisterConsumersAndProducers("direct:concurrent-")) // de-register all consumers and producers ref ! DeRegisterConsumersAndProducers() @@ -50,9 +50,9 @@ class ConcurrentActivationTest extends WordSpec with Matchers with NonSharedCame val allRefsFuture = promiseAllRefs.future // map over all futures, put all futures in one list of activated and deactivated actor refs. futureRegistrarLists.map { - case (futureActivations, futureDeactivations) ⇒ + case (futureActivations, futureDeactivations) => futureActivations zip futureDeactivations map { - case (activations, deactivations) ⇒ + case (activations, deactivations) => promiseAllRefs.success((activations.flatten, deactivations.flatten)) } } @@ -68,8 +68,8 @@ class ConcurrentActivationTest extends WordSpec with Matchers with NonSharedCame } val (activatedConsumerNames, activatedProducerNames) = partitionNames(activations) val (deactivatedConsumerNames, deactivatedProducerNames) = partitionNames(deactivations) - assertContainsSameElements(activatedConsumerNames → deactivatedConsumerNames) - assertContainsSameElements(activatedProducerNames → deactivatedProducerNames) + assertContainsSameElements(activatedConsumerNames -> deactivatedConsumerNames) + assertContainsSameElements(activatedProducerNames -> deactivatedProducerNames) } finally { system.eventStream.publish(TestEvent.UnMute(eventFilter)) } @@ -81,11 +81,11 @@ class ConsumerBroadcast(promise: Promise[(Future[List[List[ActorRef]]], Future[L private var broadcaster: Option[ActorRef] = None private implicit val ec = context.dispatcher def receive = { - case CreateRegistrars(number) ⇒ + case CreateRegistrars(number) => var allActivationFutures = List[Future[List[ActorRef]]]() var allDeactivationFutures = List[Future[List[ActorRef]]]() - val routeePaths = (1 to number).map { i ⇒ + val routeePaths = (1 to number).map { i => val activationListPromise = Promise[List[ActorRef]]() val deactivationListPromise = Promise[List[ActorRef]]() val activationListFuture = activationListPromise.future @@ -96,10 +96,10 @@ class ConsumerBroadcast(promise: Promise[(Future[List[List[ActorRef]]], Future[L val routee = context.actorOf(Props(classOf[Registrar], i, number, activationListPromise, deactivationListPromise), "registrar-" + i) routee.path.toString } - promise.success(Future.sequence(allActivationFutures) → Future.sequence(allDeactivationFutures)) + promise.success(Future.sequence(allActivationFutures) -> Future.sequence(allDeactivationFutures)) broadcaster = Some(context.actorOf(BroadcastGroup(routeePaths).props(), "registrarRouter")) - case reg: Any ⇒ + case reg: Any => broadcaster.foreach(_.forward(reg)) } } @@ -121,7 +121,7 @@ class Registrar(val start: Int, val number: Int, activationsPromise: Promise[Lis private implicit val timeout = Timeout(10.seconds.dilated(context.system)) def receive = { - case reg: RegisterConsumersAndProducers ⇒ + case reg: RegisterConsumersAndProducers => val i = index val endpoint = reg.endpointUri + start + "-" + i add(new EchoConsumer(endpoint), "concurrent-test-echo-consumer-" + start + "-" + i) @@ -130,12 +130,12 @@ class Registrar(val start: Int, val number: Int, activationsPromise: Promise[Lis if (activations.size == number * 2) { Future.sequence(activations.toList) map activationsPromise.success } - case reg: DeRegisterConsumersAndProducers ⇒ - actorRefs.foreach { aref ⇒ + case reg: DeRegisterConsumersAndProducers => + actorRefs.foreach { aref => context.stop(aref) val result = camel.deactivationFutureFor(aref) result.failed.foreach { - e ⇒ log.error("deactivationFutureFor {} failed: {}", aref, e.getMessage) + e => log.error("deactivationFutureFor {} failed: {}", aref, e.getMessage) } deActivations += result if (deActivations.size == number * 2) { @@ -144,12 +144,12 @@ class Registrar(val start: Int, val number: Int, activationsPromise: Promise[Lis } } - def add(actor: ⇒ Actor, name: String): Unit = { + def add(actor: => Actor, name: String): Unit = { val ref = context.actorOf(Props(actor), name) actorRefs = actorRefs + ref val result = camel.activationFutureFor(ref) result.failed.foreach { - e ⇒ log.error("activationFutureFor {} failed: {}", ref, e.getMessage) + e => log.error("activationFutureFor {} failed: {}", ref, e.getMessage) } activations += result } @@ -160,7 +160,7 @@ class EchoConsumer(endpoint: String) extends Actor with Consumer { def endpointUri = endpoint def receive = { - case msg: CamelMessage ⇒ sender() ! msg + case msg: CamelMessage => sender() ! msg } /** @@ -168,7 +168,7 @@ class EchoConsumer(endpoint: String) extends Actor with Consumer { * By default it returns an identity function, override this method to * return a custom route definition handler. */ - override def onRouteDefinition = (rd: RouteDefinition) ⇒ rd.onException(classOf[Exception]).handled(true).transform(Builder.exceptionMessage).end + override def onRouteDefinition = (rd: RouteDefinition) => rd.onException(classOf[Exception]).handled(true).transform(Builder.exceptionMessage).end } class TestProducer(uri: String) extends Actor with Producer { diff --git a/akka-camel/src/test/scala/akka/camel/ConsumerIntegrationTest.scala b/akka-camel/src/test/scala/akka/camel/ConsumerIntegrationTest.scala index 1c871ff0eb..d310a59eb4 100644 --- a/akka-camel/src/test/scala/akka/camel/ConsumerIntegrationTest.scala +++ b/akka-camel/src/test/scala/akka/camel/ConsumerIntegrationTest.scala @@ -39,7 +39,7 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel start(new Consumer { def endpointUri = "direct:a1" def receive = { - case m: CamelMessage ⇒ sender() ! "received " + m.bodyAs[String] + case m: CamelMessage => sender() ! "received " + m.bodyAs[String] } }, name = "direct-a1") camel.sendTo("direct:a1", msg = "some message") should ===("received some message") @@ -52,7 +52,7 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel val ref = start(new Consumer { override def replyTimeout = SHORT_TIMEOUT def endpointUri = "direct:a3" - def receive = { case _ ⇒ { Thread.sleep(LONG_WAIT.toMillis); sender() ! "done" } } + def receive = { case _ => { Thread.sleep(LONG_WAIT.toMillis); sender() ! "done" } } }, name = "ignore-this-deadletter-timeout-consumer-reply") intercept[CamelExecutionException] { @@ -68,8 +68,8 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel def endpointUri = "direct:a2" def receive = { - case "throw" ⇒ throw new TestException("") - case m: CamelMessage ⇒ sender() ! "received " + m.bodyAs[String] + case "throw" => throw new TestException("") + case m: CamelMessage => sender() ! "received " + m.bodyAs[String] } override def postRestart(reason: Throwable): Unit = { @@ -111,7 +111,7 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel "Error passing consumer supports error handling through route modification" in { val ref = start(new ErrorThrowingConsumer("direct:error-handler-test") { - override def onRouteDefinition = (rd: RouteDefinition) ⇒ { + override def onRouteDefinition = (rd: RouteDefinition) => { rd.onException(classOf[TestException]).handled(true).transform(Builder.exceptionMessage).end } }, name = "direct-error-handler-test") @@ -123,7 +123,7 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel "Error passing consumer supports redelivery through route modification" in { val ref = start(new FailingOnceConsumer("direct:failing-once-consumer") { - override def onRouteDefinition = (rd: RouteDefinition) ⇒ { + override def onRouteDefinition = (rd: RouteDefinition) => { rd.onException(classOf[TestException]).redeliveryDelay(0L).maximumRedeliveries(1).end } }, name = "direct-failing-once-consumer") @@ -136,7 +136,7 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel "Consumer supports manual Ack" in { val ref = start(new ManualAckConsumer() { def endpointUri = "direct:manual-ack" - def receive = { case _ ⇒ sender() ! Ack } + def receive = { case _ => sender() ! Ack } }, name = "direct-manual-ack-1") camel.template.asyncSendBody("direct:manual-ack", "some message").get(defaultTimeoutDuration.toSeconds, TimeUnit.SECONDS) should ===(null) //should not timeout stop(ref) @@ -146,7 +146,7 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel val someException = new Exception("e1") val ref = start(new ManualAckConsumer() { def endpointUri = "direct:manual-ack" - def receive = { case _ ⇒ sender() ! Failure(someException) } + def receive = { case _ => sender() ! Failure(someException) } }, name = "direct-manual-ack-2") intercept[ExecutionException] { @@ -159,7 +159,7 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel val ref = start(new ManualAckConsumer() { override def replyTimeout = 10 millis def endpointUri = "direct:manual-ack" - def receive = { case _ ⇒ } + def receive = { case _ => } }, name = "direct-manual-ack-3") intercept[ExecutionException] { @@ -180,7 +180,7 @@ class ConsumerIntegrationTest extends WordSpec with Matchers with NonSharedCamel class ErrorThrowingConsumer(override val endpointUri: String) extends Consumer { def receive = { - case msg: CamelMessage ⇒ throw new TestException("error: %s" format msg.body) + case msg: CamelMessage => throw new TestException("error: %s" format msg.body) } override def preRestart(reason: Throwable, message: Option[Any]): Unit = { super.preRestart(reason, message) @@ -190,9 +190,9 @@ class ErrorThrowingConsumer(override val endpointUri: String) extends Consumer { class ErrorRespondingConsumer(override val endpointUri: String) extends Consumer { def receive = { - case msg: CamelMessage ⇒ throw new TestException("Error!") + case msg: CamelMessage => throw new TestException("Error!") } - override def onRouteDefinition = (rd: RouteDefinition) ⇒ { + override def onRouteDefinition = (rd: RouteDefinition) => { // Catch TestException and handle it by returning a modified version of the in message rd.onException(classOf[TestException]).handled(true).transform(Builder.body.append(" has an error")).end } @@ -206,7 +206,7 @@ class ErrorRespondingConsumer(override val endpointUri: String) extends Consumer class FailingOnceConsumer(override val endpointUri: String) extends Consumer { def receive = { - case msg: CamelMessage ⇒ + case msg: CamelMessage => if (msg.headerAs[Boolean]("CamelRedelivered").getOrElse(false)) sender() ! ("accepted: %s" format msg.body) else @@ -221,7 +221,7 @@ class FailingOnceConsumer(override val endpointUri: String) extends Consumer { class TestActor(uri: String = "file://target/abcde") extends Consumer { def endpointUri = uri - def receive = { case _ ⇒ /* do nothing */ } + def receive = { case _ => /* do nothing */ } } trait ManualAckConsumer extends Consumer { diff --git a/akka-camel/src/test/scala/akka/camel/MessageScalaTest.scala b/akka-camel/src/test/scala/akka/camel/MessageScalaTest.scala index 2b00df5ad2..f39e03f81c 100644 --- a/akka-camel/src/test/scala/akka/camel/MessageScalaTest.scala +++ b/akka-camel/src/test/scala/akka/camel/MessageScalaTest.scala @@ -24,31 +24,31 @@ class MessageScalaTest extends FunSuite with Matchers with SharedCamelSystem { } test("mustConvertDoubleHeaderToString") { - val message = CamelMessage("test", Map("test" → 1.4)) + val message = CamelMessage("test", Map("test" -> 1.4)) message.headerAs[String]("test").get should ===("1.4") } test("mustReturnSubsetOfHeaders") { - val message = CamelMessage("test", Map("A" → "1", "B" → "2")) - message.headers(Set("B")) should ===(Map("B" → "2")) + val message = CamelMessage("test", Map("A" -> "1", "B" -> "2")) + message.headers(Set("B")) should ===(Map("B" -> "2")) } test("mustTransformBodyAndPreserveHeaders") { - CamelMessage("a", Map("A" → "1")).mapBody((body: String) ⇒ body + "b") should ===(CamelMessage("ab", Map("A" → "1"))) + CamelMessage("a", Map("A" -> "1")).mapBody((body: String) => body + "b") should ===(CamelMessage("ab", Map("A" -> "1"))) } test("mustConvertBodyAndPreserveHeaders") { - CamelMessage(1.4, Map("A" → "1")).withBodyAs[String] should ===(CamelMessage("1.4", Map("A" → "1"))) + CamelMessage(1.4, Map("A" -> "1")).withBodyAs[String] should ===(CamelMessage("1.4", Map("A" -> "1"))) } test("mustSetBodyAndPreserveHeaders") { - CamelMessage("test1", Map("A" → "1")).copy(body = "test2") should ===( - CamelMessage("test2", Map("A" → "1"))) + CamelMessage("test1", Map("A" -> "1")).copy(body = "test2") should ===( + CamelMessage("test2", Map("A" -> "1"))) } test("mustSetHeadersAndPreserveBody") { - CamelMessage("test1", Map("A" → "1")).copy(headers = Map("C" → "3")) should ===( - CamelMessage("test1", Map("C" → "3"))) + CamelMessage("test1", Map("A" -> "1")).copy(headers = Map("C" -> "3")) should ===( + CamelMessage("test1", Map("C" -> "3"))) } test("mustBeAbleToReReadStreamCacheBody") { diff --git a/akka-camel/src/test/scala/akka/camel/ProducerFeatureTest.scala b/akka-camel/src/test/scala/akka/camel/ProducerFeatureTest.scala index 6f1c85bc97..3e4cb9f744 100644 --- a/akka-camel/src/test/scala/akka/camel/ProducerFeatureTest.scala +++ b/akka-camel/src/test/scala/akka/camel/ProducerFeatureTest.scala @@ -45,9 +45,9 @@ class ProducerFeatureTest extends TestKit(ActorSystem("ProducerFeatureTest", Akk "01 produce a message and receive normal response" in { val producer = system.actorOf(Props(new TestProducer("direct:producer-test-2", true)), name = "01-direct-producer-2") - val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId -> "123")) producer.tell(message, testActor) - expectMsg(CamelMessage("received TEST", Map(CamelMessage.MessageExchangeId → "123"))) + expectMsg(CamelMessage("received TEST", Map(CamelMessage.MessageExchangeId -> "123"))) } "02 produce a message and receive failure response" in { @@ -55,30 +55,30 @@ class ProducerFeatureTest extends TestKit(ActorSystem("ProducerFeatureTest", Akk var deadActor: Option[ActorRef] = None val supervisor = system.actorOf(Props(new Actor { def receive = { - case p: Props ⇒ { + case p: Props => { val producer = context.actorOf(p) context.watch(producer) sender() ! producer } - case Terminated(actorRef) ⇒ { + case Terminated(actorRef) => { deadActor = Some(actorRef) latch.countDown() } } override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { - case _: AkkaCamelException ⇒ Stop + case _: AkkaCamelException => Stop } }), name = "02-prod-anonymous-supervisor") supervisor.tell(Props(new TestProducer("direct:producer-test-2")), testActor) val producer = receiveOne(timeoutDuration).asInstanceOf[ActorRef] - val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId -> "123")) filterEvents(EventFilter[AkkaCamelException](occurrences = 1)) { producer.tell(message, testActor) expectMsgPF(timeoutDuration) { - case Failure(e: AkkaCamelException) ⇒ + case Failure(e: AkkaCamelException) => e.getMessage should ===("failure") - e.headers should ===(Map(CamelMessage.MessageExchangeId → "123")) + e.headers should ===(Map(CamelMessage.MessageExchangeId -> "123")) } } Await.ready(latch, timeoutDuration) @@ -106,21 +106,21 @@ class ProducerFeatureTest extends TestKit(ActorSystem("ProducerFeatureTest", Akk "10 produce message to direct:producer-test-3 and receive normal response" in { val producer = system.actorOf(Props(new TestProducer("direct:producer-test-3")), name = "10-direct-producer-test-3") - val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId -> "123")) producer.tell(message, testActor) - expectMsg(CamelMessage("received test", Map(CamelMessage.MessageExchangeId → "123"))) + expectMsg(CamelMessage("received test", Map(CamelMessage.MessageExchangeId -> "123"))) } "11 produce message to direct:producer-test-3 and receive failure response" in { val producer = system.actorOf(Props(new TestProducer("direct:producer-test-3")), name = "11-direct-producer-test-3-receive-failure") - val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId -> "123")) filterEvents(EventFilter[AkkaCamelException](occurrences = 1)) { producer.tell(message, testActor) expectMsgPF(timeoutDuration) { - case Failure(e: AkkaCamelException) ⇒ + case Failure(e: AkkaCamelException) => e.getMessage should ===("failure") - e.headers should ===(Map(CamelMessage.MessageExchangeId → "123")) + e.headers should ===(Map(CamelMessage.MessageExchangeId -> "123")) } } } @@ -128,22 +128,22 @@ class ProducerFeatureTest extends TestKit(ActorSystem("ProducerFeatureTest", Akk "12 produce message, forward normal response of direct:producer-test-2 to a replying target actor and receive response" in { val target = system.actorOf(Props[ReplyingForwardTarget], name = "12-reply-forwarding-target") val producer = system.actorOf(Props(new TestForwarder("direct:producer-test-2", target)), name = "12-direct-producer-test-2-forwarder") - val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId -> "123")) producer.tell(message, testActor) - expectMsg(CamelMessage("received test", Map(CamelMessage.MessageExchangeId → "123", "test" → "result"))) + expectMsg(CamelMessage("received test", Map(CamelMessage.MessageExchangeId -> "123", "test" -> "result"))) } "13 produce message, forward failure response of direct:producer-test-2 to a replying target actor and receive response" in { val target = system.actorOf(Props[ReplyingForwardTarget], name = "13-reply-forwarding-target") val producer = system.actorOf(Props(new TestForwarder("direct:producer-test-2", target)), name = "13-direct-producer-test-2-forwarder-failure") - val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId -> "123")) filterEvents(EventFilter[AkkaCamelException](occurrences = 1)) { producer.tell(message, testActor) expectMsgPF(timeoutDuration) { - case Failure(e: AkkaCamelException) ⇒ + case Failure(e: AkkaCamelException) => e.getMessage should ===("failure") - e.headers should ===(Map(CamelMessage.MessageExchangeId → "123", "test" → "failure")) + e.headers should ===(Map(CamelMessage.MessageExchangeId -> "123", "test" -> "failure")) } } } @@ -170,23 +170,23 @@ class ProducerFeatureTest extends TestKit(ActorSystem("ProducerFeatureTest", Akk "16 produce message, forward normal response from direct:producer-test-3 to a replying target actor and receive response" in { val target = system.actorOf(Props[ReplyingForwardTarget], name = "16-reply-forwarding-target") val producer = system.actorOf(Props(new TestForwarder("direct:producer-test-3", target)), name = "16-direct-producer-test-3-to-replying-actor") - val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId -> "123")) producer.tell(message, testActor) - expectMsg(CamelMessage("received test", Map(CamelMessage.MessageExchangeId → "123", "test" → "result"))) + expectMsg(CamelMessage("received test", Map(CamelMessage.MessageExchangeId -> "123", "test" -> "result"))) } "17 produce message, forward failure response from direct:producer-test-3 to a replying target actor and receive response" in { val target = system.actorOf(Props[ReplyingForwardTarget], name = "17-reply-forwarding-target") val producer = system.actorOf(Props(new TestForwarder("direct:producer-test-3", target)), name = "17-direct-producer-test-3-forward-failure") - val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId -> "123")) filterEvents(EventFilter[AkkaCamelException](occurrences = 1)) { producer.tell(message, testActor) expectMsgPF(timeoutDuration) { - case Failure(e: AkkaCamelException) ⇒ + case Failure(e: AkkaCamelException) => e.getMessage should ===("failure") - e.headers should ===(Map(CamelMessage.MessageExchangeId → "123", "test" → "failure")) + e.headers should ===(Map(CamelMessage.MessageExchangeId -> "123", "test" -> "failure")) } } } @@ -217,7 +217,7 @@ class ProducerFeatureTest extends TestKit(ActorSystem("ProducerFeatureTest", Akk filterEvents(EventFilter[AkkaCamelException](occurrences = 1)) { val futureFailed = producer.tell("fail", testActor) expectMsgPF(timeoutDuration) { - case Failure(e) ⇒ + case Failure(e) => e.getMessage should ===("fail") } producer.tell("OK", testActor) @@ -254,9 +254,9 @@ object ProducerFeatureTest { implicit val ec = context.system.dispatcher Await.ready(CamelExtension(context.system).activationFutureFor(child), timeout.duration) def receive = { - case msg: CamelMessage ⇒ + case msg: CamelMessage => child forward (msg) - case (aref: ActorRef, msg: String) ⇒ + case (aref: ActorRef, msg: String) => aref ! msg } } @@ -269,8 +269,8 @@ object ProducerFeatureTest { def endpointUri = uri override def transformOutgoingMessage(msg: Any) = msg match { - case msg: CamelMessage ⇒ if (upper) msg.mapBody { - body: String ⇒ + case msg: CamelMessage => if (upper) msg.mapBody { + body: String => if (body == "err") throw new Exception("Crash!") val upperMsg = body.toUpperCase lastSender = Some(sender()) @@ -280,7 +280,7 @@ object ProducerFeatureTest { } override def postStop(): Unit = { - for (msg ← lastMessage; aref ← lastSender) context.parent ! ((aref, msg)) + for (msg <- lastMessage; aref <- lastSender) context.parent ! ((aref, msg)) super.postStop() } } @@ -294,8 +294,8 @@ object ProducerFeatureTest { } override protected def transformOutgoingMessage(msg: Any) = msg match { - case msg: CamelMessage ⇒ if (upper) msg.mapBody { - body: String ⇒ body.toUpperCase + case msg: CamelMessage => if (upper) msg.mapBody { + body: String => body.toUpperCase } else msg } @@ -311,11 +311,11 @@ object ProducerFeatureTest { class TestResponder extends Actor { def receive = { - case msg: CamelMessage ⇒ msg.body match { - case "fail" ⇒ context.sender() ! akka.actor.Status.Failure(new AkkaCamelException(new Exception("failure"), msg.headers)) - case _ ⇒ + case msg: CamelMessage => msg.body match { + case "fail" => context.sender() ! akka.actor.Status.Failure(new AkkaCamelException(new Exception("failure"), msg.headers)) + case _ => context.sender() ! (msg.mapBody { - body: String ⇒ "received %s" format body + body: String => "received %s" format body }) } } @@ -323,11 +323,11 @@ object ProducerFeatureTest { class ReplyingForwardTarget extends Actor { def receive = { - case msg: CamelMessage ⇒ - context.sender() ! (msg.copy(headers = msg.headers + ("test" → "result"))) - case msg: akka.actor.Status.Failure ⇒ + case msg: CamelMessage => + context.sender() ! (msg.copy(headers = msg.headers + ("test" -> "result"))) + case msg: akka.actor.Status.Failure => msg.cause match { - case e: AkkaCamelException ⇒ context.sender() ! Status.Failure(new AkkaCamelException(e, e.headers + ("test" → "failure"))) + case e: AkkaCamelException => context.sender() ! Status.Failure(new AkkaCamelException(e, e.headers + ("test" -> "failure"))) } } } @@ -349,8 +349,8 @@ object ProducerFeatureTest { from("direct:producer-test-2").process(new Processor() { def process(exchange: Exchange) = { exchange.getIn.getBody match { - case "fail" ⇒ throw new Exception("failure") - case body ⇒ exchange.getOut.setBody("received %s" format body) + case "fail" => throw new Exception("failure") + case body => exchange.getOut.setBody("received %s" format body) } } }) @@ -359,15 +359,15 @@ object ProducerFeatureTest { class SimpleProducer(override val endpointUri: String) extends Producer { override protected def transformResponse(msg: Any) = msg match { - case m: CamelMessage ⇒ m.bodyAs[String] - case m: Any ⇒ m + case m: CamelMessage => m.bodyAs[String] + case m: Any => m } } class IntermittentErrorConsumer(override val endpointUri: String) extends Consumer { def receive = { - case msg: CamelMessage if msg.bodyAs[String] == "fail" ⇒ sender() ! Failure(new Exception("fail")) - case msg: CamelMessage ⇒ sender() ! msg + case msg: CamelMessage if msg.bodyAs[String] == "fail" => sender() ! Failure(new Exception("fail")) + case msg: CamelMessage => sender() ! msg } } diff --git a/akka-camel/src/test/scala/akka/camel/TestSupport.scala b/akka-camel/src/test/scala/akka/camel/TestSupport.scala index 39a827c9dc..b1d00d0475 100644 --- a/akka-camel/src/test/scala/akka/camel/TestSupport.scala +++ b/akka-camel/src/test/scala/akka/camel/TestSupport.scala @@ -18,7 +18,7 @@ import akka.util.Timeout import akka.testkit.{ TestKit, AkkaSpec } private[camel] object TestSupport { - def start(actor: ⇒ Actor, name: String)(implicit system: ActorSystem, timeout: Timeout): ActorRef = + def start(actor: => Actor, name: String)(implicit system: ActorSystem, timeout: Timeout): ActorRef = Await.result(CamelExtension(system).activationFutureFor(system.actorOf(Props(actor), name))(timeout, system.dispatcher), timeout.duration) def stop(actorRef: ActorRef)(implicit system: ActorSystem, timeout: Timeout): Unit = { @@ -38,8 +38,8 @@ private[camel] object TestSupport { try { camel.template.asyncRequestBody(to, msg).get(timeout.toNanos, TimeUnit.NANOSECONDS) } catch { - case e: ExecutionException ⇒ throw e.getCause - case e: TimeoutException ⇒ throw new AssertionError("Failed to get response to message [%s], send to endpoint [%s], within [%s]".format(msg, to, timeout)) + case e: ExecutionException => throw e.getCause + case e: TimeoutException => throw new AssertionError("Failed to get response to message [%s], send to endpoint [%s], within [%s]".format(msg, to, timeout)) } } @@ -47,7 +47,7 @@ private[camel] object TestSupport { def routes = camel.context.getRoutes } - trait SharedCamelSystem extends BeforeAndAfterAll { this: Suite ⇒ + trait SharedCamelSystem extends BeforeAndAfterAll { this: Suite => implicit lazy val system = ActorSystem("SharedCamelSystem", AkkaSpec.testConf) implicit lazy val camel = CamelExtension(system) @@ -57,7 +57,7 @@ private[camel] object TestSupport { } } - trait NonSharedCamelSystem extends BeforeAndAfterEach { this: Suite ⇒ + trait NonSharedCamelSystem extends BeforeAndAfterEach { this: Suite => implicit var system: ActorSystem = _ implicit var camel: Camel = _ @@ -73,7 +73,7 @@ private[camel] object TestSupport { } } - def time[A](block: ⇒ A): FiniteDuration = { + def time[A](block: => A): FiniteDuration = { val start = System.nanoTime() block val duration = System.nanoTime() - start diff --git a/akka-camel/src/test/scala/akka/camel/UntypedProducerTest.scala b/akka-camel/src/test/scala/akka/camel/UntypedProducerTest.scala index a2e8ada137..80daa17b53 100644 --- a/akka-camel/src/test/scala/akka/camel/UntypedProducerTest.scala +++ b/akka-camel/src/test/scala/akka/camel/UntypedProducerTest.scala @@ -34,13 +34,13 @@ class UntypedProducerTest extends WordSpec with Matchers with BeforeAndAfterAll "produce a message and receive a normal response" in { val producer = system.actorOf(Props[SampleUntypedReplyingProducer], name = "sample-untyped-replying-producer") - val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("test", Map(CamelMessage.MessageExchangeId -> "123")) val future = producer.ask(message)(timeout) - val expected = CamelMessage("received test", Map(CamelMessage.MessageExchangeId → "123")) + val expected = CamelMessage("received test", Map(CamelMessage.MessageExchangeId -> "123")) Await.result(future, timeout) match { - case result: CamelMessage ⇒ result should ===(expected) - case unexpected ⇒ fail("Actor responded with unexpected message:" + unexpected) + case result: CamelMessage => result should ===(expected) + case unexpected => fail("Actor responded with unexpected message:" + unexpected) } } @@ -48,15 +48,15 @@ class UntypedProducerTest extends WordSpec with Matchers with BeforeAndAfterAll "produce a message and receive a failure response" in { val producer = system.actorOf(Props[SampleUntypedReplyingProducer], name = "sample-untyped-replying-producer-failure") - val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId → "123")) + val message = CamelMessage("fail", Map(CamelMessage.MessageExchangeId -> "123")) filterEvents(EventFilter[AkkaCamelException](occurrences = 1)) { val future = producer.ask(message)(timeout).failed Await.result(future, timeout) match { - case e: AkkaCamelException ⇒ + case e: AkkaCamelException => e.getMessage should ===("failure") - e.headers should ===(Map(CamelMessage.MessageExchangeId → "123")) - case unexpected ⇒ fail("Actor responded with unexpected message:" + unexpected) + e.headers should ===(Map(CamelMessage.MessageExchangeId -> "123")) + case unexpected => fail("Actor responded with unexpected message:" + unexpected) } } } @@ -84,8 +84,8 @@ object UntypedProducerTest { from("direct:producer-test-1").process(new Processor() { def process(exchange: Exchange) = { exchange.getIn.getBody match { - case "fail" ⇒ throw new Exception("failure") - case body ⇒ exchange.getOut.setBody("received %s" format body) + case "fail" => throw new Exception("failure") + case body => exchange.getOut.setBody("received %s" format body) } } }) diff --git a/akka-camel/src/test/scala/akka/camel/internal/component/ActorEndpointPathTest.scala b/akka-camel/src/test/scala/akka/camel/internal/component/ActorEndpointPathTest.scala index 5868cb87fc..d6c2d24367 100644 --- a/akka-camel/src/test/scala/akka/camel/internal/component/ActorEndpointPathTest.scala +++ b/akka-camel/src/test/scala/akka/camel/internal/component/ActorEndpointPathTest.scala @@ -15,7 +15,7 @@ class ActorEndpointPathTest extends WordSpec with SharedCamelSystem with Matcher def find(path: String) = ActorEndpointPath.fromCamelPath(path).findActorIn(system) "findActorIn returns Some(actor ref) if actor exists" in { - val path = system.actorOf(Props(new Actor { def receive = { case _ ⇒ } }), "knownactor").path + val path = system.actorOf(Props(new Actor { def receive = { case _ => } }), "knownactor").path find(path.toString) should be('defined) } diff --git a/akka-camel/src/test/scala/akka/camel/internal/component/ActorProducerTest.scala b/akka-camel/src/test/scala/akka/camel/internal/component/ActorProducerTest.scala index 061601c889..124f156e91 100644 --- a/akka-camel/src/test/scala/akka/camel/internal/component/ActorProducerTest.scala +++ b/akka-camel/src/test/scala/akka/camel/internal/component/ActorProducerTest.scala @@ -327,7 +327,7 @@ class ActorProducerTest extends TestKit(ActorSystem("ActorProducerTest")) with W } } -private[camel] trait ActorProducerFixture extends MockitoSugar with BeforeAndAfterAll with BeforeAndAfterEach { self: TestKit with Matchers with Suite ⇒ +private[camel] trait ActorProducerFixture extends MockitoSugar with BeforeAndAfterAll with BeforeAndAfterEach { self: TestKit with Matchers with Suite => var camel: Camel = _ var exchange: CamelExchangeAdapter = _ var callback: AsyncCallback = _ @@ -429,7 +429,7 @@ private[camel] trait ActorProducerFixture extends MockitoSugar with BeforeAndAft } def echoActor = system.actorOf(Props(new Actor { - def receive = { case msg ⇒ sender() ! "received " + msg } + def receive = { case msg => sender() ! "received " + msg } }), name = "echoActor") } diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsCollector.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsCollector.scala index a2ac9a0978..c40faf079d 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsCollector.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsCollector.scala @@ -64,12 +64,12 @@ private[metrics] class ClusterMetricsSupervisor extends Actor with ActorLogging } override def receive = { - case CollectionStartMessage ⇒ + case CollectionStartMessage => children.foreach(stop) collectorInstance += 1 actorOf(Props(classOf[ClusterMetricsCollector]), collectorName) log.debug(s"Collection started.") - case CollectionStopMessage ⇒ + case CollectionStopMessage => children.foreach(stop) log.debug(s"Collection stopped.") } @@ -169,19 +169,19 @@ private[metrics] class ClusterMetricsCollector extends Actor with ActorLogging { } def receive = { - case GossipTick ⇒ gossip() - case MetricsTick ⇒ sample() - case msg: MetricsGossipEnvelope ⇒ receiveGossip(msg) - case state: CurrentClusterState ⇒ receiveState(state) - case MemberUp(m) ⇒ addMember(m) - case MemberWeaklyUp(m) ⇒ addMember(m) - case MemberRemoved(m, _) ⇒ removeMember(m) - case MemberExited(m) ⇒ removeMember(m) - case UnreachableMember(m) ⇒ removeMember(m) - case ReachableMember(m) ⇒ + case GossipTick => gossip() + case MetricsTick => sample() + case msg: MetricsGossipEnvelope => receiveGossip(msg) + case state: CurrentClusterState => receiveState(state) + case MemberUp(m) => addMember(m) + case MemberWeaklyUp(m) => addMember(m) + case MemberRemoved(m, _) => removeMember(m) + case MemberExited(m) => removeMember(m) + case UnreachableMember(m) => removeMember(m) + case ReachableMember(m) => if (m.status == MemberStatus.Up || m.status == MemberStatus.WeaklyUp) addMember(m) - case _: MemberEvent ⇒ // not interested in other types of MemberEvent + case _: MemberEvent => // not interested in other types of MemberEvent } @@ -211,7 +211,7 @@ private[metrics] class ClusterMetricsCollector extends Actor with ActorLogging { */ def receiveState(state: CurrentClusterState): Unit = nodes = (state.members diff state.unreachable) collect { - case m if m.status == MemberStatus.Up || m.status == MemberStatus.WeaklyUp ⇒ m.address + case m if m.status == MemberStatus.Up || m.status == MemberStatus.WeaklyUp => m.address } /** diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsExtension.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsExtension.scala index b6050a1e50..acd4a71170 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsExtension.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsExtension.scala @@ -45,7 +45,7 @@ class ClusterMetricsExtension(system: ExtendedActorSystem) extends Extension { * Supervision strategy. */ private[metrics] val strategy = system.dynamicAccess.createInstanceFor[SupervisorStrategy]( - SupervisorStrategyProvider, immutable.Seq(classOf[Config] → SupervisorStrategyConfiguration)) + SupervisorStrategyProvider, immutable.Seq(classOf[Config] -> SupervisorStrategyConfiguration)) .getOrElse { val log: LoggingAdapter = Logging(system, getClass.getName) log.error(s"Configured strategy provider ${SupervisorStrategyProvider} failed to load, using default ${classOf[ClusterMetricsStrategy].getName}.") diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsRouting.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsRouting.scala index 0d7c10a0bb..89ec3edcfa 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsRouting.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsRouting.scala @@ -74,10 +74,10 @@ final case class AdaptiveLoadBalancingRoutingLogic(system: ActorSystem, metricsS } updateWeightedRoutees() match { - case Some(weighted) ⇒ + case Some(weighted) => if (weighted.isEmpty) NoRoutee else weighted(ThreadLocalRandom.current.nextInt(weighted.total) + 1) - case None ⇒ + case None => routees(ThreadLocalRandom.current.nextInt(routees.size)) } @@ -172,11 +172,11 @@ final case class AdaptiveLoadBalancingPool( override def withFallback(other: RouterConfig): RouterConfig = if (this.supervisorStrategy ne Pool.defaultSupervisorStrategy) this else other match { - case _: FromConfig | _: NoRouter ⇒ this // NoRouter is the default, hence “neutral” - case otherRouter: AdaptiveLoadBalancingPool ⇒ + case _: FromConfig | _: NoRouter => this // NoRouter is the default, hence “neutral” + case otherRouter: AdaptiveLoadBalancingPool => if (otherRouter.supervisorStrategy eq Pool.defaultSupervisorStrategy) this else this.withSupervisorStrategy(otherRouter.supervisorStrategy) - case _ ⇒ throw new IllegalArgumentException("Expected AdaptiveLoadBalancingPool, got [%s]".format(other)) + case _ => throw new IllegalArgumentException("Expected AdaptiveLoadBalancingPool, got [%s]".format(other)) } } @@ -256,10 +256,10 @@ case object HeapMetricsSelector extends CapacityMetricsSelector { override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = { nodeMetrics.collect { - case HeapMemory(address, _, used, committed, max) ⇒ + case HeapMemory(address, _, used, committed, max) => val capacity = max match { - case None ⇒ (committed - used).toDouble / committed - case Some(m) ⇒ (m - used).toDouble / m + case None => (committed - used).toDouble / committed + case Some(m) => (m - used).toDouble / m } (address, capacity) }.toMap @@ -296,7 +296,7 @@ case object CpuMetricsSelector extends CapacityMetricsSelector { override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = { nodeMetrics.collect { - case Cpu(address, _, _, Some(cpuCombined), Some(cpuStolen), _) ⇒ + case Cpu(address, _, _, Some(cpuCombined), Some(cpuStolen), _) => // Arbitrary load rating function which skews in favor of stolen time. val load = cpuCombined + cpuStolen * (1.0 + factor) val capacity = if (load >= 1.0) 0.0 else 1.0 - load @@ -322,7 +322,7 @@ case object SystemLoadAverageMetricsSelector extends CapacityMetricsSelector { override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = { nodeMetrics.collect { - case Cpu(address, _, Some(systemLoadAverage), _, _, processors) ⇒ + case Cpu(address, _, Some(systemLoadAverage), _, _, processors) => val capacity = 1.0 - math.min(1.0, systemLoadAverage / processors) (address, capacity) }.toMap @@ -370,11 +370,11 @@ abstract class MixMetricsSelectorBase(selectors: immutable.IndexedSeq[CapacityMe // aggregated average of the capacities by address val init: Map[Address, (Double, Int)] = Map.empty.withDefaultValue((0.0, 0)) combined.foldLeft(init) { - case (acc, (address, capacity)) ⇒ + case (acc, (address, capacity)) => val (sum, count) = acc(address) - acc + (address → ((sum + capacity, count + 1))) + acc + (address -> ((sum + capacity, count + 1))) }.map { - case (address, (sum, count)) ⇒ address → (sum / count) + case (address, (sum, count)) => address -> (sum / count) } } @@ -383,14 +383,14 @@ abstract class MixMetricsSelectorBase(selectors: immutable.IndexedSeq[CapacityMe object MetricsSelector { def fromConfig(config: Config, dynamicAccess: DynamicAccess) = config.getString("metrics-selector") match { - case "mix" ⇒ MixMetricsSelector - case "heap" ⇒ HeapMetricsSelector - case "cpu" ⇒ CpuMetricsSelector - case "load" ⇒ SystemLoadAverageMetricsSelector - case fqn ⇒ - val args = List(classOf[Config] → config) + case "mix" => MixMetricsSelector + case "heap" => HeapMetricsSelector + case "cpu" => CpuMetricsSelector + case "load" => SystemLoadAverageMetricsSelector + case fqn => + val args = List(classOf[Config] -> config) dynamicAccess.createInstanceFor[MetricsSelector](fqn, args).recover({ - case exception ⇒ throw new IllegalArgumentException( + case exception => throw new IllegalArgumentException( (s"Cannot instantiate metrics-selector [$fqn], " + "make sure it extends [akka.cluster.routing.MetricsSelector] and " + "has constructor with [com.typesafe.config.Config] parameter"), exception) @@ -433,10 +433,10 @@ abstract class CapacityMetricsSelector extends MetricsSelector { def weights(capacity: Map[Address, Double]): Map[Address, Int] = { if (capacity.isEmpty) Map.empty[Address, Int] else { - val (_, min) = capacity.minBy { case (_, c) ⇒ c } + val (_, min) = capacity.minBy { case (_, c) => c } // lowest usable capacity is 1% (>= 0.5% will be rounded to weight 1), also avoids div by zero val divisor = math.max(0.01, min) - capacity map { case (address, c) ⇒ (address → math.round((c) / divisor).toInt) } + capacity map { case (address, c) => (address -> math.round((c) / divisor).toInt) } } } @@ -462,12 +462,12 @@ private[metrics] class WeightedRoutees(routees: immutable.IndexedSeq[Routee], se private val buckets: Array[Int] = { def fullAddress(routee: Routee): Address = { val a = routee match { - case ActorRefRoutee(ref) ⇒ ref.path.address - case ActorSelectionRoutee(sel) ⇒ sel.anchor.path.address + case ActorRefRoutee(ref) => ref.path.address + case ActorSelectionRoutee(sel) => sel.anchor.path.address } a match { - case Address(_, _, None, None) ⇒ selfAddress - case a ⇒ a + case Address(_, _, None, None) => selfAddress + case a => a } } val buckets = new Array[Int](routees.size) @@ -475,7 +475,7 @@ private[metrics] class WeightedRoutees(routees: immutable.IndexedSeq[Routee], se val w = weights.withDefaultValue(meanWeight) // we don’t necessarily have metrics for all addresses var i = 0 var sum = 0 - routees foreach { r ⇒ + routees foreach { r => sum += w(fullAddress(r)) buckets(i) = sum i += 1 @@ -527,8 +527,8 @@ private[metrics] class AdaptiveLoadBalancingMetricsListener(routingLogic: Adapti override def postStop(): Unit = extension.unsubscribe(self) def receive = { - case event: ClusterMetricsChanged ⇒ routingLogic.metricsChanged(event) - case _ ⇒ // ignore + case event: ClusterMetricsChanged => routingLogic.metricsChanged(event) + case _ => // ignore } } diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsSettings.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsSettings.scala index 430131852a..332ca9bbda 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsSettings.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsSettings.scala @@ -20,8 +20,8 @@ case class ClusterMetricsSettings(config: Config) { // Extension. val MetricsDispatcher: String = cc.getString("dispatcher") match { - case "" ⇒ Dispatchers.DefaultDispatcherId - case id ⇒ id + case "" => Dispatchers.DefaultDispatcherId + case id => id } val PeriodicTasksInitialDelay: FiniteDuration = cc.getMillisDuration("periodic-tasks-initial-delay") val NativeLibraryExtractFolder: String = cc.getString("native-library-extract-folder") diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsStrategy.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsStrategy.scala index 6bad9e76f0..7ce45c3cef 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsStrategy.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/ClusterMetricsStrategy.scala @@ -28,10 +28,10 @@ object ClusterMetricsStrategy { * [[akka.actor.SupervisorStrategy]] `Decider` which allows to survive intermittent Sigar native method calls failures. */ val metricsDecider: SupervisorStrategy.Decider = { - case _: ActorInitializationException ⇒ Stop - case _: ActorKilledException ⇒ Stop - case _: DeathPactException ⇒ Stop - case _: Throwable ⇒ Restart + case _: ActorInitializationException => Stop + case _: ActorKilledException => Stop + case _: DeathPactException => Stop + case _: Throwable => Restart } } diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/Metric.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/Metric.scala index 06eb0b6079..adffed9b07 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/Metric.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/Metric.scala @@ -32,9 +32,9 @@ final case class Metric private[metrics] (name: String, value: Number, average: */ def :+(latest: Metric): Metric = if (this sameAs latest) average match { - 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 _ ⇒ copy(value = latest.value) + 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 _ => copy(value = latest.value) } else this @@ -42,8 +42,8 @@ final case class Metric private[metrics] (name: String, value: Number, average: * The numerical value of the average, if defined, otherwise the latest value */ def smoothValue: Double = average match { - case Some(avg) ⇒ avg.value - case None ⇒ value.doubleValue + case Some(avg) => avg.value + case None => value.doubleValue } /** @@ -58,8 +58,8 @@ final case class Metric private[metrics] (name: String, value: Number, average: override def hashCode = name.## override def equals(obj: Any) = obj match { - case other: Metric ⇒ sameAs(other) - case _ ⇒ false + case other: Metric => sameAs(other) + case _ => false } } @@ -82,13 +82,13 @@ object Metric extends MetricNumericConverter { * otherwise None is returned. Invalid numeric values are negative and NaN/Infinite. */ def create(name: String, value: Try[Number], decayFactor: Option[Double]): Option[Metric] = value match { - case Success(v) ⇒ create(name, v, decayFactor) - case Failure(_) ⇒ None + case Success(v) => create(name, v, decayFactor) + case Failure(_) => None } def createEWMA(value: Double, decayFactor: Option[Double]): Option[EWMA] = decayFactor match { - case Some(alpha) ⇒ Some(EWMA(value, alpha)) - case None ⇒ None + case Some(alpha) => Some(EWMA(value, alpha)) + case None => None } } @@ -126,8 +126,8 @@ object StandardMetrics { */ def unapply(nodeMetrics: NodeMetrics): Option[(Address, Long, Long, Long, Option[Long])] = { for { - used ← nodeMetrics.metric(HeapMemoryUsed) - committed ← nodeMetrics.metric(HeapMemoryCommitted) + used <- nodeMetrics.metric(HeapMemoryUsed) + committed <- nodeMetrics.metric(HeapMemoryCommitted) } yield (nodeMetrics.address, nodeMetrics.timestamp, used.smoothValue.longValue, committed.smoothValue.longValue, nodeMetrics.metric(HeapMemoryMax).map(_.smoothValue.longValue)) @@ -140,10 +140,10 @@ object StandardMetrics { * contains necessary heap metrics, otherwise it returns null. */ def extractHeapMemory(nodeMetrics: NodeMetrics): HeapMemory = nodeMetrics match { - case HeapMemory(address, timestamp, used, committed, max) ⇒ + case HeapMemory(address, timestamp, used, committed, max) => // note that above extractor returns tuple HeapMemory(address, timestamp, used, committed, max) - case _ ⇒ null + case _ => null } /** @@ -174,7 +174,7 @@ object StandardMetrics { */ def unapply(nodeMetrics: NodeMetrics): Option[(Address, Long, Option[Double], Option[Double], Option[Double], Int)] = { for { - processors ← nodeMetrics.metric(Processors) + processors <- nodeMetrics.metric(Processors) } yield (nodeMetrics.address, nodeMetrics.timestamp, nodeMetrics.metric(SystemLoadAverage).map(_.smoothValue), nodeMetrics.metric(CpuCombined).map(_.smoothValue), @@ -189,10 +189,10 @@ object StandardMetrics { * contains necessary cpu metrics, otherwise it returns null. */ def extractCpu(nodeMetrics: NodeMetrics): Cpu = nodeMetrics match { - case Cpu(address, timestamp, systemLoadAverage, cpuCombined, cpuStolen, processors) ⇒ + case Cpu(address, timestamp, systemLoadAverage, cpuCombined, cpuStolen, processors) => // note that above extractor returns tuple Cpu(address, timestamp, systemLoadAverage, cpuCombined, cpuStolen, processors) - case _ ⇒ null + case _ => null } /** @@ -216,13 +216,13 @@ object StandardMetrics { processors: Int) { cpuCombined match { - case Some(x) ⇒ require(0.0 <= x && x <= 1.0, s"cpuCombined must be between [0.0 - 1.0], was [$x]") - case None ⇒ + case Some(x) => require(0.0 <= x && x <= 1.0, s"cpuCombined must be between [0.0 - 1.0], was [$x]") + case None => } cpuStolen match { - case Some(x) ⇒ require(0.0 <= x && x <= 1.0, s"cpuStolen must be between [0.0 - 1.0], was [$x]") - case None ⇒ + case Some(x) => require(0.0 <= x && x <= 1.0, s"cpuStolen must be between [0.0 - 1.0], was [$x]") + case None => } } @@ -243,21 +243,21 @@ private[metrics] trait MetricNumericConverter { *

  • SIGAR combined CPU can occasionally return a NaN or Infinite (known bug)
  • */ def defined(value: Number): Boolean = convertNumber(value) match { - case Left(a) ⇒ a >= 0 - case Right(b) ⇒ !(b < 0.0 || b.isNaN || b.isInfinite) + case Left(a) => a >= 0 + case Right(b) => !(b < 0.0 || b.isNaN || b.isInfinite) } /** * May involve rounding or truncation. */ def convertNumber(from: Any): Either[Long, Double] = from match { - case n: Int ⇒ Left(n) - case n: Long ⇒ Left(n) - case n: Double ⇒ Right(n) - case n: Float ⇒ Right(n) - case n: BigInt ⇒ Left(n.longValue) - case n: BigDecimal ⇒ Right(n.doubleValue) - case x ⇒ throw new IllegalArgumentException(s"Not a number [$x]") + case n: Int => Left(n) + case n: Long => Left(n) + case n: Double => Right(n) + case n: Float => Right(n) + case n: BigInt => Left(n.longValue) + case n: BigDecimal => Right(n.doubleValue) + case x => throw new IllegalArgumentException(s"Not a number [$x]") } } @@ -296,8 +296,8 @@ final case class NodeMetrics(address: Address, timestamp: Long, metrics: Set[Met val (latestNode, currentNode) = if (this.timestamp >= that.timestamp) (this, that) else (that, this) // Average metrics present in both latest and current. val updated = for { - latest ← latestNode.metrics - current ← currentNode.metrics + latest <- latestNode.metrics + current <- currentNode.metrics if (latest sameAs current) } yield { current :+ latest @@ -308,7 +308,7 @@ final case class NodeMetrics(address: Address, timestamp: Long, metrics: Set[Met copy(metrics = merged, timestamp = latestNode.timestamp) } - def metric(key: String): Option[Metric] = metrics.collectFirst { case m if m.name == key ⇒ m } + def metric(key: String): Option[Metric] = metrics.collectFirst { case m if m.name == key => m } /** * Java API @@ -323,8 +323,8 @@ final case class NodeMetrics(address: Address, timestamp: Long, metrics: Set[Met override def hashCode = address.## override def equals(obj: Any) = obj match { - case other: NodeMetrics ⇒ sameAs(other) - case _ ⇒ false + case other: NodeMetrics => sameAs(other) + case _ => false } } @@ -359,20 +359,20 @@ private[metrics] final case class MetricsGossip(nodes: Set[NodeMetrics]) { * Adds new remote [[NodeMetrics]] and merges existing from a remote gossip. */ def merge(otherGossip: MetricsGossip): MetricsGossip = - otherGossip.nodes.foldLeft(this) { (gossip, nodeMetrics) ⇒ gossip :+ nodeMetrics } + otherGossip.nodes.foldLeft(this) { (gossip, nodeMetrics) => gossip :+ nodeMetrics } /** * Adds new local [[NodeMetrics]], or merges an existing. */ def :+(newNodeMetrics: NodeMetrics): MetricsGossip = nodeMetricsFor(newNodeMetrics.address) match { - case Some(existingNodeMetrics) ⇒ + case Some(existingNodeMetrics) => copy(nodes = nodes - existingNodeMetrics + (existingNodeMetrics update newNodeMetrics)) - case None ⇒ copy(nodes = nodes + newNodeMetrics) + case None => copy(nodes = nodes + newNodeMetrics) } /** * Returns [[NodeMetrics]] for a node if exists. */ - def nodeMetricsFor(address: Address): Option[NodeMetrics] = nodes find { n ⇒ n.address == address } + def nodeMetricsFor(address: Address): Option[NodeMetrics] = nodes find { n => n.address == address } } diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/MetricsCollector.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/MetricsCollector.scala index d140b5aff2..834c0a4994 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/MetricsCollector.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/MetricsCollector.scala @@ -13,7 +13,7 @@ import java.lang.management.MemoryMXBean import java.lang.management.ManagementFactory import java.lang.management.OperatingSystemMXBean import java.lang.management.MemoryUsage -import java.lang.System.{ currentTimeMillis ⇒ newTimestamp } +import java.lang.System.{ currentTimeMillis => newTimestamp } import akka.cluster.Cluster import java.io.Closeable import org.hyperic.sigar.SigarProxy @@ -60,7 +60,7 @@ private[metrics] object MetricsCollector { def create(provider: String) = TryNative { log.debug(s"Trying ${provider}.") system.asInstanceOf[ExtendedActorSystem].dynamicAccess - .createInstanceFor[MetricsCollector](provider, List(classOf[ActorSystem] → system)).get + .createInstanceFor[MetricsCollector](provider, List(classOf[ActorSystem] -> system)).get } val collector = if (useCustom) @@ -71,7 +71,7 @@ private[metrics] object MetricsCollector { create(collectorCustom) orElse create(collectorSigar) orElse create(collectorJMX) collector.recover { - case e ⇒ throw new ConfigurationException(s"Could not create metrics collector: ${e}") + case e => throw new ConfigurationException(s"Could not create metrics collector: ${e}") }.get } } diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/Provision.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/Provision.scala index cb42dbb73c..8848e6b964 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/Provision.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/Provision.scala @@ -39,7 +39,7 @@ trait SigarProvider { SigarProvider.close(sigar) true } catch { - case e: Throwable ⇒ false + case e: Throwable => false } /** Create sigar and verify it works. */ @@ -68,7 +68,7 @@ trait SigarProvider { provisionSigarLibrary() verifiedSigarInstance } recover { - case e: Throwable ⇒ throw new RuntimeException("Failed to load sigar:", e) + case e: Throwable => throw new RuntimeException("Failed to load sigar:", e) } get } @@ -96,9 +96,9 @@ case class DefaultSigarProvider(settings: ClusterMetricsSettings) extends SigarP * INTERNAL API */ private[metrics] object TryNative { - def apply[T](r: ⇒ T): Try[T] = + def apply[T](r: => T): Try[T] = try Success(r) catch { // catching all, for example java.lang.LinkageError that are not caught by `NonFatal` in `Try` - case e: Throwable ⇒ Failure(e) + case e: Throwable => Failure(e) } } diff --git a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/protobuf/MessageSerializer.scala b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/protobuf/MessageSerializer.scala index daed4644c1..6d5f0966c9 100644 --- a/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/protobuf/MessageSerializer.scala +++ b/akka-cluster-metrics/src/main/scala/akka/cluster/metrics/protobuf/MessageSerializer.scala @@ -6,10 +6,10 @@ package akka.cluster.metrics.protobuf import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, ObjectOutputStream } import java.util.zip.{ GZIPInputStream, GZIPOutputStream } -import java.{ lang ⇒ jl } +import java.{ lang => jl } import akka.actor.{ Address, ExtendedActorSystem } -import akka.cluster.metrics.protobuf.msg.{ ClusterMetricsMessages ⇒ cm } +import akka.cluster.metrics.protobuf.msg.{ ClusterMetricsMessages => cm } import akka.cluster.metrics._ import akka.serialization.{ BaseSerializer, SerializationExtension, Serializers, SerializerWithStringManifest } import akka.util.ClassLoaderObjectInputStream @@ -40,24 +40,24 @@ class MessageSerializer(val system: ExtendedActorSystem) extends SerializerWithS private lazy val serialization = SerializationExtension(system) override def manifest(obj: AnyRef): String = obj match { - case _: MetricsGossipEnvelope ⇒ MetricsGossipEnvelopeManifest - case _: AdaptiveLoadBalancingPool ⇒ AdaptiveLoadBalancingPoolManifest - case _: MixMetricsSelector ⇒ MixMetricsSelectorManifest - case CpuMetricsSelector ⇒ CpuMetricsSelectorManifest - case HeapMetricsSelector ⇒ HeapMetricsSelectorManifest - case SystemLoadAverageMetricsSelector ⇒ SystemLoadAverageMetricsSelectorManifest - case _ ⇒ + case _: MetricsGossipEnvelope => MetricsGossipEnvelopeManifest + case _: AdaptiveLoadBalancingPool => AdaptiveLoadBalancingPoolManifest + case _: MixMetricsSelector => MixMetricsSelectorManifest + case CpuMetricsSelector => CpuMetricsSelectorManifest + case HeapMetricsSelector => HeapMetricsSelectorManifest + case SystemLoadAverageMetricsSelector => SystemLoadAverageMetricsSelectorManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: MetricsGossipEnvelope ⇒ compress(metricsGossipEnvelopeToProto(m)) - case alb: AdaptiveLoadBalancingPool ⇒ adaptiveLoadBalancingPoolToBinary(alb) - case mms: MixMetricsSelector ⇒ mixMetricSelectorToBinary(mms) - case CpuMetricsSelector ⇒ Array.emptyByteArray - case HeapMetricsSelector ⇒ Array.emptyByteArray - case SystemLoadAverageMetricsSelector ⇒ Array.emptyByteArray - case _ ⇒ + case m: MetricsGossipEnvelope => compress(metricsGossipEnvelopeToProto(m)) + case alb: AdaptiveLoadBalancingPool => adaptiveLoadBalancingPoolToBinary(alb) + case mms: MixMetricsSelector => mixMetricSelectorToBinary(mms) + case CpuMetricsSelector => Array.emptyByteArray + case HeapMetricsSelector => Array.emptyByteArray + case SystemLoadAverageMetricsSelector => Array.emptyByteArray + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } @@ -75,8 +75,8 @@ class MessageSerializer(val system: ExtendedActorSystem) extends SerializerWithS val buffer = new Array[Byte](BufferSize) @tailrec def readChunk(): Unit = in.read(buffer) match { - case -1 ⇒ () - case n ⇒ + case -1 => () + case n => out.write(buffer, 0, n) readChunk() } @@ -87,20 +87,20 @@ class MessageSerializer(val system: ExtendedActorSystem) extends SerializerWithS } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case MetricsGossipEnvelopeManifest ⇒ metricsGossipEnvelopeFromBinary(bytes) - case AdaptiveLoadBalancingPoolManifest ⇒ adaptiveLoadBalancingPoolFromBinary(bytes) - case MixMetricsSelectorManifest ⇒ mixMetricSelectorFromBinary(bytes) - case CpuMetricsSelectorManifest ⇒ CpuMetricsSelector - case HeapMetricsSelectorManifest ⇒ HeapMetricsSelector - case SystemLoadAverageMetricsSelectorManifest ⇒ SystemLoadAverageMetricsSelector - case _ ⇒ throw new NotSerializableException( + case MetricsGossipEnvelopeManifest => metricsGossipEnvelopeFromBinary(bytes) + case AdaptiveLoadBalancingPoolManifest => adaptiveLoadBalancingPoolFromBinary(bytes) + case MixMetricsSelectorManifest => mixMetricSelectorFromBinary(bytes) + case CpuMetricsSelectorManifest => CpuMetricsSelector + case HeapMetricsSelectorManifest => HeapMetricsSelector + case SystemLoadAverageMetricsSelectorManifest => SystemLoadAverageMetricsSelector + case _ => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}") } private def addressToProto(address: Address): cm.Address.Builder = address match { - case Address(protocol, actorSystem, Some(host), Some(port)) ⇒ + case Address(protocol, actorSystem, Some(host), Some(port)) => cm.Address.newBuilder().setSystem(actorSystem).setHostname(host).setPort(port).setProtocol(protocol) - case _ ⇒ throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") } def adaptiveLoadBalancingPoolToBinary(alb: AdaptiveLoadBalancingPool): Array[Byte] = { @@ -132,7 +132,7 @@ class MessageSerializer(val system: ExtendedActorSystem) extends SerializerWithS private def mixMetricSelectorToBinary(mms: MixMetricsSelector): Array[Byte] = { val builder = cm.MixMetricsSelector.newBuilder() - mms.selectors.foreach { selector ⇒ + mms.selectors.foreach { selector => builder.addSelectors(metricsSelectorToProto(selector)) } builder.build().toByteArray @@ -167,32 +167,32 @@ class MessageSerializer(val system: ExtendedActorSystem) extends SerializerWithS Address(getProtocol(address), getSystem(address), address.getHostname, address.getPort) private def mapWithErrorMessage[T](map: Map[T, Int], value: T, unknown: String): Int = map.get(value) match { - case Some(x) ⇒ x - case _ ⇒ throw new IllegalArgumentException(s"Unknown $unknown [$value] in cluster message") + case Some(x) => x + case _ => throw new IllegalArgumentException(s"Unknown $unknown [$value] in cluster message") } private def metricsGossipEnvelopeToProto(envelope: MetricsGossipEnvelope): cm.MetricsGossipEnvelope = { val allNodeMetrics = envelope.gossip.nodes val allAddresses: Vector[Address] = allNodeMetrics.iterator.map(_.address).to(immutable.Vector) val addressMapping = allAddresses.zipWithIndex.toMap - val allMetricNames: Vector[String] = allNodeMetrics.foldLeft(Set.empty[String])((s, n) ⇒ s ++ n.metrics.iterator.map(_.name)).toVector + val allMetricNames: Vector[String] = allNodeMetrics.foldLeft(Set.empty[String])((s, n) => s ++ n.metrics.iterator.map(_.name)).toVector val metricNamesMapping = allMetricNames.zipWithIndex.toMap def mapAddress(address: Address) = mapWithErrorMessage(addressMapping, address, "address") def mapName(name: String) = mapWithErrorMessage(metricNamesMapping, name, "address") def ewmaToProto(ewma: Option[EWMA]): Option[cm.NodeMetrics.EWMA.Builder] = ewma.map { - x ⇒ cm.NodeMetrics.EWMA.newBuilder().setValue(x.value).setAlpha(x.alpha) + x => cm.NodeMetrics.EWMA.newBuilder().setValue(x.value).setAlpha(x.alpha) } def numberToProto(number: Number): cm.NodeMetrics.Number.Builder = { import cm.NodeMetrics.Number import cm.NodeMetrics.NumberType number match { - case n: jl.Double ⇒ Number.newBuilder().setType(NumberType.Double).setValue64(jl.Double.doubleToLongBits(n)) - case n: jl.Long ⇒ Number.newBuilder().setType(NumberType.Long).setValue64(n) - case n: jl.Float ⇒ Number.newBuilder().setType(NumberType.Float).setValue32(jl.Float.floatToIntBits(n)) - case n: jl.Integer ⇒ Number.newBuilder().setType(NumberType.Integer).setValue32(n) - case _ ⇒ + case n: jl.Double => Number.newBuilder().setType(NumberType.Double).setValue64(jl.Double.doubleToLongBits(n)) + case n: jl.Long => Number.newBuilder().setType(NumberType.Long).setValue64(n) + case n: jl.Float => Number.newBuilder().setType(NumberType.Float).setValue32(jl.Float.floatToIntBits(n)) + case n: jl.Integer => Number.newBuilder().setType(NumberType.Integer).setValue32(n) + case _ => val bos = new ByteArrayOutputStream val out = new ObjectOutputStream(bos) out.writeObject(number) @@ -232,11 +232,11 @@ class MessageSerializer(val system: ExtendedActorSystem) extends SerializerWithS def numberFromProto(number: cm.NodeMetrics.Number): Number = { import cm.NodeMetrics.NumberType number.getType.getNumber match { - case NumberType.Double_VALUE ⇒ jl.Double.longBitsToDouble(number.getValue64) - case NumberType.Long_VALUE ⇒ number.getValue64 - case NumberType.Float_VALUE ⇒ jl.Float.intBitsToFloat(number.getValue32) - case NumberType.Integer_VALUE ⇒ number.getValue32 - case NumberType.Serialized_VALUE ⇒ + case NumberType.Double_VALUE => jl.Double.longBitsToDouble(number.getValue64) + case NumberType.Long_VALUE => number.getValue64 + case NumberType.Float_VALUE => jl.Float.intBitsToFloat(number.getValue32) + case NumberType.Integer_VALUE => number.getValue32 + case NumberType.Serialized_VALUE => val in = new ClassLoaderObjectInputStream( system.dynamicAccess.classLoader, new ByteArrayInputStream(number.getSerialized.toByteArray)) @@ -284,7 +284,7 @@ class MessageSerializer(val system: ExtendedActorSystem) extends SerializerWithS val mm = cm.MixMetricsSelector.parseFrom(bytes) MixMetricsSelector(mm.getSelectorsList.asScala // should be safe because we serialized only the right subtypes of MetricsSelector - .map(s ⇒ metricSelectorFromProto(s).asInstanceOf[CapacityMetricsSelector]).toIndexedSeq) + .map(s => metricSelectorFromProto(s).asInstanceOf[CapacityMetricsSelector]).toIndexedSeq) } def metricSelectorFromProto(selector: cm.MetricsSelector): MetricsSelector = diff --git a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/ClusterMetricsExtensionSpec.scala b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/ClusterMetricsExtensionSpec.scala index 28594bb5a4..21a711f936 100644 --- a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/ClusterMetricsExtensionSpec.scala +++ b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/ClusterMetricsExtensionSpec.scala @@ -24,7 +24,7 @@ trait ClusterMetricsCommonConfig extends MultiNodeConfig { def nodeList = Seq(node1, node2, node3, node4, node5) // Extract individual sigar library for every node. - nodeList foreach { role ⇒ + nodeList foreach { role => nodeConfig(role) { parseString(s"akka.cluster.metrics.native-library-extract-folder=$${user.dir}/target/native/" + role.name) } @@ -89,7 +89,7 @@ abstract class ClusterMetricsEnabledSpec extends MultiNodeSpec(ClusterMetricsEna val conf = cluster.system.settings.config val text = conf.root.render val file = new File(s"target/${myself.name}_application.conf") - Some(new PrintWriter(file)) map { p ⇒ p.write(text); p.close } + Some(new PrintWriter(file)) map { p => p.write(text); p.close } } saveApplicationConf() diff --git a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/ClusterMetricsRoutingSpec.scala b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/ClusterMetricsRoutingSpec.scala index 0e488777e1..3e4388dc34 100644 --- a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/ClusterMetricsRoutingSpec.scala +++ b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/ClusterMetricsRoutingSpec.scala @@ -27,14 +27,14 @@ object AdaptiveLoadBalancingRouterConfig extends MultiNodeConfig { class Echo extends Actor { def receive = { - case _ ⇒ sender() ! Reply(Cluster(context.system).selfAddress) + case _ => sender() ! Reply(Cluster(context.system).selfAddress) } } class Memory extends Actor with ActorLogging { var usedMemory: Array[Array[Int]] = _ def receive = { - case AllocateMemory ⇒ + case AllocateMemory => val heap = ManagementFactory.getMemoryMXBean.getHeapMemoryUsage // getMax can be undefined (-1) val max = math.max(heap.getMax, heap.getCommitted) @@ -59,7 +59,7 @@ object AdaptiveLoadBalancingRouterConfig extends MultiNodeConfig { def nodeList = Seq(node1, node2, node3) // Extract individual sigar library for every node. - nodeList foreach { role ⇒ + nodeList foreach { role => nodeConfig(role) { ConfigFactory.parseString(s"akka.cluster.metrics.native-library-extract-folder=$${user.dir}/target/native/" + role.name) } @@ -118,11 +118,11 @@ abstract class AdaptiveLoadBalancingRouterSpec extends MultiNodeSpec(AdaptiveLoa Await.result(router ? GetRoutees, timeout.duration).asInstanceOf[Routees].routees def receiveReplies(expectedReplies: Int): Map[Address, Int] = { - val zero = Map.empty[Address, Int] ++ roles.map(address(_) → 0) + val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0) (receiveWhile(5 seconds, messages = expectedReplies) { - case Reply(address) ⇒ address + case Reply(address) => address }).foldLeft(zero) { - case (replyMap, address) ⇒ replyMap + (address → (replyMap(address) + 1)) + case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) } } @@ -130,8 +130,8 @@ abstract class AdaptiveLoadBalancingRouterSpec extends MultiNodeSpec(AdaptiveLoa * Fills in self address for local ActorRef */ def fullAddress(actorRef: ActorRef): Address = actorRef.path.address match { - case Address(_, _, None, None) ⇒ cluster.selfAddress - case a ⇒ a + case Address(_, _, None, None) => cluster.selfAddress + case a => a } def startRouter(name: String): ActorRef = { @@ -144,7 +144,7 @@ abstract class AdaptiveLoadBalancingRouterSpec extends MultiNodeSpec(AdaptiveLoa // it may take some time until router receives cluster member events awaitAssert { currentRoutees(router).size should ===(roles.size) } val routees = currentRoutees(router) - routees.map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) }.toSet should ===(roles.map(address).toSet) + routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet) router } @@ -166,7 +166,7 @@ abstract class AdaptiveLoadBalancingRouterSpec extends MultiNodeSpec(AdaptiveLoa metricsAwait() val iterationCount = 100 - 1 to iterationCount foreach { _ ⇒ + 1 to iterationCount foreach { _ => router1 ! "hit" // wait a while between each message, since metrics is collected periodically Thread.sleep(10) @@ -203,7 +203,7 @@ abstract class AdaptiveLoadBalancingRouterSpec extends MultiNodeSpec(AdaptiveLoa metricsAwait() val iterationCount = 3000 - 1 to iterationCount foreach { _ ⇒ + 1 to iterationCount foreach { _ => router2 ! "hit" } @@ -223,7 +223,7 @@ abstract class AdaptiveLoadBalancingRouterSpec extends MultiNodeSpec(AdaptiveLoa // it may take some time until router receives cluster member events awaitAssert { currentRoutees(router3).size should ===(9) } val routees = currentRoutees(router3) - routees.map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) }.toSet should ===(Set(address(node1))) + routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(Set(address(node1))) } enterBarrier("after-4") } @@ -234,7 +234,7 @@ abstract class AdaptiveLoadBalancingRouterSpec extends MultiNodeSpec(AdaptiveLoa // it may take some time until router receives cluster member events awaitAssert { currentRoutees(router4).size should ===(6) } val routees = currentRoutees(router4) - routees.map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) }.toSet should ===(Set( + routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(Set( address(node1), address(node2), address(node3))) } enterBarrier("after-5") diff --git a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsSampleSpec.scala b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsSampleSpec.scala index 4aabd3578b..a7011ead8e 100644 --- a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsSampleSpec.scala +++ b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsSampleSpec.scala @@ -24,7 +24,7 @@ object StatsSampleSpecConfig extends MultiNodeConfig { def nodeList = Seq(first, second, third) // Extract individual sigar library for every node. - nodeList foreach { role ⇒ + nodeList foreach { role => nodeConfig(role) { ConfigFactory.parseString(s""" # Enable metrics extension in akka-cluster-metrics. @@ -105,7 +105,7 @@ abstract class StatsSampleSpec extends MultiNodeSpec(StatsSampleSpecConfig) system.actorOf(Props[StatsWorker], "statsWorker") system.actorOf(Props[StatsService], "statsService") - receiveN(3).collect { case MemberUp(m) ⇒ m.address }.toSet should be( + receiveN(3).collect { case MemberUp(m) => m.address }.toSet should be( Set(firstAddress, secondAddress, thirdAddress)) Cluster(system).unsubscribe(testActor) diff --git a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsService.scala b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsService.scala index ea72711b11..17a1d9d179 100644 --- a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsService.scala +++ b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsService.scala @@ -20,13 +20,13 @@ class StatsService extends Actor { name = "workerRouter") def receive = { - case StatsJob(text) if text != "" ⇒ + case StatsJob(text) if text != "" => val words = text.split(" ") val replyTo = sender() // important to not close over sender() // create actor that collects replies from workers val aggregator = context.actorOf(Props( classOf[StatsAggregator], words.size, replyTo)) - words foreach { word ⇒ + words foreach { word => workerRouter.tell( ConsistentHashableEnvelope(word, word), aggregator) } @@ -38,14 +38,14 @@ class StatsAggregator(expectedResults: Int, replyTo: ActorRef) extends Actor { context.setReceiveTimeout(3.seconds) def receive = { - case wordCount: Int ⇒ + case wordCount: Int => results = results :+ wordCount if (results.size == expectedResults) { val meanWordLength = results.sum.toDouble / results.size replyTo ! StatsResult(meanWordLength) context.stop(self) } - case ReceiveTimeout ⇒ + case ReceiveTimeout => replyTo ! JobFailed("Service unavailable, try again later") context.stop(self) } diff --git a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsWorker.scala b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsWorker.scala index 0e86920215..0a71f52b85 100644 --- a/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsWorker.scala +++ b/akka-cluster-metrics/src/multi-jvm/scala/akka/cluster/metrics/sample/StatsWorker.scala @@ -10,12 +10,12 @@ import akka.actor.Actor class StatsWorker extends Actor { var cache = Map.empty[String, Int] def receive = { - case word: String ⇒ + case word: String => val length = cache.get(word) match { - case Some(x) ⇒ x - case None ⇒ + case Some(x) => x + case None => val x = word.length - cache += (word → x) + cache += (word -> x) x } diff --git a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/ClusterMetricsExtensionSpec.scala b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/ClusterMetricsExtensionSpec.scala index 8d6065c769..d983b14dd4 100644 --- a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/ClusterMetricsExtensionSpec.scala +++ b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/ClusterMetricsExtensionSpec.scala @@ -72,10 +72,10 @@ class MetricsExtensionSpec extends AkkaSpec(MetricsConfig.clusterSigarMock) expected.size should ===(sampleCount) history.zip(expected) foreach { - case (mockMetrics, expectedData) ⇒ + case (mockMetrics, expectedData) => (mockMetrics, expectedData) match { case (Cpu(_, _, loadAverageMock, cpuCombinedMock, cpuStolenMock, _), - (loadAverageEwma, cpuCombinedEwma, cpuStolenEwma)) ⇒ + (loadAverageEwma, cpuCombinedEwma, cpuStolenEwma)) => loadAverageMock.get should ===(loadAverageEwma +- epsilon) cpuCombinedMock.get should ===(cpuCombinedEwma +- epsilon) cpuStolenMock.get should ===(cpuStolenEwma +- epsilon) @@ -108,7 +108,7 @@ class MetricsExtensionSpec extends AkkaSpec(MetricsConfig.clusterSigarMock) } - (1 to 3) foreach { step ⇒ cycle() } + (1 to 3) foreach { step => cycle() } } diff --git a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/ClusterMetricsRoutingSpec.scala b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/ClusterMetricsRoutingSpec.scala index ada1f89251..109a52334d 100644 --- a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/ClusterMetricsRoutingSpec.scala +++ b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/ClusterMetricsRoutingSpec.scala @@ -63,15 +63,15 @@ class MetricsSelectorSpec extends WordSpec with Matchers { "CapacityMetricsSelector" must { "calculate weights from capacity" in { - val capacity = Map(a1 → 0.6, b1 → 0.3, c1 → 0.1) + val capacity = Map(a1 -> 0.6, b1 -> 0.3, c1 -> 0.1) val weights = abstractSelector.weights(capacity) - weights should ===(Map(c1 → 1, b1 → 3, a1 → 6)) + weights should ===(Map(c1 -> 1, b1 -> 3, a1 -> 6)) } "handle low and zero capacity" in { - val capacity = Map(a1 → 0.0, b1 → 1.0, c1 → 0.005, d1 → 0.004) + val capacity = Map(a1 -> 0.0, b1 -> 1.0, c1 -> 0.005, d1 -> 0.004) val weights = abstractSelector.weights(capacity) - weights should ===(Map(a1 → 0, b1 → 100, c1 → 1, d1 → 0)) + weights should ===(Map(a1 -> 0, b1 -> 100, c1 -> 1, d1 -> 0)) } } diff --git a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/EWMASpec.scala b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/EWMASpec.scala index a957034967..8695ff9c7c 100644 --- a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/EWMASpec.scala +++ b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/EWMASpec.scala @@ -32,7 +32,7 @@ class EWMASpec extends AkkaSpec(MetricsConfig.defaultEnabled) with MetricsCollec val d4 = d3 :+ 10.0 d4.value should ===(453.64 +- 0.01) - val dn = (1 to 100).foldLeft(d0)((d, _) ⇒ d :+ 10.0) + val dn = (1 to 100).foldLeft(d0)((d, _) => d :+ 10.0) dn.value should ===(10.0 +- 0.1) } @@ -75,14 +75,14 @@ class EWMASpec extends AkkaSpec(MetricsConfig.defaultEnabled) with MetricsCollec "calculate the ewma for multiple, variable, data streams" taggedAs LongRunningTest in { var streamingDataSet = Map.empty[String, Metric] var usedMemory = Array.empty[Byte] - (1 to 50) foreach { _ ⇒ + (1 to 50) foreach { _ => // wait a while between each message to give the metrics a chance to change Thread.sleep(100) usedMemory = usedMemory ++ Array.fill(1024)(ThreadLocalRandom.current.nextInt(127).toByte) - val changes = collector.sample.metrics.flatMap { latest ⇒ + val changes = collector.sample.metrics.flatMap { latest => streamingDataSet.get(latest.name) match { - case None ⇒ Some(latest) - case Some(previous) ⇒ + case None => Some(latest) + case Some(previous) => if (latest.isSmooth && latest.value != previous.value) { val updated = previous :+ latest updated.isSmooth should ===(true) @@ -91,7 +91,7 @@ class EWMASpec extends AkkaSpec(MetricsConfig.defaultEnabled) with MetricsCollec } else None } } - streamingDataSet ++= changes.map(m ⇒ m.name → m) + streamingDataSet ++= changes.map(m => m.name -> m) } } } diff --git a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/MetricSpec.scala b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/MetricSpec.scala index 5410280fe4..fe7aa7d5c4 100644 --- a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/MetricSpec.scala +++ b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/MetricSpec.scala @@ -11,7 +11,7 @@ import scala.util.Failure import akka.actor.Address import akka.testkit.AkkaSpec import akka.testkit.ImplicitSender -import java.lang.System.{ currentTimeMillis ⇒ newTimestamp } +import java.lang.System.{ currentTimeMillis => newTimestamp } class MetricNumericConverterSpec extends WordSpec with Matchers with MetricNumericConverter { @@ -172,7 +172,7 @@ class MetricsGossipSpec extends AkkaSpec(MetricsConfig.defaultEnabled) with Impl g2.nodes.size should ===(2) g2.nodeMetricsFor(m1.address).map(_.metrics) should ===(Some(m1.metrics)) g2.nodeMetricsFor(m2.address).map(_.metrics) should ===(Some(m2Updated.metrics)) - g2.nodes collect { case peer if peer.address == m2.address ⇒ peer.timestamp should ===(m2Updated.timestamp) } + g2.nodes collect { case peer if peer.address == m2.address => peer.timestamp should ===(m2Updated.timestamp) } } "merge an existing metric set for a node and update node ring" in { @@ -239,10 +239,10 @@ class MetricValuesSpec extends AkkaSpec(MetricsConfig.defaultEnabled) with Metri val node2 = NodeMetrics(Address("akka.tcp", "sys", "a", 2555), 1, collector.sample.metrics) val nodes: Seq[NodeMetrics] = { - (1 to 100).foldLeft(List(node1, node2)) { (nodes, _) ⇒ - nodes map { n ⇒ - n.copy(metrics = collector.sample.metrics.flatMap(latest ⇒ n.metrics.collect { - case streaming if latest sameAs streaming ⇒ streaming :+ latest + (1 to 100).foldLeft(List(node1, node2)) { (nodes, _) => + nodes map { n => + n.copy(metrics = collector.sample.metrics.flatMap(latest => n.metrics.collect { + case streaming if latest sameAs streaming => streaming :+ latest })) } } @@ -256,9 +256,9 @@ class MetricValuesSpec extends AkkaSpec(MetricsConfig.defaultEnabled) with Metri } "extract expected MetricValue types for load balancing" in { - nodes foreach { node ⇒ + nodes foreach { node => node match { - case HeapMemory(address, _, used, committed, _) ⇒ + case HeapMemory(address, _, used, committed, _) => used should be > (0L) committed should be >= (used) // Documentation java.lang.management.MemoryUsage says that committed <= max, @@ -269,7 +269,7 @@ class MetricValuesSpec extends AkkaSpec(MetricsConfig.defaultEnabled) with Metri } node match { - case Cpu(address, _, systemLoadAverageOption, cpuCombinedOption, cpuStolenOption, processors) ⇒ + case Cpu(address, _, systemLoadAverageOption, cpuCombinedOption, cpuStolenOption, processors) => processors should be > (0) if (systemLoadAverageOption.isDefined) systemLoadAverageOption.get should be >= (0.0) diff --git a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/MetricsCollectorSpec.scala b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/MetricsCollectorSpec.scala index 66fc6c3751..cf7686caa5 100644 --- a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/MetricsCollectorSpec.scala +++ b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/MetricsCollectorSpec.scala @@ -19,11 +19,11 @@ class MetricsCollectorSpec extends AkkaSpec(MetricsConfig.defaultEnabled) with I "Metric must" must { "merge 2 metrics that are tracking the same metric" in { - for (i ← 1 to 20) { + for (i <- 1 to 20) { val sample1 = collector.sample.metrics val sample2 = collector.sample.metrics - val merged12 = sample2 flatMap (latest ⇒ sample1 collect { - case peer if latest sameAs peer ⇒ + val merged12 = sample2 flatMap (latest => sample1 collect { + case peer if latest sameAs peer => val m = peer :+ latest m.value should ===(latest.value) m.isSmooth should ===(peer.isSmooth || latest.isSmooth) @@ -32,8 +32,8 @@ class MetricsCollectorSpec extends AkkaSpec(MetricsConfig.defaultEnabled) with I val sample3 = collector.sample.metrics val sample4 = collector.sample.metrics - val merged34 = sample4 flatMap (latest ⇒ sample3 collect { - case peer if latest sameAs peer ⇒ + val merged34 = sample4 flatMap (latest => sample3 collect { + case peer if latest sameAs peer => val m = peer :+ latest m.value should ===(latest.value) m.isSmooth should ===(peer.isSmooth || latest.isSmooth) @@ -51,22 +51,22 @@ class MetricsCollectorSpec extends AkkaSpec(MetricsConfig.defaultEnabled) with I "collect accurate metrics for a node" in { val sample = collector.sample - val metrics = sample.metrics.collect { case m ⇒ (m.name, m.value) } - val used = metrics collectFirst { case (HeapMemoryUsed, b) ⇒ b } - val committed = metrics collectFirst { case (HeapMemoryCommitted, b) ⇒ b } + val metrics = sample.metrics.collect { case m => (m.name, m.value) } + val used = metrics collectFirst { case (HeapMemoryUsed, b) => b } + val committed = metrics collectFirst { case (HeapMemoryCommitted, b) => b } metrics foreach { - case (SystemLoadAverage, b) ⇒ b.doubleValue should be >= (0.0) - case (Processors, b) ⇒ b.intValue should be >= (0) - case (HeapMemoryUsed, b) ⇒ b.longValue should be >= (0L) - case (HeapMemoryCommitted, b) ⇒ b.longValue should be > (0L) - case (HeapMemoryMax, b) ⇒ + case (SystemLoadAverage, b) => b.doubleValue should be >= (0.0) + case (Processors, b) => b.intValue should be >= (0) + case (HeapMemoryUsed, b) => b.longValue should be >= (0L) + case (HeapMemoryCommitted, b) => b.longValue should be > (0L) + case (HeapMemoryMax, b) => b.longValue should be > (0L) used.get.longValue should be <= (b.longValue) committed.get.longValue should be <= (b.longValue) - case (CpuCombined, b) ⇒ + case (CpuCombined, b) => b.doubleValue should be <= (1.0) b.doubleValue should be >= (0.0) - case (CpuStolen, b) ⇒ + case (CpuStolen, b) => b.doubleValue should be <= (1.0) b.doubleValue should be >= (0.0) @@ -85,7 +85,7 @@ class MetricsCollectorSpec extends AkkaSpec(MetricsConfig.defaultEnabled) with I } "collect 50 node metrics samples in an acceptable duration" taggedAs LongRunningTest in within(10 seconds) { - (1 to 50) foreach { _ ⇒ + (1 to 50) foreach { _ => val sample = collector.sample sample.metrics.size should be >= (3) Thread.sleep(100) diff --git a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/TestUtil.scala b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/TestUtil.scala index cd71a9ccae..4f019da715 100644 --- a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/TestUtil.scala +++ b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/TestUtil.scala @@ -93,7 +93,7 @@ case class MockitoSigarProvider( * * TODO change factory after https://github.com/akka/akka/issues/16369 */ -trait MetricsCollectorFactory { this: AkkaSpec ⇒ +trait MetricsCollectorFactory { this: AkkaSpec => import MetricsConfig._ import org.hyperic.sigar.Sigar @@ -106,7 +106,7 @@ trait MetricsCollectorFactory { this: AkkaSpec ⇒ new SigarMetricsCollector(selfAddress, defaultDecayFactor, new Sigar()) //new SigarMetricsCollector(selfAddress, defaultDecayFactor, SimpleSigarProvider().createSigarInstance) } catch { - case e: Throwable ⇒ + case e: Throwable => log.warning("Sigar failed to load. Using JMX. Reason: " + e.toString) new JmxMetricsCollector(selfAddress, defaultDecayFactor) } @@ -206,10 +206,10 @@ class ClusterMetricsView(system: ExtendedActorSystem) extends Closeable { override def preStart(): Unit = extension.subscribe(self) override def postStop(): Unit = extension.unsubscribe(self) def receive = { - case ClusterMetricsChanged(nodes) ⇒ + case ClusterMetricsChanged(nodes) => currentMetricsSet = nodes collectedMetricsList = nodes :: collectedMetricsList - case _ ⇒ + case _ => // Ignore. } }).withDispatcher(Dispatchers.DefaultDispatcherId).withDeploy(Deploy.local), name = "metrics-event-bus-listener") diff --git a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/WeightedRouteesSpec.scala b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/WeightedRouteesSpec.scala index b56fd2b04d..0e865da070 100644 --- a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/WeightedRouteesSpec.scala +++ b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/WeightedRouteesSpec.scala @@ -37,7 +37,7 @@ class WeightedRouteesSpec extends AkkaSpec(ConfigFactory.parseString(""" "WeightedRoutees" must { "allocate weighted routees" in { - val weights = Map(a1 → 1, b1 → 3, c1 → 10) + val weights = Map(a1 -> 1, b1 -> 3, c1 -> 10) val weighted = new WeightedRoutees(routees, a1, weights) weighted(1) should ===(routeeA) @@ -53,7 +53,7 @@ class WeightedRouteesSpec extends AkkaSpec(ConfigFactory.parseString(""" empty.total } - val empty2 = new WeightedRoutees(Vector(routeeA), a1, Map(a1 → 0)) + val empty2 = new WeightedRoutees(Vector(routeeA), a1, Map(a1 -> 0)) empty2.isEmpty should ===(true) intercept[IllegalArgumentException] { empty2.total @@ -73,7 +73,7 @@ class WeightedRouteesSpec extends AkkaSpec(ConfigFactory.parseString(""" } "allocate routees for undefined weight" in { - val weights = Map(a1 → 1, b1 → 7) + val weights = Map(a1 -> 1, b1 -> 7) val weighted = new WeightedRoutees(routees, a1, weights) weighted(1) should ===(routeeA) @@ -84,7 +84,7 @@ class WeightedRouteesSpec extends AkkaSpec(ConfigFactory.parseString(""" } "allocate weighted local routees" in { - val weights = Map(a1 → 2, b1 → 1, c1 → 10) + val weights = Map(a1 -> 2, b1 -> 1, c1 -> 10) val routees2 = Vector(testActorRoutee, routeeB, routeeC) val weighted = new WeightedRoutees(routees2, a1, weights) @@ -93,7 +93,7 @@ class WeightedRouteesSpec extends AkkaSpec(ConfigFactory.parseString(""" } "not allocate ref with weight zero" in { - val weights = Map(a1 → 0, b1 → 2, c1 → 10) + val weights = Map(a1 -> 0, b1 -> 2, c1 -> 10) val weighted = new WeightedRoutees(routees, a1, weights) 1 to weighted.total foreach { weighted(_) should not be (routeeA) } diff --git a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/protobuf/MessageSerializerSpec.scala b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/protobuf/MessageSerializerSpec.scala index 702a82c6a1..a0e0d7a62c 100644 --- a/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/protobuf/MessageSerializerSpec.scala +++ b/akka-cluster-metrics/src/test/scala/akka/cluster/metrics/protobuf/MessageSerializerSpec.scala @@ -24,7 +24,7 @@ class MessageSerializerSpec extends AkkaSpec( val blob = serializer.toBinary(obj) val ref = serializer.fromBinary(blob, serializer.manifest(obj)) obj match { - case _ ⇒ + case _ => ref should ===(obj) } diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/ClusterShardingSettings.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/ClusterShardingSettings.scala index 0759556e21..6881a6f5ab 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/ClusterShardingSettings.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/ClusterShardingSettings.scala @@ -9,8 +9,8 @@ import akka.actor.NoSerializationVerificationNeeded import akka.actor.typed.ActorSystem import akka.annotation.InternalApi import akka.cluster.ClusterSettings.DataCenter -import akka.cluster.sharding.{ ClusterShardingSettings ⇒ UntypedShardingSettings } -import akka.cluster.singleton.{ ClusterSingletonManagerSettings ⇒ UntypedClusterSingletonManagerSettings } +import akka.cluster.sharding.{ ClusterShardingSettings => UntypedShardingSettings } +import akka.cluster.singleton.{ ClusterSingletonManagerSettings => UntypedClusterSingletonManagerSettings } import akka.cluster.typed.Cluster import akka.cluster.typed.ClusterSingletonManagerSettings import com.typesafe.config.Config diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/ShardingMessageExtractor.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/ShardingMessageExtractor.scala index 8e15dbc624..395d5bc16b 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/ShardingMessageExtractor.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/ShardingMessageExtractor.scala @@ -26,7 +26,7 @@ object ShardingMessageExtractor { def noEnvelope[M]( numberOfShards: Int, stopMessage: M)( - extractEntityId: M ⇒ String): ShardingMessageExtractor[M, M] = + extractEntityId: M => String): ShardingMessageExtractor[M, M] = new HashCodeNoEnvelopeMessageExtractor[M](numberOfShards) { def entityId(message: M) = extractEntityId(message) } diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ClusterShardingImpl.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ClusterShardingImpl.scala index e3fd4318f6..53f22e9c09 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ClusterShardingImpl.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ClusterShardingImpl.scala @@ -31,12 +31,12 @@ import akka.annotation.InternalApi import akka.cluster.sharding.ShardCoordinator.LeastShardAllocationStrategy import akka.cluster.sharding.ShardCoordinator.ShardAllocationStrategy import akka.cluster.sharding.ShardRegion -import akka.cluster.sharding.ShardRegion.{ StartEntity ⇒ UntypedStartEntity } +import akka.cluster.sharding.ShardRegion.{ StartEntity => UntypedStartEntity } import akka.cluster.sharding.typed.scaladsl.EntityContext import akka.cluster.typed.Cluster import akka.event.Logging import akka.event.LoggingAdapter -import akka.japi.function.{ Function ⇒ JFunction } +import akka.japi.function.{ Function => JFunction } import akka.pattern.AskTimeoutException import akka.pattern.PromiseActorRef import akka.persistence.typed.PersistenceId @@ -52,9 +52,9 @@ import akka.util.Timeout extends ShardingMessageExtractor[Any, M] { override def entityId(message: Any): String = { message match { - case ShardingEnvelope(entityId, _) ⇒ entityId //also covers UntypedStartEntity in ShardingEnvelope - case UntypedStartEntity(entityId) ⇒ entityId - case msg: E @unchecked ⇒ delegate.entityId(msg) + case ShardingEnvelope(entityId, _) => entityId //also covers UntypedStartEntity in ShardingEnvelope + case UntypedStartEntity(entityId) => entityId + case msg: E @unchecked => delegate.entityId(msg) } } @@ -62,13 +62,13 @@ import akka.util.Timeout override def unwrapMessage(message: Any): M = { message match { - case ShardingEnvelope(_, msg: M @unchecked) ⇒ + case ShardingEnvelope(_, msg: M @unchecked) => //also covers UntypedStartEntity in ShardingEnvelope msg - case msg: UntypedStartEntity ⇒ + case msg: UntypedStartEntity => // not really of type M, but erased and StartEntity is only handled internally, not delivered to the entity msg.asInstanceOf[M] - case msg: E @unchecked ⇒ + case msg: E @unchecked => delegate.unwrapMessage(msg) } } @@ -135,13 +135,13 @@ import akka.util.Timeout // scaladsl impl override def init[M, E](entity: scaladsl.Entity[M, E]): ActorRef[E] = { val settings = entity.settings match { - case None ⇒ ClusterShardingSettings(system) - case Some(s) ⇒ s + case None => ClusterShardingSettings(system) + case Some(s) => s } val extractor = (entity.messageExtractor match { - case None ⇒ new HashCodeMessageExtractor[M](settings.numberOfShards) - case Some(e) ⇒ e + case None => new HashCodeMessageExtractor[M](settings.numberOfShards) + case Some(e) => e }).asInstanceOf[ShardingMessageExtractor[E, M]] internalInit(entity.createBehavior, entity.entityProps, entity.typeKey, @@ -152,7 +152,7 @@ import akka.util.Timeout override def init[M, E](entity: javadsl.Entity[M, E]): ActorRef[E] = { import scala.compat.java8.OptionConverters._ init(new scaladsl.Entity( - createBehavior = (ctx: EntityContext) ⇒ Behaviors.setup[M] { actorContext ⇒ + createBehavior = (ctx: EntityContext) => Behaviors.setup[M] { actorContext => entity.createBehavior( new javadsl.EntityContext[M](ctx.entityId, ctx.shard, actorContext.asJava)) }, @@ -166,7 +166,7 @@ import akka.util.Timeout } private def internalInit[M, E]( - behavior: EntityContext ⇒ Behavior[M], + behavior: EntityContext => Behavior[M], entityProps: Props, typeKey: scaladsl.EntityTypeKey[M], stopMessage: Option[M], @@ -177,13 +177,13 @@ import akka.util.Timeout val extractorAdapter = new ExtractorAdapter(extractor) val extractEntityId: ShardRegion.ExtractEntityId = { // TODO is it possible to avoid the double evaluation of entityId - case message if extractorAdapter.entityId(message) != null ⇒ + case message if extractorAdapter.entityId(message) != null => (extractorAdapter.entityId(message), extractorAdapter.unwrapMessage(message)) } - val extractShardId: ShardRegion.ExtractShardId = { message ⇒ + val extractShardId: ShardRegion.ExtractShardId = { message => extractorAdapter.entityId(message) match { - case null ⇒ null - case eid ⇒ extractorAdapter.shardId(eid) + case null => null + case eid => extractorAdapter.shardId(eid) } } @@ -205,12 +205,12 @@ import akka.util.Timeout def poisonPillInterceptor(behv: Behavior[M]): Behavior[M] = { stopMessage match { - case Some(_) ⇒ behv - case None ⇒ Behaviors.intercept(new PoisonPillInterceptor[M])(behv) + case Some(_) => behv + case None => Behaviors.intercept(new PoisonPillInterceptor[M])(behv) } } - val untypedEntityPropsFactory: String ⇒ akka.actor.Props = { entityId ⇒ + val untypedEntityPropsFactory: String => akka.actor.Props = { entityId => val behv = behavior(new EntityContext(entityId, shardCommandDelegator)) PropsAdapter(poisonPillInterceptor(behv), entityProps) } @@ -239,9 +239,9 @@ import akka.util.Timeout val typeNames = if (settings.shouldHostShard(cluster)) regions else proxies typeNames.putIfAbsent(typeKey.name, messageClassName) match { - case spawnedMessageClassName: String if messageClassName != spawnedMessageClassName ⇒ + case spawnedMessageClassName: String if messageClassName != spawnedMessageClassName => throw new IllegalArgumentException(s"[${typeKey.name}] already initialized for [$spawnedMessageClassName]") - case _ ⇒ () + case _ => () } ActorRefAdapter(ref) @@ -281,7 +281,7 @@ import akka.util.Timeout override def tell(msg: M): Unit = shardRegion ! ShardingEnvelope(entityId, msg) - override def ask[U](message: ActorRef[U] ⇒ M)(implicit timeout: Timeout): Future[U] = { + override def ask[U](message: ActorRef[U] => M)(implicit timeout: Timeout): Future[U] = { val replyTo = new EntityPromiseRef[U](shardRegion.asInstanceOf[InternalActorRef], timeout) val m = message(replyTo.ref) if (replyTo.promiseRef ne null) replyTo.promiseRef.messageClassName = m.getClass.getName @@ -290,12 +290,12 @@ import akka.util.Timeout } def ask[U](message: JFunction[ActorRef[U], M], timeout: Timeout): CompletionStage[U] = - ask[U](replyTo ⇒ message.apply(replyTo))(timeout).toJava + ask[U](replyTo => message.apply(replyTo))(timeout).toJava /** Similar to [[akka.actor.typed.scaladsl.AskPattern.PromiseRef]] but for an `EntityRef` target. */ @InternalApi private final class EntityPromiseRef[U](untyped: InternalActorRef, timeout: Timeout) { - import akka.actor.typed.internal.{ adapter ⇒ adapt } + import akka.actor.typed.internal.{ adapter => adapt } // Note: _promiseRef mustn't have a type pattern, since it can be null private[this] val (_ref: ActorRef[U], _future: Future[U], _promiseRef) = @@ -345,7 +345,7 @@ import akka.util.Timeout */ @InternalApi private[akka] object ShardCommandActor { import akka.actor.typed.scaladsl.adapter._ - import akka.cluster.sharding.ShardRegion.{ Passivate ⇒ UntypedPassivate } + import akka.cluster.sharding.ShardRegion.{ Passivate => UntypedPassivate } def behavior(stopMessage: Any): Behavior[scaladsl.ClusterSharding.ShardCommand] = { def sendUntypedPassivate(entity: ActorRef[_], ctx: TypedActorContext[_]): Unit = { @@ -353,15 +353,15 @@ import akka.util.Timeout ctx.asScala.system.toUntyped.actorSelection(pathToShard).tell(UntypedPassivate(stopMessage), entity.toUntyped) } - Behaviors.receive { (ctx, msg) ⇒ + Behaviors.receive { (ctx, msg) => msg match { - case scaladsl.ClusterSharding.Passivate(entity) ⇒ + case scaladsl.ClusterSharding.Passivate(entity) => sendUntypedPassivate(entity, ctx) Behaviors.same - case javadsl.ClusterSharding.Passivate(entity) ⇒ + case javadsl.ClusterSharding.Passivate(entity) => sendUntypedPassivate(entity, ctx) Behaviors.same - case _ ⇒ + case _ => Behaviors.unhandled } } diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/JoinConfigCompatCheckerClusterSharding.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/JoinConfigCompatCheckerClusterSharding.scala index 13d9116a8d..8a5e92f17a 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/JoinConfigCompatCheckerClusterSharding.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/JoinConfigCompatCheckerClusterSharding.scala @@ -8,7 +8,7 @@ import akka.annotation.InternalApi import akka.cluster.{ ConfigValidation, JoinConfigCompatChecker, Valid } import com.typesafe.config.Config -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } /** * INTERNAL API diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ShardingSerializer.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ShardingSerializer.scala index 0b749f26b7..653ddb4fcd 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ShardingSerializer.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ShardingSerializer.scala @@ -24,29 +24,29 @@ import akka.serialization.SerializerWithStringManifest private val ShardingEnvelopeManifest = "a" override def manifest(o: AnyRef): String = o match { - case ref: ShardingEnvelope[_] ⇒ ShardingEnvelopeManifest - case _ ⇒ + case ref: ShardingEnvelope[_] => ShardingEnvelopeManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass} in [${getClass.getName}]") } override def toBinary(o: AnyRef): Array[Byte] = o match { - case env: ShardingEnvelope[_] ⇒ + case env: ShardingEnvelope[_] => val builder = ShardingMessages.ShardingEnvelope.newBuilder() builder.setEntityId(env.entityId) builder.setMessage(payloadSupport.payloadBuilder(env.message)) builder.build().toByteArray() - case _ ⇒ + case _ => throw new IllegalArgumentException(s"Cannot serialize object of type [${o.getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case ShardingEnvelopeManifest ⇒ + case ShardingEnvelopeManifest => val env = ShardingMessages.ShardingEnvelope.parseFrom(bytes) val entityId = env.getEntityId val wrappedMsg = payloadSupport.deserializePayload(env.getMessage) ShardingEnvelope(entityId, wrappedMsg) - case _ ⇒ + case _ => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ShardingState.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ShardingState.scala index 0fc7210129..bc53191ea7 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ShardingState.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/internal/ShardingState.scala @@ -18,7 +18,7 @@ import akka.cluster.sharding.typed.{ ClusterShardingQuery, GetShardRegionState } object ShardingState { def behavior(untypedSharding: ClusterSharding): Behavior[ClusterShardingQuery] = Behaviors.receiveMessage { - case GetShardRegionState(key, replyTo) ⇒ + case GetShardRegionState(key, replyTo) => if (untypedSharding.getShardTypeNames.contains(key.name)) { untypedSharding.shardRegion(key.name).tell(ShardRegion.GetShardRegionState, replyTo.toUntyped) } else { diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/javadsl/ClusterSharding.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/javadsl/ClusterSharding.scala index 531bb15391..948cb89969 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/javadsl/ClusterSharding.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/javadsl/ClusterSharding.scala @@ -19,7 +19,7 @@ import akka.annotation.DoNotInherit import akka.annotation.InternalApi import akka.cluster.sharding.ShardCoordinator.ShardAllocationStrategy import akka.cluster.sharding.typed.internal.EntityTypeKeyImpl -import akka.japi.function.{ Function ⇒ JFunction } +import akka.japi.function.{ Function => JFunction } import akka.persistence.typed.PersistenceId import akka.util.Timeout @@ -342,7 +342,7 @@ object StartEntity { * * Not for user extension. */ -@DoNotInherit abstract class EntityTypeKey[T] { scaladslSelf: scaladsl.EntityTypeKey[T] ⇒ +@DoNotInherit abstract class EntityTypeKey[T] { scaladslSelf: scaladsl.EntityTypeKey[T] => /** * Name of the entity type. @@ -399,7 +399,7 @@ object EntityTypeKey { * * Not for user extension. */ -@DoNotInherit abstract class EntityRef[M] extends RecipientRef[M] { scaladslSelf: scaladsl.EntityRef[M] with InternalRecipientRef[M] ⇒ +@DoNotInherit abstract class EntityRef[M] extends RecipientRef[M] { scaladslSelf: scaladsl.EntityRef[M] with InternalRecipientRef[M] => /** * Send a message to the entity referenced by this EntityRef using *at-most-once* diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/scaladsl/ClusterSharding.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/scaladsl/ClusterSharding.scala index c5c657b6c8..fccbd00196 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/scaladsl/ClusterSharding.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/scaladsl/ClusterSharding.scala @@ -23,7 +23,7 @@ import akka.annotation.InternalApi import akka.cluster.sharding.ShardCoordinator.ShardAllocationStrategy import akka.cluster.sharding.typed.internal.ClusterShardingImpl import akka.cluster.sharding.typed.internal.EntityTypeKeyImpl -import akka.cluster.sharding.ShardRegion.{ StartEntity ⇒ UntypedStartEntity } +import akka.cluster.sharding.ShardRegion.{ StartEntity => UntypedStartEntity } import akka.persistence.typed.PersistenceId object ClusterSharding extends ExtensionId[ClusterSharding] { @@ -164,7 +164,7 @@ object ClusterSharding extends ExtensionId[ClusterSharding] { * such implementations. */ @DoNotInherit -trait ClusterSharding extends Extension { javadslSelf: javadsl.ClusterSharding ⇒ +trait ClusterSharding extends Extension { javadslSelf: javadsl.ClusterSharding => /** * Initialize sharding for the given `entity` factory settings. @@ -222,7 +222,7 @@ object Entity { */ def apply[M]( typeKey: EntityTypeKey[M], - createBehavior: EntityContext ⇒ Behavior[M]): Entity[M, ShardingEnvelope[M]] = + createBehavior: EntityContext => Behavior[M]): Entity[M, ShardingEnvelope[M]] = new Entity(createBehavior, typeKey, None, Props.empty, None, None, None) } @@ -230,7 +230,7 @@ object Entity { * Defines how the entity should be created. Used in [[ClusterSharding#init]]. */ final class Entity[M, E] private[akka] ( - val createBehavior: EntityContext ⇒ Behavior[M], + val createBehavior: EntityContext => Behavior[M], val typeKey: EntityTypeKey[M], val stopMessage: Option[M], val entityProps: Props, @@ -278,7 +278,7 @@ final class Entity[M, E] private[akka] ( copy(allocationStrategy = Option(newAllocationStrategy)) private def copy( - createBehavior: EntityContext ⇒ Behavior[M] = createBehavior, + createBehavior: EntityContext => Behavior[M] = createBehavior, typeKey: EntityTypeKey[M] = typeKey, stopMessage: Option[M] = stopMessage, entityProps: Props = entityProps, @@ -364,7 +364,7 @@ object EntityTypeKey { * [[ActorRef]] and watch it in case such notification is desired. * Not for user extension. */ -@DoNotInherit trait EntityRef[M] extends RecipientRef[M] { this: InternalRecipientRef[M] ⇒ +@DoNotInherit trait EntityRef[M] extends RecipientRef[M] { this: InternalRecipientRef[M] => /** * Send a message to the entity referenced by this EntityRef using *at-most-once* @@ -409,7 +409,7 @@ object EntityTypeKey { * * Please note that an implicit [[akka.util.Timeout]] must be available to use this pattern. */ - def ask[U](f: ActorRef[U] ⇒ M)(implicit timeout: Timeout): Future[U] + def ask[U](f: ActorRef[U] => M)(implicit timeout: Timeout): Future[U] /** * Allows to "ask" the [[EntityRef]] for a reply. @@ -430,13 +430,13 @@ object EntityTypeKey { * * Please note that an implicit [[akka.util.Timeout]] must be available to use this pattern. */ - def ?[U](message: ActorRef[U] ⇒ M)(implicit timeout: Timeout): Future[U] = + def ?[U](message: ActorRef[U] => M)(implicit timeout: Timeout): Future[U] = this.ask(message)(timeout) } object ClusterShardingSetup { - def apply[T <: Extension](createExtension: ActorSystem[_] ⇒ ClusterSharding): ClusterShardingSetup = + def apply[T <: Extension](createExtension: ActorSystem[_] => ClusterSharding): ClusterShardingSetup = new ClusterShardingSetup(new java.util.function.Function[ActorSystem[_], ClusterSharding] { override def apply(sys: ActorSystem[_]): ClusterSharding = createExtension(sys) }) // TODO can be simplified when compiled only with Scala >= 2.12 diff --git a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/scaladsl/EventSourcedEntity.scala b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/scaladsl/EventSourcedEntity.scala index 800b758f03..933aa1f57f 100644 --- a/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/scaladsl/EventSourcedEntity.scala +++ b/akka-cluster-sharding-typed/src/main/scala/akka/cluster/sharding/typed/scaladsl/EventSourcedEntity.scala @@ -23,7 +23,7 @@ object EventSourcedEntity { entityTypeKey: EntityTypeKey[Command], entityId: String, emptyState: State, - commandHandler: (State, Command) ⇒ Effect[Event, State], - eventHandler: (State, Event) ⇒ State): EventSourcedBehavior[Command, Event, State] = + commandHandler: (State, Command) => Effect[Event, State], + eventHandler: (State, Event) => State): EventSourcedBehavior[Command, Event, State] = EventSourcedBehavior(entityTypeKey.persistenceIdFrom(entityId), emptyState, commandHandler, eventHandler) } diff --git a/akka-cluster-sharding-typed/src/multi-jvm/scala/akka/cluster/sharding/typed/MultiDcClusterShardingSpec.scala b/akka-cluster-sharding-typed/src/multi-jvm/scala/akka/cluster/sharding/typed/MultiDcClusterShardingSpec.scala index 191c5d8a98..9791c91436 100644 --- a/akka-cluster-sharding-typed/src/multi-jvm/scala/akka/cluster/sharding/typed/MultiDcClusterShardingSpec.scala +++ b/akka-cluster-sharding-typed/src/multi-jvm/scala/akka/cluster/sharding/typed/MultiDcClusterShardingSpec.scala @@ -70,7 +70,7 @@ abstract class MultiDcClusterShardingSpec extends MultiNodeSpec(MultiDcClusterSh "init sharding" in { val sharding = ClusterSharding(typedSystem) val shardRegion: ActorRef[ShardingEnvelope[PingProtocol]] = sharding.init( - Entity(typeKey, _ ⇒ multiDcPinger)) + Entity(typeKey, _ => multiDcPinger)) val probe = TestProbe[Pong] shardRegion ! ShardingEnvelope(entityId, Ping(probe.ref)) probe.expectMessage(max = 10.seconds, Pong(cluster.selfMember.dataCenter)) @@ -99,7 +99,7 @@ abstract class MultiDcClusterShardingSpec extends MultiNodeSpec(MultiDcClusterSh val proxy: ActorRef[ShardingEnvelope[PingProtocol]] = ClusterSharding(typedSystem).init( Entity( typeKey, - _ ⇒ multiDcPinger) + _ => multiDcPinger) .withSettings(ClusterShardingSettings(typedSystem).withDataCenter("dc2"))) val probe = TestProbe[Pong] proxy ! ShardingEnvelope(entityId, Ping(probe.ref)) diff --git a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/JoinConfigCompatCheckerClusterShardingSpec.scala b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/JoinConfigCompatCheckerClusterShardingSpec.scala index 1cb61d173b..40259cd27b 100644 --- a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/JoinConfigCompatCheckerClusterShardingSpec.scala +++ b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/JoinConfigCompatCheckerClusterShardingSpec.scala @@ -5,7 +5,7 @@ package akka.cluster.sharding.typed import scala.concurrent.duration._ -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } import scala.util.Try import akka.actor.ActorSystem @@ -47,13 +47,13 @@ abstract class JoinConfigCompatCheckerClusterShardingSpec extends AkkaSpec( protected def join(sys: ActorSystem): Cluster = { nodes :+= sys sys match { - case seed if seed eq system ⇒ + case seed if seed eq system => configured(system) should ===(JoinConfig.Shards) val seedNode = Cluster(seed) seedNode.join(seedNode.selfAddress) awaitCond(seedNode.readView.isSingletonCluster, duration) seedNode - case joining ⇒ + case joining => val cluster = Cluster(joining) cluster.joinSeedNodes(im.Seq(Cluster(system).readView.selfAddress)) cluster @@ -91,7 +91,7 @@ class JoinConfigCompatibilitySpec extends JoinConfigCompatCheckerClusterSharding val cluster = join(joining) for { - node ← Set(seedNode, cluster) + node <- Set(seedNode, cluster) } awaitCond(node.readView.members.size == joinConfig, duration) } } diff --git a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/ShardingSerializerSpec.scala b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/ShardingSerializerSpec.scala index 3e31eb2ce1..0762232141 100644 --- a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/ShardingSerializerSpec.scala +++ b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/ShardingSerializerSpec.scala @@ -18,11 +18,11 @@ class ShardingSerializerSpec extends ScalaTestWithActorTestKit with WordSpecLike def checkSerialization(obj: AnyRef): Unit = { serialization.findSerializerFor(obj) match { - case serializer: ShardingSerializer ⇒ + case serializer: ShardingSerializer => val blob = serializer.toBinary(obj) val ref = serializer.fromBinary(blob, serializer.manifest(obj)) ref should ===(obj) - case s ⇒ + case s => throw new IllegalStateException(s"Wrong serializer ${s.getClass} for ${obj.getClass}") } } diff --git a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingPersistenceSpec.scala b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingPersistenceSpec.scala index 6212249855..2c014ea961 100644 --- a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingPersistenceSpec.scala +++ b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingPersistenceSpec.scala @@ -25,7 +25,7 @@ import akka.cluster.sharding.ShardRegion.CurrentShardRegionState import akka.cluster.sharding.ShardRegion.GetShardRegionState import akka.cluster.sharding.typed.scaladsl.ClusterSharding.Passivate import akka.cluster.sharding.typed.scaladsl.ClusterSharding.ShardCommand -import akka.cluster.sharding.{ ClusterSharding ⇒ UntypedClusterSharding } +import akka.cluster.sharding.{ ClusterSharding => UntypedClusterSharding } import akka.cluster.typed.Cluster import akka.cluster.typed.Join import akka.persistence.typed.ExpectingReply @@ -68,11 +68,11 @@ object ClusterShardingPersistenceSpec { val entityActorRefs = new ConcurrentHashMap[String, Promise[ActorRef[Any]]] def persistentEntity(entityId: String, shard: ActorRef[ShardCommand]): Behavior[Command] = { - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => entityActorRefs.get(entityId) match { - case null ⇒ - case promise ⇒ promise.trySuccess(ctx.self.unsafeUpcast) + case null => + case promise => promise.trySuccess(ctx.self.unsafeUpcast) } // transient state (testing purpose) @@ -82,61 +82,61 @@ object ClusterShardingPersistenceSpec { entityTypeKey = typeKey, entityId = entityId, emptyState = "", - commandHandler = (state, cmd) ⇒ cmd match { - case Add(s) ⇒ + commandHandler = (state, cmd) => cmd match { + case Add(s) => if (stashing) Effect.stash() else Effect.persist(s) - case cmd @ AddWithConfirmation(s) ⇒ + case cmd @ AddWithConfirmation(s) => if (stashing) Effect.stash() else Effect.persist(s) - .thenReply(cmd)(_ ⇒ Done) + .thenReply(cmd)(_ => Done) - case Get(replyTo) ⇒ + case Get(replyTo) => replyTo ! s"$entityId:$state" Effect.none - case cmd @ PassivateAndPersist(s) ⇒ + case cmd @ PassivateAndPersist(s) => shard ! Passivate(ctx.self) Effect.persist(s) - .thenReply(cmd)(_ ⇒ Done) + .thenReply(cmd)(_ => Done) - case Echo(msg, replyTo) ⇒ - Effect.none.thenRun(_ ⇒ replyTo ! msg) + case Echo(msg, replyTo) => + Effect.none.thenRun(_ => replyTo ! msg) - case Block(latch) ⇒ + case Block(latch) => latch.await(5, TimeUnit.SECONDS) Effect.none - case BeginStashingAddCommands ⇒ + case BeginStashingAddCommands => stashing = true Effect.none - case UnstashAll ⇒ + case UnstashAll => stashing = false Effect.unstashAll() - case UnstashAllAndPassivate ⇒ + case UnstashAllAndPassivate => stashing = false shard ! Passivate(ctx.self) Effect.unstashAll() }, - eventHandler = (state, evt) ⇒ if (state.isEmpty) evt else state + "|" + evt) - .onRecoveryCompleted { state ⇒ + eventHandler = (state, evt) => if (state.isEmpty) evt else state + "|" + evt) + .onRecoveryCompleted { state => ctx.log.debug("onRecoveryCompleted: [{}]", state) lifecycleProbes.get(entityId) match { - case null ⇒ ctx.log.debug("no lifecycleProbe (onRecoveryCompleted) for [{}]", entityId) - case p ⇒ p ! s"recoveryCompleted:$state" + case null => ctx.log.debug("no lifecycleProbe (onRecoveryCompleted) for [{}]", entityId) + case p => p ! s"recoveryCompleted:$state" } } - .onPostStop(() ⇒ + .onPostStop(() => lifecycleProbes.get(entityId) match { - case null ⇒ ctx.log.debug("no lifecycleProbe (postStop) for [{}]", entityId) - case p ⇒ p ! "stopped" + case null => ctx.log.debug("no lifecycleProbe (postStop) for [{}]", entityId) + case p => p ! "stopped" } ) } @@ -164,7 +164,7 @@ class ClusterShardingPersistenceSpec extends ScalaTestWithActorTestKit(ClusterSh val untypedRegion = UntypedClusterSharding(system.toUntyped) regionStateProbe.awaitAssert { untypedRegion.shardRegion(typeKey.name).tell(GetShardRegionState, regionStateProbe.ref.toUntyped) - regionStateProbe.receiveMessage().shards.foreach { shardState ⇒ + regionStateProbe.receiveMessage().shards.foreach { shardState => shardState.entityIds should not contain entityId } } @@ -174,7 +174,7 @@ class ClusterShardingPersistenceSpec extends ScalaTestWithActorTestKit(ClusterSh ClusterSharding(system).init(Entity( typeKey, - ctx ⇒ persistentEntity(ctx.entityId, ctx.shard))) + ctx => persistentEntity(ctx.entityId, ctx.shard))) Cluster(system).manager ! Join(Cluster(system).selfMember.address) @@ -213,7 +213,7 @@ class ClusterShardingPersistenceSpec extends ScalaTestWithActorTestKit(ClusterSh val p1 = TestProbe[Done]() val ref = ClusterSharding(system).entityRefFor(typeKey, entityId) - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => ref ! PassivateAndPersist(n.toString)(p1.ref) lifecycleProbe.expectMessage(max = 10.seconds, "recoveryCompleted:" + (1 until n).map(_.toString).mkString("|")) p1.expectMessage(Done) @@ -381,7 +381,7 @@ class ClusterShardingPersistenceSpec extends ScalaTestWithActorTestKit(ClusterSh // not using actorRefPromise.future.futureValue because it's polling (slow) and want to run this before // recovery completed, to exercise that scenario implicit val ec: ExecutionContext = testKit.system.executionContext - val poisonSent = actorRefPromise.future.map { actorRef ⇒ + val poisonSent = actorRefPromise.future.map { actorRef => // not sending via the EntityRef because that would make the test racy actorRef ! PoisonPill actorRef @@ -417,7 +417,7 @@ class ClusterShardingPersistenceSpec extends ScalaTestWithActorTestKit(ClusterSh // not using actorRefPromise.future.futureValue because it's polling (slow) and want to run this before // recovery completed, to exercise that scenario implicit val ec: ExecutionContext = testKit.system.executionContext - val poisonSent = actorRefPromise.future.map { actorRef ⇒ + val poisonSent = actorRefPromise.future.map { actorRef => // not sending via the EntityRef because that would make the test racy // these are stashed, since before the PoisonPill actorRef ! Echo("echo-2", echoProbe.ref) diff --git a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingSpec.scala b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingSpec.scala index a4a0726eb4..ce595b875f 100644 --- a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingSpec.scala +++ b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingSpec.scala @@ -79,13 +79,13 @@ object ClusterShardingSpec { class Serializer(system: ExtendedActorSystem) extends SerializerWithStringManifest { def identifier: Int = 48 def manifest(o: AnyRef): String = o match { - case _: ReplyPlz ⇒ "a" - case _: WhoAreYou ⇒ "b" - case _: StopPlz ⇒ "c" - case _: PassivatePlz ⇒ "d" - case _: IdReplyPlz ⇒ "A" - case _: IdWhoAreYou ⇒ "B" - case _: IdStopPlz ⇒ "C" + case _: ReplyPlz => "a" + case _: WhoAreYou => "b" + case _: StopPlz => "c" + case _: PassivatePlz => "d" + case _: IdReplyPlz => "A" + case _: IdWhoAreYou => "B" + case _: IdStopPlz => "C" } private def actorRefToBinary(ref: ActorRef[_]): Array[Byte] = @@ -99,13 +99,13 @@ object ClusterShardingSpec { } def toBinary(o: AnyRef): Array[Byte] = o match { - case ReplyPlz(ref) ⇒ actorRefToBinary(ref) - case WhoAreYou(ref) ⇒ actorRefToBinary(ref) - case _: StopPlz ⇒ Array.emptyByteArray - case _: PassivatePlz ⇒ Array.emptyByteArray - case IdReplyPlz(id, ref) ⇒ idAndRefToBinary(id, ref) - case IdWhoAreYou(id, ref) ⇒ idAndRefToBinary(id, ref) - case _: IdStopPlz ⇒ Array.emptyByteArray + case ReplyPlz(ref) => actorRefToBinary(ref) + case WhoAreYou(ref) => actorRefToBinary(ref) + case _: StopPlz => Array.emptyByteArray + case _: PassivatePlz => Array.emptyByteArray + case IdReplyPlz(id, ref) => idAndRefToBinary(id, ref) + case IdWhoAreYou(id, ref) => idAndRefToBinary(id, ref) + case _: IdStopPlz => Array.emptyByteArray } private def actorRefFromBinary[T](bytes: Array[Byte]): ActorRef[T] = @@ -119,13 +119,13 @@ object ClusterShardingSpec { } def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case "a" ⇒ ReplyPlz(actorRefFromBinary(bytes)) - case "b" ⇒ WhoAreYou(actorRefFromBinary(bytes)) - case "c" ⇒ StopPlz() - case "d" ⇒ PassivatePlz() - case "A" ⇒ IdReplyPlz.tupled(idAndRefFromBinary(bytes)) - case "B" ⇒ IdWhoAreYou.tupled(idAndRefFromBinary(bytes)) - case "C" ⇒ IdStopPlz() + case "a" => ReplyPlz(actorRefFromBinary(bytes)) + case "b" => WhoAreYou(actorRefFromBinary(bytes)) + case "c" => StopPlz() + case "d" => PassivatePlz() + case "A" => IdReplyPlz.tupled(idAndRefFromBinary(bytes)) + case "B" => IdWhoAreYou.tupled(idAndRefFromBinary(bytes)) + case "C" => IdStopPlz() } } @@ -136,46 +136,46 @@ object ClusterShardingSpec { def behavior(shard: ActorRef[ClusterSharding.ShardCommand], stopProbe: Option[ActorRef[String]] = None) = Behaviors.receive[TestProtocol] { - case (ctx, PassivatePlz()) ⇒ + case (ctx, PassivatePlz()) => shard ! ClusterSharding.Passivate(ctx.self) Behaviors.same - case (_, StopPlz()) ⇒ + case (_, StopPlz()) => stopProbe.foreach(_ ! "StopPlz") Behaviors.stopped - case (ctx, WhoAreYou(replyTo)) ⇒ + case (ctx, WhoAreYou(replyTo)) => val address = Cluster(ctx.system).selfMember.address replyTo ! s"I'm ${ctx.self.path.name} at ${address.host.get}:${address.port.get}" Behaviors.same - case (_, ReplyPlz(toMe)) ⇒ + case (_, ReplyPlz(toMe)) => toMe ! "Hello!" Behaviors.same }.receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => stopProbe.foreach(_ ! "PostStop") Behaviors.same } def behaviorWithId(shard: ActorRef[ClusterSharding.ShardCommand]) = Behaviors.receive[IdTestProtocol] { - case (_, IdStopPlz()) ⇒ + case (_, IdStopPlz()) => Behaviors.stopped - case (ctx, IdWhoAreYou(_, replyTo)) ⇒ + case (ctx, IdWhoAreYou(_, replyTo)) => val address = Cluster(ctx.system).selfMember.address replyTo ! s"I'm ${ctx.self.path.name} at ${address.host.get}:${address.port.get}" Behaviors.same - case (_, IdReplyPlz(_, toMe)) ⇒ + case (_, IdReplyPlz(_, toMe)) => toMe ! "Hello!" Behaviors.same } val idTestProtocolMessageExtractor = ShardingMessageExtractor.noEnvelope[IdTestProtocol](10, IdStopPlz()) { - case IdReplyPlz(id, _) ⇒ id - case IdWhoAreYou(id, _) ⇒ id - case other ⇒ throw new IllegalArgumentException(s"Unexpected message $other") + case IdReplyPlz(id, _) => id + case IdWhoAreYou(id, _) => id + case other => throw new IllegalArgumentException(s"Unexpected message $other") } } @@ -195,28 +195,28 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. private val shardingRef1: ActorRef[ShardingEnvelope[TestProtocol]] = sharding.init(Entity( typeKey, - ctx ⇒ behavior(ctx.shard)) + ctx => behavior(ctx.shard)) .withStopMessage(StopPlz())) private val shardingRef2 = sharding2.init(Entity( typeKey, - ctx ⇒ behavior(ctx.shard)) + ctx => behavior(ctx.shard)) .withStopMessage(StopPlz())) private val shardingRef3: ActorRef[IdTestProtocol] = sharding.init(Entity( typeKey2, - ctx ⇒ behaviorWithId(ctx.shard)) + ctx => behaviorWithId(ctx.shard)) .withMessageExtractor(ShardingMessageExtractor.noEnvelope[IdTestProtocol](10, IdStopPlz()) { - case IdReplyPlz(id, _) ⇒ id - case IdWhoAreYou(id, _) ⇒ id - case other ⇒ throw new IllegalArgumentException(s"Unexpected message $other") + case IdReplyPlz(id, _) => id + case IdWhoAreYou(id, _) => id + case other => throw new IllegalArgumentException(s"Unexpected message $other") }) .withStopMessage(IdStopPlz()) ) private val shardingRef4 = sharding2.init(Entity( typeKey2, - ctx ⇒ behaviorWithId(ctx.shard)) + ctx => behaviorWithId(ctx.shard)) .withMessageExtractor(idTestProtocolMessageExtractor) .withStopMessage(IdStopPlz()) ) @@ -248,7 +248,7 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. } "send messages via cluster sharding, using envelopes" in { - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => val p = TestProbe[String]() shardingRef1 ! ShardingEnvelope(s"test$n", ReplyPlz(p.ref)) p.expectMessage("Hello!") @@ -256,7 +256,7 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. } "send messages via cluster sharding, without envelopes" in { - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => val p = TestProbe[String]() shardingRef3 ! IdReplyPlz(s"test$n", p.ref) p.expectMessage("Hello!") @@ -270,7 +270,7 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. val shardingRef3: ActorRef[ShardingEnvelope[TestProtocol]] = sharding.init(Entity( typeKey3, - ctx ⇒ behavior(ctx.shard, Some(stopProbe.ref))) + ctx => behavior(ctx.shard, Some(stopProbe.ref))) .withStopMessage(StopPlz())) shardingRef3 ! ShardingEnvelope(s"test1", ReplyPlz(p.ref)) @@ -291,7 +291,7 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. val shardingRef4: ActorRef[ShardingEnvelope[TestProtocol]] = sharding.init(Entity( typeKey4, - ctx ⇒ behavior(ctx.shard, Some(stopProbe.ref)))) + ctx => behavior(ctx.shard, Some(stopProbe.ref)))) // no StopPlz stopMessage shardingRef4 ! ShardingEnvelope(s"test4", ReplyPlz(p.ref)) @@ -310,7 +310,7 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. val ex = intercept[Exception] { sharding.init(Entity( EntityTypeKey[IdTestProtocol]("envelope-shard"), - ctx ⇒ behaviorWithId(ctx.shard)) + ctx => behaviorWithId(ctx.shard)) .withStopMessage(IdStopPlz())) } @@ -350,17 +350,17 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. val p = TestProbe[TheReply]() spawn( - Behaviors.setup[TheReply] { ctx ⇒ + Behaviors.setup[TheReply] { ctx => // FIXME is the implicit ClassTag difficult to use? // it works fine when there is a single parameter apply, // but trouble when more parameters and this doesn't compile //ctx.ask(aliceRef)(x => WhoAreYou(x)) { ctx.ask(aliceRef)(WhoAreYou) { - case Success(name) ⇒ TheReply(name) - case Failure(ex) ⇒ TheReply(ex.getMessage) + case Success(name) => TheReply(name) + case Failure(ex) => TheReply(ex.getMessage) } - Behaviors.receiveMessage[TheReply] { reply ⇒ + Behaviors.receiveMessage[TheReply] { reply => p.ref ! reply Behaviors.same } @@ -376,7 +376,7 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. sharding.init(Entity( ignorantKey, - _ ⇒ Behaviors.ignore[TestProtocol]) + _ => Behaviors.ignore[TestProtocol]) .withStopMessage(StopPlz())) val ref = sharding.entityRefFor(ignorantKey, "sloppy") @@ -423,7 +423,7 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. // use many entites to reduce the risk that all are hashed to the same shard/node val numberOfEntities = 100 val probe1 = TestProbe[String]() - (1 to numberOfEntities).foreach { n ⇒ + (1 to numberOfEntities).foreach { n => shardingRef1 ! ShardingEnvelope(s"test$n", WhoAreYou(probe1.ref)) } val replies1 = probe1.receiveMessages(numberOfEntities, 10.seconds) @@ -436,7 +436,7 @@ class ClusterShardingSpec extends ScalaTestWithActorTestKit(ClusterShardingSpec. } val probe2 = TestProbe[String]() - (1 to numberOfEntities).foreach { n ⇒ + (1 to numberOfEntities).foreach { n => shardingRef1 ! ShardingEnvelope(s"test$n", WhoAreYou(probe2.ref)) } val replies2 = probe2.receiveMessages(numberOfEntities, 10.seconds) diff --git a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingStateSpec.scala b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingStateSpec.scala index b0b06a4bf2..43dab1cc02 100644 --- a/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingStateSpec.scala +++ b/akka-cluster-sharding-typed/src/test/scala/akka/cluster/sharding/typed/scaladsl/ClusterShardingStateSpec.scala @@ -17,9 +17,9 @@ class ClusterShardingStateSpec extends ScalaTestWithActorTestKit(ClusterSharding val sharding = ClusterSharding(system) val shardExtractor = ShardingMessageExtractor.noEnvelope[IdTestProtocol](10, IdStopPlz()) { - case IdReplyPlz(id, _) ⇒ id - case IdWhoAreYou(id, _) ⇒ id - case other ⇒ throw new IllegalArgumentException(s"Unexpected message $other") + case IdReplyPlz(id, _) => id + case IdWhoAreYou(id, _) => id + case other => throw new IllegalArgumentException(s"Unexpected message $other") } val cluster = Cluster(system) @@ -38,7 +38,7 @@ class ClusterShardingStateSpec extends ScalaTestWithActorTestKit(ClusterSharding val shardingRef: ActorRef[IdTestProtocol] = sharding.init( Entity( typeKey, - ctx ⇒ ClusterShardingSpec.behaviorWithId(ctx.shard)) + ctx => ClusterShardingSpec.behaviorWithId(ctx.shard)) .withStopMessage(IdStopPlz()) .withMessageExtractor(idTestProtocolMessageExtractor) ) diff --git a/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/HelloWorldEventSourcedEntityExampleSpec.scala b/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/HelloWorldEventSourcedEntityExampleSpec.scala index 819b2b8f4a..660f970d1e 100644 --- a/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/HelloWorldEventSourcedEntityExampleSpec.scala +++ b/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/HelloWorldEventSourcedEntityExampleSpec.scala @@ -37,7 +37,7 @@ class HelloWorldEventSourcedEntityExampleSpec extends ScalaTestWithActorTestKit( sharding.init(Entity( HelloWorld.entityTypeKey, - ctx ⇒ HelloWorld.persistentEntity(ctx.entityId))) + ctx => HelloWorld.persistentEntity(ctx.entityId))) } "HelloWorld example" must { diff --git a/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/HelloWorldPersistentEntityExample.scala b/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/HelloWorldPersistentEntityExample.scala index 5669c1cf3a..664e596e98 100644 --- a/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/HelloWorldPersistentEntityExample.scala +++ b/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/HelloWorldPersistentEntityExample.scala @@ -25,7 +25,7 @@ object HelloWorldPersistentEntityExample { sharding.init(Entity( typeKey = HelloWorld.entityTypeKey, - createBehavior = entityContext ⇒ HelloWorld.persistentEntity(entityContext.entityId))) + createBehavior = entityContext => HelloWorld.persistentEntity(entityContext.entityId))) private implicit val askTimeout: Timeout = Timeout(5.seconds) @@ -62,19 +62,19 @@ object HelloWorldPersistentEntityExample { def numberOfPeople: Int = names.size } - private val commandHandler: (KnownPeople, Command) ⇒ Effect[Greeted, KnownPeople] = { - (_, cmd) ⇒ + private val commandHandler: (KnownPeople, Command) => Effect[Greeted, KnownPeople] = { + (_, cmd) => cmd match { - case cmd: Greet ⇒ greet(cmd) + case cmd: Greet => greet(cmd) } } private def greet(cmd: Greet): Effect[Greeted, KnownPeople] = Effect.persist(Greeted(cmd.whom)) - .thenRun(state ⇒ cmd.replyTo ! Greeting(cmd.whom, state.numberOfPeople)) + .thenRun(state => cmd.replyTo ! Greeting(cmd.whom, state.numberOfPeople)) - private val eventHandler: (KnownPeople, Greeted) ⇒ KnownPeople = { - (state, evt) ⇒ state.add(evt.whom) + private val eventHandler: (KnownPeople, Greeted) => KnownPeople = { + (state, evt) => state.add(evt.whom) } val entityTypeKey: EntityTypeKey[Command] = diff --git a/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/ShardingCompileOnlySpec.scala b/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/ShardingCompileOnlySpec.scala index 651025d72a..f0e4c8e02c 100644 --- a/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/ShardingCompileOnlySpec.scala +++ b/akka-cluster-sharding-typed/src/test/scala/docs/akka/cluster/sharding/typed/ShardingCompileOnlySpec.scala @@ -35,9 +35,9 @@ object ShardingCompileOnlySpec { def counter(entityId: String, value: Int): Behavior[CounterCommand] = Behaviors.receiveMessage[CounterCommand] { - case Increment ⇒ + case Increment => counter(entityId, value + 1) - case GetValue(replyTo) ⇒ + case GetValue(replyTo) => replyTo ! value Behaviors.same } @@ -48,7 +48,7 @@ object ShardingCompileOnlySpec { val shardRegion: ActorRef[ShardingEnvelope[CounterCommand]] = sharding.init(Entity( typeKey = TypeKey, - createBehavior = ctx ⇒ counter(ctx.entityId, 0))) + createBehavior = ctx => counter(ctx.entityId, 0))) //#init //#send @@ -66,7 +66,7 @@ object ShardingCompileOnlySpec { ClusterSharding(system).init(Entity( typeKey = BlogTypeKey, - createBehavior = ctx ⇒ behavior(ctx.entityId))) + createBehavior = ctx => behavior(ctx.entityId))) //#persistence //#counter-passivate @@ -75,20 +75,20 @@ object ShardingCompileOnlySpec { case object GoodByeCounter extends CounterCommand def counter2(shard: ActorRef[ClusterSharding.ShardCommand], entityId: String): Behavior[CounterCommand] = { - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => def become(value: Int): Behavior[CounterCommand] = Behaviors.receiveMessage[CounterCommand] { - case Increment ⇒ + case Increment => become(value + 1) - case GetValue(replyTo) ⇒ + case GetValue(replyTo) => replyTo ! value Behaviors.same - case Idle ⇒ + case Idle => // after receive timeout shard ! ClusterSharding.Passivate(ctx.self) Behaviors.same - case GoodByeCounter ⇒ + case GoodByeCounter => // the stopMessage, used for rebalance and passivate Behaviors.stopped } @@ -100,7 +100,7 @@ object ShardingCompileOnlySpec { sharding.init(Entity( typeKey = TypeKey, - createBehavior = ctx ⇒ counter2(ctx.shard, ctx.entityId)) + createBehavior = ctx => counter2(ctx.shard, ctx.entityId)) .withStopMessage(GoodByeCounter)) //#counter-passivate diff --git a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ClusterSharding.scala b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ClusterSharding.scala index 94e18f5c8a..d047a784ce 100755 --- a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ClusterSharding.scala +++ b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ClusterSharding.scala @@ -173,8 +173,8 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { system.settings.config.getString("akka.cluster.sharding.guardian-name") val dispatcher = system.settings.config .getString("akka.cluster.sharding.use-dispatcher") match { - case "" ⇒ Dispatchers.DefaultDispatcherId - case id ⇒ id + case "" => Dispatchers.DefaultDispatcherId + case id => id } system.systemActorOf(Props[ClusterShardingGuardian].withDispatcher(dispatcher), guardianName) } @@ -213,7 +213,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { allocationStrategy: ShardAllocationStrategy, handOffStopMessage: Any): ActorRef = { - internalStart(typeName, _ ⇒ entityProps, settings, extractEntityId, extractShardId, allocationStrategy, handOffStopMessage) + internalStart(typeName, _ => entityProps, settings, extractEntityId, extractShardId, allocationStrategy, handOffStopMessage) } /** @@ -256,7 +256,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { */ @InternalApi private[akka] def internalStart( typeName: String, - entityProps: String ⇒ Props, + entityProps: String => Props, settings: ClusterShardingSettings, extractEntityId: ShardRegion.ExtractEntityId, extractShardId: ShardRegion.ExtractShardId, @@ -265,7 +265,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { if (settings.shouldHostShard(cluster)) { regions.get(typeName) match { - case null ⇒ + case null => // it's ok to Start several time, the guardian will deduplicate concurrent requests implicit val timeout = system.settings.CreationTimeout val startMsg = Start(typeName, entityProps, settings, @@ -273,7 +273,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { val Started(shardRegion) = Await.result(guardian ? startMsg, timeout.duration) regions.put(typeName, shardRegion) shardRegion - case ref ⇒ ref // already started, use cached ActorRef + case ref => ref // already started, use cached ActorRef } } else { log.debug("Starting Shard Region Proxy [{}] (no actors will be hosted on this node)...", typeName) @@ -387,13 +387,13 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { internalStart( typeName, - _ ⇒ entityProps, + _ => entityProps, settings, extractEntityId = { - case msg if messageExtractor.entityId(msg) ne null ⇒ + case msg if messageExtractor.entityId(msg) ne null => (messageExtractor.entityId(msg), messageExtractor.entityMessage(msg)) }, - extractShardId = msg ⇒ messageExtractor.shardId(msg), + extractShardId = msg => messageExtractor.shardId(msg), allocationStrategy = allocationStrategy, handOffStopMessage = handOffStopMessage ) @@ -513,7 +513,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { extractShardId: ShardRegion.ExtractShardId): ActorRef = { proxies.get(proxyName(typeName, dataCenter)) match { - case null ⇒ + case null => // it's ok to StartProxy several time, the guardian will deduplicate concurrent requests implicit val timeout = system.settings.CreationTimeout val settings = ClusterShardingSettings(system).withRole(role) @@ -522,14 +522,14 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { // it must be possible to start several proxies, one per data center proxies.put(proxyName(typeName, dataCenter), shardRegion) shardRegion - case ref ⇒ ref // already started, use cached ActorRef + case ref => ref // already started, use cached ActorRef } } private def proxyName(typeName: String, dataCenter: Option[DataCenter]): String = { dataCenter match { - case None ⇒ s"${typeName}Proxy" - case Some(t) ⇒ s"${typeName}Proxy" + "-" + t + case None => s"${typeName}Proxy" + case Some(t) => s"${typeName}Proxy" + "-" + t } } @@ -584,10 +584,10 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { Option(role.orElse(null)), Option(dataCenter.orElse(null)), extractEntityId = { - case msg if messageExtractor.entityId(msg) ne null ⇒ + case msg if messageExtractor.entityId(msg) ne null => (messageExtractor.entityId(msg), messageExtractor.entityMessage(msg)) }, - extractShardId = msg ⇒ messageExtractor.shardId(msg) + extractShardId = msg => messageExtractor.shardId(msg) ) } @@ -609,14 +609,14 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { */ def shardRegion(typeName: String): ActorRef = { regions.get(typeName) match { - case null ⇒ + case null => proxies.get(proxyName(typeName, None)) match { - case null ⇒ + case null => throw new IllegalArgumentException( s"Shard type [$typeName] must be started first") - case ref ⇒ ref + case ref => ref } - case ref ⇒ ref + case ref => ref } } @@ -629,10 +629,10 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { */ def shardRegionProxy(typeName: String, dataCenter: DataCenter): ActorRef = { proxies.get(proxyName(typeName, Some(dataCenter))) match { - case null ⇒ + case null => throw new IllegalArgumentException( s"Shard type [$typeName] must be started first") - case ref ⇒ ref + case ref => ref } } @@ -654,7 +654,7 @@ private[akka] object ClusterShardingGuardian { import ShardCoordinator.ShardAllocationStrategy final case class Start( typeName: String, - entityProps: String ⇒ Props, + entityProps: String => Props, settings: ClusterShardingSettings, extractEntityId: ShardRegion.ExtractEntityId, extractShardId: ShardRegion.ExtractShardId, @@ -698,11 +698,11 @@ private[akka] class ClusterShardingGuardian extends Actor { if (settings.stateStoreMode == ClusterShardingSettings.StateStoreModeDData) { // one Replicator per role replicatorByRole.get(settings.role) match { - case Some(ref) ⇒ ref - case None ⇒ + case Some(ref) => ref + case None => val name = settings.role match { - case Some(r) ⇒ URLEncoder.encode(r, ByteString.UTF_8) + "Replicator" - case None ⇒ "replicator" + case Some(r) => URLEncoder.encode(r, ByteString.UTF_8) + "Replicator" + case None => "replicator" } // Use members within the data center and with the given role (if any) val replicatorRoles = Set( @@ -724,7 +724,7 @@ private[akka] class ClusterShardingGuardian extends Actor { extractEntityId, extractShardId, allocationStrategy, - handOffStopMessage) ⇒ + handOffStopMessage) => try { import settings.role import settings.tuningParameters.coordinatorFailureBackoff @@ -775,7 +775,7 @@ private[akka] class ClusterShardingGuardian extends Actor { } sender() ! Started(shardRegion) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // don't restart // could be invalid ReplicatorSettings, or InvalidActorNameException // if it has already been started @@ -786,14 +786,14 @@ private[akka] class ClusterShardingGuardian extends Actor { dataCenter, settings, extractEntityId, - extractShardId) ⇒ + extractShardId) => try { val encName = URLEncoder.encode(s"${typeName}Proxy", ByteString.UTF_8) val cPath = coordinatorPath(URLEncoder.encode(typeName, ByteString.UTF_8)) // it must be possible to start several proxies, one per data center val actorName = dataCenter match { - case None ⇒ encName - case Some(t) ⇒ URLEncoder.encode(typeName + "-" + t, ByteString.UTF_8) + case None => encName + case Some(t) => URLEncoder.encode(typeName + "-" + t, ByteString.UTF_8) } val shardRegion = context.child(actorName).getOrElse { context.actorOf( @@ -813,7 +813,7 @@ private[akka] class ClusterShardingGuardian extends Actor { } sender() ! Started(shardRegion) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // don't restart // could be InvalidActorNameException if it has already been started sender() ! Status.Failure(e) diff --git a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/JoinConfigCompatCheckSharding.scala b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/JoinConfigCompatCheckSharding.scala index ca311f324d..c6fdb829dd 100644 --- a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/JoinConfigCompatCheckSharding.scala +++ b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/JoinConfigCompatCheckSharding.scala @@ -7,7 +7,7 @@ package akka.cluster.sharding import akka.annotation.InternalApi import akka.cluster.{ ConfigValidation, JoinConfigCompatChecker } import com.typesafe.config.Config -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } /** * INTERNAL API diff --git a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/RemoveInternalClusterShardingData.scala b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/RemoveInternalClusterShardingData.scala index d6920d6b85..e7c9628dd4 100644 --- a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/RemoveInternalClusterShardingData.scala +++ b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/RemoveInternalClusterShardingData.scala @@ -70,7 +70,7 @@ object RemoveInternalClusterShardingData { else { val journalPluginId = system.settings.config.getString("akka.cluster.sharding.journal-plugin-id") import system.dispatcher - remove(system, journalPluginId, typeNames, terminateSystem = true, remove2dot3Data).onComplete { _ ⇒ + remove(system, journalPluginId, typeNames, terminateSystem = true, remove2dot3Data).onComplete { _ => system.terminate() } } @@ -131,12 +131,12 @@ object RemoveInternalClusterShardingData { var hasSnapshots = false override def receiveRecover: Receive = { - case event: ShardCoordinator.Internal.DomainEvent ⇒ + case event: ShardCoordinator.Internal.DomainEvent => - case SnapshotOffer(_, _) ⇒ + case SnapshotOffer(_, _) => hasSnapshots = true - case RecoveryCompleted ⇒ + case RecoveryCompleted => deleteMessages(Long.MaxValue) if (hasSnapshots) deleteSnapshots(SnapshotSelectionCriteria()) @@ -145,23 +145,23 @@ object RemoveInternalClusterShardingData { } override def receiveCommand: Receive = ({ - case DeleteSnapshotsSuccess(_) ⇒ + case DeleteSnapshotsSuccess(_) => context.become(waitDeleteMessagesSuccess) - case DeleteMessagesSuccess(_) ⇒ + case DeleteMessagesSuccess(_) => context.become(waitDeleteSnapshotsSuccess) }: Receive).orElse(handleFailure) def waitDeleteSnapshotsSuccess: Receive = ({ - case DeleteSnapshotsSuccess(_) ⇒ done() + case DeleteSnapshotsSuccess(_) => done() }: Receive).orElse(handleFailure) def waitDeleteMessagesSuccess: Receive = ({ - case DeleteMessagesSuccess(_) ⇒ done() + case DeleteMessagesSuccess(_) => done() }: Receive).orElse(handleFailure) def handleFailure: Receive = { - case DeleteMessagesFailure(cause, _) ⇒ failure(cause) - case DeleteSnapshotsFailure(_, cause) ⇒ failure(cause) + case DeleteMessagesFailure(cause, _) => failure(cause) + case DeleteSnapshotsFailure(_, cause) => failure(cause) } def done(): Unit = { @@ -209,16 +209,16 @@ class RemoveInternalClusterShardingData(journalPluginId: String, typeNames: Set[ } def receive = { - case Result(Success(_)) ⇒ + case Result(Success(_)) => log.info("Removed data for persistenceId [{}]", currentPid) if (remainingPids.isEmpty) done() else removeNext() - case Result(Failure(cause)) ⇒ + case Result(Failure(cause)) => log.error("Failed to remove data for persistenceId [{}]", currentPid) failure(cause) - case Terminated(ref) ⇒ + case Terminated(ref) => if (ref == currentRef) { val msg = s"Failed to remove data for persistenceId [$currentPid], unexpected termination" log.error(msg) diff --git a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/Shard.scala b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/Shard.scala index b9ef25fcb7..3cb4ffb256 100644 --- a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/Shard.scala +++ b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/Shard.scala @@ -98,7 +98,7 @@ private[akka] object Shard { def props( typeName: String, shardId: ShardRegion.ShardId, - entityProps: String ⇒ Props, + entityProps: String => Props, settings: ClusterShardingSettings, extractEntityId: ShardRegion.ExtractEntityId, extractShardId: ShardRegion.ExtractShardId, @@ -131,7 +131,7 @@ private[akka] object Shard { private[akka] class Shard( typeName: String, shardId: ShardRegion.ShardId, - entityProps: String ⇒ Props, + entityProps: String => Props, settings: ClusterShardingSettings, extractEntityId: ShardRegion.ExtractEntityId, extractShardId: ShardRegion.ExtractShardId, @@ -165,26 +165,26 @@ private[akka] class Shard( def initialized(): Unit = context.parent ! ShardInitialized(shardId) - def processChange[E <: StateChange](event: E)(handler: E ⇒ Unit): Unit = + def processChange[E <: StateChange](event: E)(handler: E => Unit): Unit = handler(event) def receive = receiveCommand def receiveCommand: Receive = { - case Terminated(ref) ⇒ receiveTerminated(ref) - case msg: CoordinatorMessage ⇒ receiveCoordinatorMessage(msg) - case msg: ShardCommand ⇒ receiveShardCommand(msg) - case msg: ShardRegion.StartEntity ⇒ receiveStartEntity(msg) - case msg: ShardRegion.StartEntityAck ⇒ receiveStartEntityAck(msg) - case msg: ShardRegionCommand ⇒ receiveShardRegionCommand(msg) - case msg: ShardQuery ⇒ receiveShardQuery(msg) - case PassivateIdleTick ⇒ passivateIdleEntities() - case msg if extractEntityId.isDefinedAt(msg) ⇒ deliverMessage(msg, sender()) + case Terminated(ref) => receiveTerminated(ref) + case msg: CoordinatorMessage => receiveCoordinatorMessage(msg) + case msg: ShardCommand => receiveShardCommand(msg) + case msg: ShardRegion.StartEntity => receiveStartEntity(msg) + case msg: ShardRegion.StartEntityAck => receiveStartEntityAck(msg) + case msg: ShardRegionCommand => receiveShardRegionCommand(msg) + case msg: ShardQuery => receiveShardQuery(msg) + case PassivateIdleTick => passivateIdleEntities() + case msg if extractEntityId.isDefinedAt(msg) => deliverMessage(msg, sender()) } def receiveShardCommand(msg: ShardCommand): Unit = msg match { - case RestartEntity(id) ⇒ getOrCreateEntity(id) - case RestartEntities(ids) ⇒ restartEntities(ids) + case RestartEntity(id) => getOrCreateEntity(id) + case RestartEntities(ids) => restartEntities(ids) } def receiveStartEntity(start: ShardRegion.StartEntity): Unit = { @@ -193,13 +193,13 @@ private[akka] class Shard( if (passivateIdleTask.isDefined) { lastMessageTimestamp = lastMessageTimestamp.updated(start.entityId, System.nanoTime()) } - getOrCreateEntity(start.entityId, _ ⇒ processChange(EntityStarted(start.entityId))(_ ⇒ requester ! ShardRegion.StartEntityAck(start.entityId, shardId))) + getOrCreateEntity(start.entityId, _ => processChange(EntityStarted(start.entityId))(_ => requester ! ShardRegion.StartEntityAck(start.entityId, shardId))) } def receiveStartEntityAck(ack: ShardRegion.StartEntityAck): Unit = { if (ack.shardId != shardId && state.entities.contains(ack.entityId)) { log.debug("Entity [{}] previously owned by shard [{}] started in shard [{}]", ack.entityId, shardId, ack.shardId) - processChange(EntityStopped(ack.entityId)) { _ ⇒ + processChange(EntityStopped(ack.entityId)) { _ => state = state.copy(state.entities - ack.entityId) messageBuffers.remove(ack.entityId) } @@ -211,24 +211,24 @@ private[akka] class Shard( } def receiveShardRegionCommand(msg: ShardRegionCommand): Unit = msg match { - case Passivate(stopMessage) ⇒ passivate(sender(), stopMessage) - case _ ⇒ unhandled(msg) + case Passivate(stopMessage) => passivate(sender(), stopMessage) + case _ => unhandled(msg) } def receiveCoordinatorMessage(msg: CoordinatorMessage): Unit = msg match { - case HandOff(`shardId`) ⇒ handOff(sender()) - case HandOff(shard) ⇒ log.warning("Shard [{}] can not hand off for another Shard [{}]", shardId, shard) - case _ ⇒ unhandled(msg) + case HandOff(`shardId`) => handOff(sender()) + case HandOff(shard) => log.warning("Shard [{}] can not hand off for another Shard [{}]", shardId, shard) + case _ => unhandled(msg) } def receiveShardQuery(msg: ShardQuery): Unit = msg match { - case GetCurrentShardState ⇒ sender() ! CurrentShardState(shardId, refById.keySet) - case GetShardStats ⇒ sender() ! ShardStats(shardId, state.entities.size) + case GetCurrentShardState => sender() ! CurrentShardState(shardId, refById.keySet) + case GetShardStats => sender() ! ShardStats(shardId, state.entities.size) } def handOff(replyTo: ActorRef): Unit = handOffStopper match { - case Some(_) ⇒ log.warning("HandOff shard [{}] received during existing handOff", shardId) - case None ⇒ + case Some(_) => log.warning("HandOff shard [{}] received during existing handOff", shardId) + case None => log.debug("HandOff shard [{}]", shardId) if (state.entities.nonEmpty) { @@ -238,7 +238,7 @@ private[akka] class Shard( //During hand off we only care about watching for termination of the hand off stopper context become { - case Terminated(ref) ⇒ receiveTerminated(ref) + case Terminated(ref) => receiveTerminated(ref) } } else { replyTo ! ShardStopped(shardId) @@ -272,21 +272,21 @@ private[akka] class Shard( def passivate(entity: ActorRef, stopMessage: Any): Unit = { idByRef.get(entity) match { - case Some(id) ⇒ if (!messageBuffers.contains(id)) { + case Some(id) => if (!messageBuffers.contains(id)) { passivating = passivating + entity messageBuffers.add(id) entity ! stopMessage } else { log.debug("Passivation already in progress for {}. Not sending stopMessage back to entity.", entity) } - case None ⇒ log.debug("Unknown entity {}. Not sending stopMessage back to entity.", entity) + case None => log.debug("Unknown entity {}. Not sending stopMessage back to entity.", entity) } } def passivateIdleEntities(): Unit = { val deadline = System.nanoTime() - settings.passivateIdleEntityAfter.toNanos val refsToPassivate = lastMessageTimestamp.collect { - case (entityId, lastMessageTimestamp) if lastMessageTimestamp < deadline ⇒ refById(entityId) + case (entityId, lastMessageTimestamp) if lastMessageTimestamp < deadline => refById(entityId) } if (refsToPassivate.nonEmpty) { log.debug("Passivating [{}] idle entities", refsToPassivate.size) @@ -313,7 +313,7 @@ private[akka] class Shard( //Now there is no deliveryBuffer we can try to redeliver // and as the child exists, the message will be directly forwarded messages.foreach { - case (msg, snd) ⇒ deliverMessage(msg, snd) + case (msg, snd) => deliverMessage(msg, snd) } } } @@ -325,18 +325,18 @@ private[akka] class Shard( context.system.deadLetters ! msg } else { payload match { - case start: ShardRegion.StartEntity ⇒ + case start: ShardRegion.StartEntity => // in case it was wrapped, used in Typed receiveStartEntity(start) - case _ ⇒ + case _ => messageBuffers.contains(id) match { - case false ⇒ deliverTo(id, msg, payload, snd) + case false => deliverTo(id, msg, payload, snd) - case true if messageBuffers.totalSize >= bufferSize ⇒ + case true if messageBuffers.totalSize >= bufferSize => log.debug("Buffer is full, dropping message for entity [{}]", id) context.system.deadLetters ! msg - case true ⇒ + case true => log.debug("Message for entity [{}] buffered", id) messageBuffers.append(id, msg, snd) } @@ -351,11 +351,11 @@ private[akka] class Shard( getOrCreateEntity(id).tell(payload, snd) } - def getOrCreateEntity(id: EntityId, onCreate: ActorRef ⇒ Unit = ConstantFun.scalaAnyToUnit): ActorRef = { + def getOrCreateEntity(id: EntityId, onCreate: ActorRef => Unit = ConstantFun.scalaAnyToUnit): ActorRef = { val name = URLEncoder.encode(id, "utf-8") context.child(name) match { - case Some(child) ⇒ child - case None ⇒ + case Some(child) => child + case None => log.debug("Starting entity [{}] in shard [{}]", id, shardId) val a = context.watch(context.actorOf(entityProps(id), name)) idByRef = idByRef.updated(a, id) @@ -413,17 +413,17 @@ private[akka] class RememberEntityStarter( def sendStart(ids: Set[ShardRegion.EntityId]): Unit = { // these go through the region rather the directly to the shard // so that shard mapping changes are picked up - ids.foreach(id ⇒ region ! ShardRegion.StartEntity(id)) + ids.foreach(id => region ! ShardRegion.StartEntity(id)) } override def receive: Receive = { - case ack: ShardRegion.StartEntityAck ⇒ + case ack: ShardRegion.StartEntityAck => waitingForAck -= ack.entityId // inform whoever requested the start that it happened requestor ! ack if (waitingForAck.isEmpty) context.stop(self) - case Tick ⇒ + case Tick => sendStart(waitingForAck) } @@ -437,7 +437,7 @@ private[akka] class RememberEntityStarter( * INTERNAL API: Common things for PersistentShard and DDataShard */ private[akka] trait RememberingShard { - selfType: Shard ⇒ + selfType: Shard => import ShardRegion.{ EntityId, Msg } import Shard._ @@ -448,8 +448,8 @@ private[akka] trait RememberingShard { protected val rememberedEntitiesRecoveryStrategy: EntityRecoveryStrategy = { import settings.tuningParameters._ entityRecoveryStrategy match { - case "all" ⇒ EntityRecoveryStrategy.allStrategy() - case "constant" ⇒ EntityRecoveryStrategy.constantStrategy( + case "all" => EntityRecoveryStrategy.allStrategy() + case "constant" => EntityRecoveryStrategy.constantStrategy( context.system, entityRecoveryConstantRateStrategyFrequency, entityRecoveryConstantRateStrategyNumberOfEntities) @@ -457,7 +457,7 @@ private[akka] trait RememberingShard { } protected def restartRememberedEntities(): Unit = { - rememberedEntitiesRecoveryStrategy.recoverEntities(state.entities).foreach { scheduledRecovery ⇒ + rememberedEntitiesRecoveryStrategy.recoverEntities(state.entities).foreach { scheduledRecovery => import context.dispatcher scheduledRecovery.filter(_.nonEmpty).map(RestartEntities).pipeTo(self) } @@ -490,9 +490,9 @@ private[akka] trait RememberingShard { override def deliverTo(id: EntityId, msg: Any, payload: Msg, snd: ActorRef): Unit = { val name = URLEncoder.encode(id, "utf-8") context.child(name) match { - case Some(actor) ⇒ + case Some(actor) => actor.tell(payload, snd) - case None ⇒ + case None => if (state.entities.contains(id)) { require(!messageBuffers.contains(id), s"Message buffers contains id [$id].") getOrCreateEntity(id).tell(payload, snd) @@ -517,7 +517,7 @@ private[akka] trait RememberingShard { private[akka] class PersistentShard( typeName: String, shardId: ShardRegion.ShardId, - entityProps: String ⇒ Props, + entityProps: String => Props, override val settings: ClusterShardingSettings, extractEntityId: ShardRegion.ExtractEntityId, extractShardId: ShardRegion.ExtractShardId, @@ -539,7 +539,7 @@ private[akka] class PersistentShard( override def receive = receiveCommand - override def processChange[E <: StateChange](event: E)(handler: E ⇒ Unit): Unit = { + override def processChange[E <: StateChange](event: E)(handler: E => Unit): Unit = { saveSnapshotWhenNeeded() persist(event)(handler) } @@ -552,24 +552,24 @@ private[akka] class PersistentShard( } override def receiveRecover: Receive = { - case EntityStarted(id) ⇒ state = state.copy(state.entities + id) - case EntityStopped(id) ⇒ state = state.copy(state.entities - id) - case SnapshotOffer(_, snapshot: State) ⇒ state = snapshot - case RecoveryCompleted ⇒ + case EntityStarted(id) => state = state.copy(state.entities + id) + case EntityStopped(id) => state = state.copy(state.entities - id) + case SnapshotOffer(_, snapshot: State) => state = snapshot + case RecoveryCompleted => restartRememberedEntities() super.initialized() log.debug("PersistentShard recovery completed shard [{}] with [{}] entities", shardId, state.entities.size) } override def receiveCommand: Receive = ({ - case e: SaveSnapshotSuccess ⇒ + case e: SaveSnapshotSuccess => log.debug("PersistentShard snapshot saved successfully") internalDeleteMessagesBeforeSnapshot(e, keepNrOfBatches, snapshotAfter) - case SaveSnapshotFailure(_, reason) ⇒ + case SaveSnapshotFailure(_, reason) => log.warning("PersistentShard snapshot failure: [{}]", reason.getMessage) - case DeleteMessagesSuccess(toSequenceNr) ⇒ + case DeleteMessagesSuccess(toSequenceNr) => val deleteTo = toSequenceNr - 1 val deleteFrom = math.max(0, deleteTo - (keepNrOfBatches * snapshotAfter)) log.debug("PersistentShard messages to [{}] deleted successfully. Deleting snapshots from [{}] to [{}]", toSequenceNr, deleteFrom, deleteTo) @@ -578,13 +578,13 @@ private[akka] class PersistentShard( maxSequenceNr = deleteTo )) - case DeleteMessagesFailure(reason, toSequenceNr) ⇒ + case DeleteMessagesFailure(reason, toSequenceNr) => log.warning("PersistentShard messages to [{}] deletion failure: [{}]", toSequenceNr, reason.getMessage) - case DeleteSnapshotsSuccess(m) ⇒ + case DeleteSnapshotsSuccess(m) => log.debug("PersistentShard snapshots matching [{}] deleted successfully", m) - case DeleteSnapshotsFailure(m, reason) ⇒ + case DeleteSnapshotsFailure(m, reason) => log.warning("PersistentShard snapshots matching [{}] deletion failure: [{}]", m, reason.getMessage) }: Receive).orElse(super.receiveCommand) @@ -603,7 +603,7 @@ private[akka] class PersistentShard( private[akka] class DDataShard( typeName: String, shardId: ShardRegion.ShardId, - entityProps: String ⇒ Props, + entityProps: String => Props, override val settings: ClusterShardingSettings, extractEntityId: ShardRegion.ExtractEntityId, extractShardId: ShardRegion.ExtractShardId, @@ -633,7 +633,7 @@ private[akka] class DDataShard( // configuration on each node. private val numberOfKeys = 5 private val stateKeys: Array[ORSetKey[EntityId]] = - Array.tabulate(numberOfKeys)(i ⇒ ORSetKey[EntityId](s"shard-${typeName}-${shardId}-$i")) + Array.tabulate(numberOfKeys)(i => ORSetKey[EntityId](s"shard-${typeName}-${shardId}-$i")) private def key(entityId: EntityId): ORSetKey[EntityId] = { val i = (math.abs(entityId.hashCode % numberOfKeys)) @@ -644,7 +644,7 @@ private[akka] class DDataShard( getState() private def getState(): Unit = { - (0 until numberOfKeys).map { i ⇒ + (0 until numberOfKeys).map { i => replicator ! Get(stateKeys(i), readMajority, Some(i)) } } @@ -665,22 +665,22 @@ private[akka] class DDataShard( } { - case g @ GetSuccess(_, Some(i: Int)) ⇒ + case g @ GetSuccess(_, Some(i: Int)) => val key = stateKeys(i) state = state.copy(entities = state.entities union (g.get(key).elements)) receiveOne(i) - case GetFailure(_, _) ⇒ + case GetFailure(_, _) => log.error( "The DDataShard was unable to get an initial state within 'waiting-for-state-timeout': {} millis", waitingForStateTimeout.toMillis) // parent ShardRegion supervisor will notice that it terminated and will start it again, after backoff context.stop(self) - case NotFound(_, Some(i: Int)) ⇒ + case NotFound(_, Some(i: Int)) => receiveOne(i) - case _ ⇒ + case _ => stash() } } @@ -693,30 +693,30 @@ private[akka] class DDataShard( context.become(receiveCommand) } - override def processChange[E <: StateChange](event: E)(handler: E ⇒ Unit): Unit = { + override def processChange[E <: StateChange](event: E)(handler: E => Unit): Unit = { context.become(waitingForUpdate(event, handler), discardOld = false) sendUpdate(event, retryCount = 1) } private def sendUpdate(evt: StateChange, retryCount: Int) = { replicator ! Update(key(evt.entityId), ORSet.empty[EntityId], writeMajority, - Some((evt, retryCount))) { existing ⇒ + Some((evt, retryCount))) { existing => evt match { - case EntityStarted(id) ⇒ existing + id - case EntityStopped(id) ⇒ existing - id + case EntityStarted(id) => existing + id + case EntityStopped(id) => existing - id } } } // this state will stash all messages until it receives UpdateSuccess - private def waitingForUpdate[E <: StateChange](evt: E, afterUpdateCallback: E ⇒ Unit): Receive = { - case UpdateSuccess(_, Some((`evt`, _))) ⇒ + private def waitingForUpdate[E <: StateChange](evt: E, afterUpdateCallback: E => Unit): Receive = { + case UpdateSuccess(_, Some((`evt`, _))) => log.debug("The DDataShard state was successfully updated with {}", evt) context.unbecome() afterUpdateCallback(evt) unstashAll() - case UpdateTimeout(_, Some((`evt`, retryCount: Int))) ⇒ + case UpdateTimeout(_, Some((`evt`, retryCount: Int))) => if (retryCount == maxUpdateAttempts) { // parent ShardRegion supervisor will notice that it terminated and will start it again, after backoff log.error( @@ -731,7 +731,7 @@ private[akka] class DDataShard( sendUpdate(evt, retryCount + 1) } - case ModifyFailure(_, error, cause, Some((`evt`, _))) ⇒ + case ModifyFailure(_, error, cause, Some((`evt`, _))) => log.error( cause, "The DDataShard was unable to update state with error {} and event {}. Shard will be restarted", @@ -739,7 +739,7 @@ private[akka] class DDataShard( evt) throw cause - case _ ⇒ stash() + case _ => stash() } } @@ -775,7 +775,7 @@ final class ConstantRateEntityRecoveryStrategy(actorSystem: ActorSystem, frequen override def recoverEntities(entities: Set[EntityId]): Set[Future[Set[EntityId]]] = entities.grouped(numberOfEntities).foldLeft((frequency, Set[Future[Set[EntityId]]]())) { - case ((interval, scheduledEntityIds), entityIds) ⇒ + case ((interval, scheduledEntityIds), entityIds) => (interval + frequency, scheduledEntityIds + scheduleEntities(interval, entityIds)) }._2 diff --git a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ShardCoordinator.scala b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ShardCoordinator.scala index 50e47ba2ba..1c27e400a9 100644 --- a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ShardCoordinator.scala +++ b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ShardCoordinator.scala @@ -162,7 +162,7 @@ object ShardCoordinator { override def allocateShard(requester: ActorRef, shardId: ShardId, currentShardAllocations: Map[ActorRef, immutable.IndexedSeq[ShardId]]): Future[ActorRef] = { - val (regionWithLeastShards, _) = currentShardAllocations.minBy { case (_, v) ⇒ v.size } + val (regionWithLeastShards, _) = currentShardAllocations.minBy { case (_, v) => v.size } Future.successful(regionWithLeastShards) } @@ -170,9 +170,9 @@ object ShardCoordinator { currentShardAllocations: Map[ActorRef, immutable.IndexedSeq[ShardId]], rebalanceInProgress: Set[ShardId]): Future[Set[ShardId]] = { if (rebalanceInProgress.size < maxSimultaneousRebalance) { - val (regionWithLeastShards, leastShards) = currentShardAllocations.minBy { case (_, v) ⇒ v.size } + val (regionWithLeastShards, leastShards) = currentShardAllocations.minBy { case (_, v) => v.size } val mostShards = currentShardAllocations.collect { - case (_, v) ⇒ v.filterNot(s ⇒ rebalanceInProgress(s)) + case (_, v) => v.filterNot(s => rebalanceInProgress(s)) }.maxBy(_.size) val difference = mostShards.size - leastShards.size if (difference > rebalanceThreshold) { @@ -304,13 +304,13 @@ object ShardCoordinator { def allShards: Set[ShardId] = shards.keySet union unallocatedShards def updated(event: DomainEvent): State = event match { - case ShardRegionRegistered(region) ⇒ + case ShardRegionRegistered(region) => require(!regions.contains(region), s"Region $region already registered: $this") copy(regions = regions.updated(region, Vector.empty)) - case ShardRegionProxyRegistered(proxy) ⇒ + case ShardRegionProxyRegistered(proxy) => require(!regionProxies.contains(proxy), s"Region proxy $proxy already registered: $this") copy(regionProxies = regionProxies + proxy) - case ShardRegionTerminated(region) ⇒ + case ShardRegionTerminated(region) => require(regions.contains(region), s"Terminated region $region not registered: $this") val newUnallocatedShards = if (rememberEntities) (unallocatedShards ++ regions(region)) else unallocatedShards @@ -318,10 +318,10 @@ object ShardCoordinator { regions = regions - region, shards = shards -- regions(region), unallocatedShards = newUnallocatedShards) - case ShardRegionProxyTerminated(proxy) ⇒ + case ShardRegionProxyTerminated(proxy) => require(regionProxies.contains(proxy), s"Terminated region proxy $proxy not registered: $this") copy(regionProxies = regionProxies - proxy) - case ShardHomeAllocated(shard, region) ⇒ + case ShardHomeAllocated(shard, region) => require(regions.contains(region), s"Region $region not registered: $this") require(!shards.contains(shard), s"Shard [$shard] already allocated: $this") val newUnallocatedShards = @@ -330,7 +330,7 @@ object ShardCoordinator { shards = shards.updated(shard, region), regions = regions.updated(region, regions(region) :+ shard), unallocatedShards = newUnallocatedShards) - case ShardHomeDeallocated(shard) ⇒ + case ShardHomeDeallocated(shard) => require(shards.contains(shard), s"Shard [$shard] not allocated: $this") val region = shards(shard) require(regions.contains(region), s"Region $region for shard [$shard] not registered: $this") @@ -389,18 +389,18 @@ object ShardCoordinator { context.system.scheduler.scheduleOnce(handOffTimeout, self, ReceiveTimeout) def receive = { - case BeginHandOffAck(`shard`) ⇒ + case BeginHandOffAck(`shard`) => remaining -= sender() if (remaining.isEmpty) { from ! HandOff(shard) context.become(stoppingShard, discardOld = true) } - case ReceiveTimeout ⇒ done(ok = false) + case ReceiveTimeout => done(ok = false) } def stoppingShard: Receive = { - case ShardStopped(`shard`) ⇒ done(ok = true) - case ReceiveTimeout ⇒ done(ok = false) + case ShardStopped(`shard`) => done(ok = true) + case ReceiveTimeout => done(ok = false) } def done(ok: Boolean): Unit = { @@ -431,9 +431,9 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti val cluster = Cluster(context.system) val removalMargin = cluster.downingProvider.downRemovalMargin val minMembers = settings.role match { - case None ⇒ + case None => cluster.settings.MinNrOfMembers - case Some(r) ⇒ + case Some(r) => cluster.settings.MinNrOfMembersOfRole.getOrElse(r, cluster.settings.MinNrOfMembers) } var allRegionsRegistered = false @@ -461,11 +461,11 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti def isMember(region: ActorRef): Boolean = { val regionAddress = region.path.address (region.path.address == self.path.address || - cluster.state.members.exists(m ⇒ m.address == regionAddress && m.status == MemberStatus.Up)) + cluster.state.members.exists(m => m.address == regionAddress && m.status == MemberStatus.Up)) } def active: Receive = ({ - case Register(region) ⇒ + case Register(region) => if (isMember(region)) { log.debug("ShardRegion registered: [{}]", region) aliveRegions += region @@ -474,7 +474,7 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti allocateShardHomesForRememberEntities() } else { gracefulShutdownInProgress -= region - update(ShardRegionRegistered(region)) { evt ⇒ + update(ShardRegionRegistered(region)) { evt => state = state.updated(evt) context.watch(region) region ! RegisterAck(self) @@ -485,19 +485,19 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti log.debug("ShardRegion {} was not registered since the coordinator currently does not know about a node of that region", region) } - case RegisterProxy(proxy) ⇒ + case RegisterProxy(proxy) => log.debug("ShardRegion proxy registered: [{}]", proxy) if (state.regionProxies.contains(proxy)) proxy ! RegisterAck(self) else { - update(ShardRegionProxyRegistered(proxy)) { evt ⇒ + update(ShardRegionProxyRegistered(proxy)) { evt => state = state.updated(evt) context.watch(proxy) proxy ! RegisterAck(self) } } - case GetShardHome(shard) ⇒ + case GetShardHome(shard) => if (!handleGetShardHome(shard)) { // location not know, yet val activeRegions = state.regions -- gracefulShutdownInProgress @@ -505,63 +505,63 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti val getShardHomeSender = sender() val regionFuture = allocationStrategy.allocateShard(getShardHomeSender, shard, activeRegions) regionFuture.value match { - case Some(Success(region)) ⇒ + case Some(Success(region)) => continueGetShardHome(shard, region, getShardHomeSender) - case _ ⇒ + case _ => // continue when future is completed - regionFuture.map { region ⇒ + regionFuture.map { region => AllocateShardResult(shard, Some(region), getShardHomeSender) }.recover { - case _ ⇒ AllocateShardResult(shard, None, getShardHomeSender) + case _ => AllocateShardResult(shard, None, getShardHomeSender) }.pipeTo(self) } } } - case AllocateShardResult(shard, None, getShardHomeSender) ⇒ + case AllocateShardResult(shard, None, getShardHomeSender) => log.debug("Shard [{}] allocation failed. It will be retried.", shard) - case AllocateShardResult(shard, Some(region), getShardHomeSender) ⇒ + case AllocateShardResult(shard, Some(region), getShardHomeSender) => continueGetShardHome(shard, region, getShardHomeSender) - case ShardStarted(shard) ⇒ + case ShardStarted(shard) => unAckedHostShards.get(shard) match { - case Some(cancel) ⇒ + case Some(cancel) => cancel.cancel() unAckedHostShards = unAckedHostShards - shard - case _ ⇒ + case _ => } - case ResendShardHost(shard, region) ⇒ + case ResendShardHost(shard, region) => state.shards.get(shard) match { - case Some(`region`) ⇒ sendHostShardMsg(shard, region) - case _ ⇒ //Reallocated to another region + case Some(`region`) => sendHostShardMsg(shard, region) + case _ => //Reallocated to another region } - case RebalanceTick ⇒ + case RebalanceTick => if (state.regions.nonEmpty) { val shardsFuture = allocationStrategy.rebalance(state.regions, rebalanceInProgress.keySet) shardsFuture.value match { - case Some(Success(shards)) ⇒ + case Some(Success(shards)) => continueRebalance(shards) - case _ ⇒ + case _ => // continue when future is completed - shardsFuture.map { shards ⇒ RebalanceResult(shards) + shardsFuture.map { shards => RebalanceResult(shards) }.recover { - case _ ⇒ RebalanceResult(Set.empty) + case _ => RebalanceResult(Set.empty) }.pipeTo(self) } } - case RebalanceResult(shards) ⇒ + case RebalanceResult(shards) => continueRebalance(shards) - case RebalanceDone(shard, ok) ⇒ + case RebalanceDone(shard, ok) => log.debug("Rebalance shard [{}] done [{}]", shard, ok) // The shard could have been removed by ShardRegionTerminated if (state.shards.contains(shard)) { if (ok) { - update(ShardHomeDeallocated(shard)) { evt ⇒ + update(ShardHomeDeallocated(shard)) { evt => log.debug("Shard [{}] deallocated after rebalance", shard) state = state.updated(evt) clearRebalanceInProgress(shard) @@ -576,48 +576,48 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti clearRebalanceInProgress(shard) } - case GracefulShutdownReq(region) ⇒ + case GracefulShutdownReq(region) => if (!gracefulShutdownInProgress(region)) state.regions.get(region) match { - case Some(shards) ⇒ + case Some(shards) => log.debug("Graceful shutdown of region [{}] with shards [{}]", region, shards) gracefulShutdownInProgress += region continueRebalance(shards.toSet) - case None ⇒ + case None => } - case ShardRegion.GetClusterShardingStats(waitMax) ⇒ + case ShardRegion.GetClusterShardingStats(waitMax) => import akka.pattern.ask implicit val timeout: Timeout = waitMax - Future.sequence(aliveRegions.map { regionActor ⇒ + Future.sequence(aliveRegions.map { regionActor => (regionActor ? ShardRegion.GetShardRegionStats).mapTo[ShardRegion.ShardRegionStats] - .map(stats ⇒ regionActor → stats) - }).map { allRegionStats ⇒ + .map(stats => regionActor -> stats) + }).map { allRegionStats => ShardRegion.ClusterShardingStats(allRegionStats.map { - case (region, stats) ⇒ + case (region, stats) => val regionAddress = region.path.address val address: Address = if (regionAddress.hasLocalScope && regionAddress.system == cluster.selfAddress.system) cluster.selfAddress else regionAddress - address → stats + address -> stats }.toMap) }.recover { - case x: AskTimeoutException ⇒ ShardRegion.ClusterShardingStats(Map.empty) + case x: AskTimeoutException => ShardRegion.ClusterShardingStats(Map.empty) }.pipeTo(sender()) - case ShardHome(_, _) ⇒ + case ShardHome(_, _) => //On rebalance, we send ourselves a GetShardHome message to reallocate a // shard. This receive handles the "response" from that message. i.e. ignores it. - case ClusterShuttingDown ⇒ + case ClusterShuttingDown => log.debug("Shutting down ShardCoordinator") // can't stop because supervisor will start it again, // it will soon be stopped when singleton is stopped context.become(shuttingDown) - case ShardRegion.GetCurrentRegions ⇒ - val reply = ShardRegion.CurrentRegions(state.regions.keySet.map { ref ⇒ + case ShardRegion.GetCurrentRegions => + val reply = ShardRegion.CurrentRegions(state.regions.keySet.map { ref => if (ref.path.address.host.isEmpty) cluster.selfAddress else ref.path.address }) @@ -627,13 +627,13 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti private def clearRebalanceInProgress(shard: String): Unit = { rebalanceInProgress.get(shard) match { - case Some(pendingGetShardHome) ⇒ + case Some(pendingGetShardHome) => val msg = GetShardHome(shard) - pendingGetShardHome.foreach { getShardHomeSender ⇒ + pendingGetShardHome.foreach { getShardHomeSender => self.tell(msg, getShardHomeSender) } rebalanceInProgress -= shard - case None ⇒ + case None => } } @@ -656,20 +656,20 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti true } else { state.shards.get(shard) match { - case Some(ref) ⇒ + case Some(ref) => if (regionTerminationInProgress(ref)) log.debug("GetShardHome [{}] request ignored, due to region [{}] termination in progress.", shard, ref) else sender() ! ShardHome(shard, ref) true - case None ⇒ + case None => false // location not known, yet, caller will handle allocation } } } def receiveTerminated: Receive = { - case t @ Terminated(ref) ⇒ + case t @ Terminated(ref) => if (state.regions.contains(ref)) { if (removalMargin != Duration.Zero && t.addressTerminated && aliveRegions(ref)) { context.system.scheduler.scheduleOnce(removalMargin, self, DelayedShardRegionTerminated(ref)) @@ -680,11 +680,11 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti regionProxyTerminated(ref) } - case DelayedShardRegionTerminated(ref) ⇒ + case DelayedShardRegionTerminated(ref) => regionTerminated(ref) } - def update[E <: DomainEvent](evt: E)(f: E ⇒ Unit): Unit + def update[E <: DomainEvent](evt: E)(f: E => Unit): Unit def watchStateActors(): Unit = { @@ -694,14 +694,14 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti // amount of lost messages during startup. val nodes = cluster.state.members.map(_.address) state.regions.foreach { - case (ref, _) ⇒ + case (ref, _) => val a = ref.path.address if (a.hasLocalScope || nodes(a)) context.watch(ref) else regionTerminated(ref) // not part of cluster } - state.regionProxies.foreach { ref ⇒ + state.regionProxies.foreach { ref => val a = ref.path.address if (a.hasLocalScope || nodes(a)) context.watch(ref) @@ -717,7 +717,7 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti } def stateInitialized(): Unit = { - state.shards.foreach { case (a, r) ⇒ sendHostShardMsg(a, r) } + state.shards.foreach { case (a, r) => sendHostShardMsg(a, r) } allocateShardHomesForRememberEntities() } @@ -734,9 +734,9 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti if (state.regions.contains(ref)) { log.debug("ShardRegion terminated: [{}]", ref) regionTerminationInProgress += ref - state.regions(ref).foreach { s ⇒ self ! GetShardHome(s) } + state.regions(ref).foreach { s => self ! GetShardHome(s) } - update(ShardRegionTerminated(ref)) { evt ⇒ + update(ShardRegionTerminated(ref)) { evt => state = state.updated(evt) gracefulShutdownInProgress -= ref regionTerminationInProgress -= ref @@ -748,13 +748,13 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti def regionProxyTerminated(ref: ActorRef): Unit = if (state.regionProxies.contains(ref)) { log.debug("ShardRegion proxy terminated: [{}]", ref) - update(ShardRegionProxyTerminated(ref)) { evt ⇒ + update(ShardRegionProxyTerminated(ref)) { evt => state = state.updated(evt) } } def shuttingDown: Receive = { - case _ ⇒ // ignore all + case _ => // ignore all } def sendHostShardMsg(shard: ShardId, region: ActorRef): Unit = { @@ -773,10 +773,10 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti deferGetShardHomeRequest(shard, getShardHomeSender) } else { state.shards.get(shard) match { - case Some(ref) ⇒ getShardHomeSender ! ShardHome(shard, ref) - case None ⇒ + case Some(ref) => getShardHomeSender ! ShardHome(shard, ref) + case None => if (state.regions.contains(region) && !gracefulShutdownInProgress.contains(region)) { - update(ShardHomeAllocated(shard, region)) { evt ⇒ + update(ShardHomeAllocated(shard, region)) { evt => state = state.updated(evt) log.debug("Shard [{}] allocated at [{}]", evt.shard, evt.region) @@ -791,16 +791,16 @@ abstract class ShardCoordinator(typeName: String, settings: ClusterShardingSetti } def continueRebalance(shards: Set[ShardId]): Unit = - shards.foreach { shard ⇒ + shards.foreach { shard => if (!rebalanceInProgress.contains(shard)) { state.shards.get(shard) match { - case Some(rebalanceFromRegion) ⇒ + case Some(rebalanceFromRegion) => rebalanceInProgress = rebalanceInProgress.updated(shard, Set.empty) log.debug("Rebalance shard [{}] from [{}]", shard, rebalanceFromRegion) context.actorOf(rebalanceWorkerProps(shard, rebalanceFromRegion, handOffTimeout, state.regions.keySet union state.regionProxies) .withDispatcher(context.props.dispatcher)) - case None ⇒ + case None => log.debug("Rebalance of non-existing shard [{}] is ignored", shard) } @@ -827,14 +827,14 @@ class PersistentShardCoordinator(typeName: String, settings: ClusterShardingSett override def snapshotPluginId: String = settings.snapshotPluginId override def receiveRecover: Receive = { - case evt: DomainEvent ⇒ + case evt: DomainEvent => log.debug("receiveRecover {}", evt) evt match { - case ShardRegionRegistered(region) ⇒ + case ShardRegionRegistered(region) => state = state.updated(evt) - case ShardRegionProxyRegistered(proxy) ⇒ + case ShardRegionProxyRegistered(proxy) => state = state.updated(evt) - case ShardRegionTerminated(region) ⇒ + case ShardRegionTerminated(region) => if (state.regions.contains(region)) state = state.updated(evt) else { @@ -842,16 +842,16 @@ class PersistentShardCoordinator(typeName: String, settings: ClusterShardingSett " some stored ActorRef in Akka v2.3.0 and v2.3.1 did not contain full address information. It will be " + "removed by later watch.", region) } - case ShardRegionProxyTerminated(proxy) ⇒ + case ShardRegionProxyTerminated(proxy) => if (state.regionProxies.contains(proxy)) state = state.updated(evt) - case ShardHomeAllocated(shard, region) ⇒ + case ShardHomeAllocated(shard, region) => state = state.updated(evt) - case _: ShardHomeDeallocated ⇒ + case _: ShardHomeDeallocated => state = state.updated(evt) } - case SnapshotOffer(_, st: State) ⇒ + case SnapshotOffer(_, st: State) => log.debug("receiveRecover SnapshotOffer {}", st) state = st.withRememberEntities(settings.rememberEntities) //Old versions of the state object may not have unallocatedShard set, @@ -859,7 +859,7 @@ class PersistentShardCoordinator(typeName: String, settings: ClusterShardingSett if (state.unallocatedShards == null) state = state.copy(unallocatedShards = Set.empty) - case RecoveryCompleted ⇒ + case RecoveryCompleted => state = state.withRememberEntities(settings.rememberEntities) watchStateActors() } @@ -867,35 +867,35 @@ class PersistentShardCoordinator(typeName: String, settings: ClusterShardingSett override def receiveCommand: Receive = waitingForStateInitialized def waitingForStateInitialized: Receive = ({ - case StateInitialized ⇒ + case StateInitialized => stateInitialized() context.become(active.orElse[Any, Unit](receiveSnapshotResult)) }: Receive).orElse[Any, Unit](receiveTerminated).orElse[Any, Unit](receiveSnapshotResult) def receiveSnapshotResult: Receive = { - case e: SaveSnapshotSuccess ⇒ + case e: SaveSnapshotSuccess => log.debug("Persistent snapshot saved successfully") internalDeleteMessagesBeforeSnapshot(e, keepNrOfBatches, snapshotAfter) - case SaveSnapshotFailure(_, reason) ⇒ + case SaveSnapshotFailure(_, reason) => log.warning("Persistent snapshot failure: {}", reason.getMessage) - case DeleteMessagesSuccess(toSequenceNr) ⇒ + case DeleteMessagesSuccess(toSequenceNr) => log.debug("Persistent messages to {} deleted successfully", toSequenceNr) deleteSnapshots(SnapshotSelectionCriteria(maxSequenceNr = toSequenceNr - 1)) - case DeleteMessagesFailure(reason, toSequenceNr) ⇒ + case DeleteMessagesFailure(reason, toSequenceNr) => log.warning("Persistent messages to {} deletion failure: {}", toSequenceNr, reason.getMessage) - case DeleteSnapshotsSuccess(m) ⇒ + case DeleteSnapshotsSuccess(m) => log.debug("Persistent snapshots matching {} deleted successfully", m) - case DeleteSnapshotsFailure(m, reason) ⇒ + case DeleteSnapshotsFailure(m, reason) => log.warning("Persistent snapshots matching {} deletion failure: {}", m, reason.getMessage) } - def update[E <: DomainEvent](evt: E)(f: E ⇒ Unit): Unit = { + def update[E <: DomainEvent](evt: E)(f: E => Unit): Unit = { saveSnapshotWhenNeeded() persist(evt)(f) } @@ -949,7 +949,7 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, // This state will drop all other messages since they will be retried def waitingForState(remainingKeys: Set[Key[ReplicatedData]]): Receive = ({ - case g @ GetSuccess(CoordinatorStateKey, _) ⇒ + case g @ GetSuccess(CoordinatorStateKey, _) => state = g.get(CoordinatorStateKey).value.withRememberEntities(settings.rememberEntities) val newRemainingKeys = remainingKeys - CoordinatorStateKey if (newRemainingKeys.isEmpty) @@ -957,21 +957,21 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, else context.become(waitingForState(newRemainingKeys)) - case GetFailure(CoordinatorStateKey, _) ⇒ + case GetFailure(CoordinatorStateKey, _) => log.error( "The ShardCoordinator was unable to get an initial state within 'waiting-for-state-timeout': {} millis (retrying). Has ClusterSharding been started on all nodes?", readMajority.timeout.toMillis) // repeat until GetSuccess getCoordinatorState() - case NotFound(CoordinatorStateKey, _) ⇒ + case NotFound(CoordinatorStateKey, _) => val newRemainingKeys = remainingKeys - CoordinatorStateKey if (newRemainingKeys.isEmpty) becomeWaitingForStateInitialized() else context.become(waitingForState(newRemainingKeys)) - case g @ GetSuccess(AllShardsKey, _) ⇒ + case g @ GetSuccess(AllShardsKey, _) => shards = g.get(AllShardsKey).elements val newUnallocatedShards = state.unallocatedShards union (shards diff state.shards.keySet) state = state.copy(unallocatedShards = newUnallocatedShards) @@ -981,14 +981,14 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, else context.become(waitingForState(newRemainingKeys)) - case GetFailure(AllShardsKey, _) ⇒ + case GetFailure(AllShardsKey, _) => log.error( "The ShardCoordinator was unable to get all shards state within 'waiting-for-state-timeout': {} millis (retrying)", readMajority.timeout.toMillis) // repeat until GetSuccess getAllShards() - case NotFound(AllShardsKey, _) ⇒ + case NotFound(AllShardsKey, _) => val newRemainingKeys = remainingKeys - AllShardsKey if (newRemainingKeys.isEmpty) becomeWaitingForStateInitialized() @@ -1011,18 +1011,18 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, // this state will stash all messages until it receives StateInitialized, // which was scheduled by previous watchStateActors def waitingForStateInitialized: Receive = { - case StateInitialized ⇒ + case StateInitialized => unstashAll() stateInitialized() activate() - case _ ⇒ stash() + case _ => stash() } // this state will stash all messages until it receives UpdateSuccess - def waitingForUpdate[E <: DomainEvent](evt: E, afterUpdateCallback: E ⇒ Unit, + def waitingForUpdate[E <: DomainEvent](evt: E, afterUpdateCallback: E => Unit, remainingKeys: Set[Key[ReplicatedData]]): Receive = { - case UpdateSuccess(CoordinatorStateKey, Some(`evt`)) ⇒ + case UpdateSuccess(CoordinatorStateKey, Some(`evt`)) => log.debug("The coordinator state was successfully updated with {}", evt) val newRemainingKeys = remainingKeys - CoordinatorStateKey if (newRemainingKeys.isEmpty) @@ -1030,7 +1030,7 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, else context.become(waitingForUpdate(evt, afterUpdateCallback, newRemainingKeys)) - case UpdateTimeout(CoordinatorStateKey, Some(`evt`)) ⇒ + case UpdateTimeout(CoordinatorStateKey, Some(`evt`)) => log.error( "The ShardCoordinator was unable to update a distributed state within 'updating-state-timeout': {} millis (retrying). " + "Perhaps the ShardRegion has not started on all active nodes yet? event={}", @@ -1038,7 +1038,7 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, // repeat until UpdateSuccess sendCoordinatorStateUpdate(evt) - case UpdateSuccess(AllShardsKey, Some(newShard: String)) ⇒ + case UpdateSuccess(AllShardsKey, Some(newShard: String)) => log.debug("The coordinator shards state was successfully updated with {}", newShard) val newRemainingKeys = remainingKeys - AllShardsKey if (newRemainingKeys.isEmpty) @@ -1046,28 +1046,28 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, else context.become(waitingForUpdate(evt, afterUpdateCallback, newRemainingKeys)) - case UpdateTimeout(AllShardsKey, Some(newShard: String)) ⇒ + case UpdateTimeout(AllShardsKey, Some(newShard: String)) => log.error( "The ShardCoordinator was unable to update shards distributed state within 'updating-state-timeout': {} millis (retrying), event={}", writeMajority.timeout.toMillis, evt) // repeat until UpdateSuccess sendAllShardsUpdate(newShard) - case ModifyFailure(key, error, cause, _) ⇒ + case ModifyFailure(key, error, cause, _) => log.error( cause, "The ShardCoordinator was unable to update a distributed state {} with error {} and event {}.Coordinator will be restarted", key, error, evt) throw cause - case GetShardHome(shard) ⇒ + case GetShardHome(shard) => if (!handleGetShardHome(shard)) stash() // must wait for update that is in progress - case _ ⇒ stash() + case _ => stash() } - private def unbecomeAfterUpdate[E <: DomainEvent](evt: E, afterUpdateCallback: E ⇒ Unit): Unit = { + private def unbecomeAfterUpdate[E <: DomainEvent](evt: E, afterUpdateCallback: E => Unit): Unit = { context.unbecome() afterUpdateCallback(evt) unstashAll() @@ -1081,19 +1081,19 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, override def active: Receive = if (rememberEntities) { ({ - case chg @ Changed(AllShardsKey) ⇒ + case chg @ Changed(AllShardsKey) => shards = chg.get(AllShardsKey).elements }: Receive).orElse[Any, Unit](super.active) } else super.active - def update[E <: DomainEvent](evt: E)(f: E ⇒ Unit): Unit = { + def update[E <: DomainEvent](evt: E)(f: E => Unit): Unit = { sendCoordinatorStateUpdate(evt) evt match { - case s: ShardHomeAllocated if rememberEntities && !shards(s.shard) ⇒ + case s: ShardHomeAllocated if rememberEntities && !shards(s.shard) => sendAllShardsUpdate(s.shard) context.become(waitingForUpdate(evt, f, allKeys), discardOld = false) - case _ ⇒ + case _ => // no update of shards, already known context.become(waitingForUpdate(evt, f, Set(CoordinatorStateKey)), discardOld = false) } @@ -1111,7 +1111,7 @@ class DDataShardCoordinator(typeName: String, settings: ClusterShardingSettings, def sendCoordinatorStateUpdate(evt: DomainEvent) = { val s = state.updated(evt) - replicator ! Update(CoordinatorStateKey, LWWRegister(initEmptyState), writeMajority, Some(evt)) { reg ⇒ + replicator ! Update(CoordinatorStateKey, LWWRegister(initEmptyState), writeMajority, Some(evt)) { reg => reg.withValue(s) } } diff --git a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ShardRegion.scala b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ShardRegion.scala index 4989b789ed..b19da256de 100644 --- a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ShardRegion.scala +++ b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/ShardRegion.scala @@ -35,7 +35,7 @@ object ShardRegion { */ private[akka] def props( typeName: String, - entityProps: String ⇒ Props, + entityProps: String => Props, settings: ClusterShardingSettings, coordinatorPath: String, extractEntityId: ShardRegion.ExtractEntityId, @@ -92,7 +92,7 @@ object ShardRegion { * Only messages that passed the [[ExtractEntityId]] will be used * as input to this function. */ - type ExtractShardId = Msg ⇒ ShardId + type ExtractShardId = Msg => ShardId /** * Java API: Interface of functions to extract entity id, @@ -144,8 +144,8 @@ object ShardRegion { override def shardId(message: Any): String = { val id = message match { - case ShardRegion.StartEntity(entityId) ⇒ entityId - case _ ⇒ entityId(message) + case ShardRegion.StartEntity(entityId) => entityId + case _ => entityId(message) } HashCodeMessageExtractor.shardId(id, maxNumberOfShards) } @@ -347,7 +347,7 @@ object ShardRegion { context.setReceiveTimeout(handoffTimeout) - entities.foreach { a ⇒ + entities.foreach { a => context watch a a ! stopMessage } @@ -355,16 +355,16 @@ object ShardRegion { var remaining = entities def receive = { - case ReceiveTimeout ⇒ + case ReceiveTimeout => log.warning("HandOffStopMessage[{}] is not handled by some of the entities of the `{}` shard, " + "stopping the remaining entities.", stopMessage.getClass.getName, shard) remaining.foreach { - ref ⇒ + ref => context stop ref } - case Terminated(ref) ⇒ + case Terminated(ref) => remaining -= ref if (remaining.isEmpty) { replyTo ! ShardStopped(shard) @@ -389,7 +389,7 @@ object ShardRegion { */ private[akka] class ShardRegion( typeName: String, - entityProps: Option[String ⇒ Props], + entityProps: Option[String => Props], dataCenter: Option[DataCenter], settings: ClusterShardingSettings, coordinatorPath: String, @@ -428,7 +428,7 @@ private[akka] class ShardRegion( val gracefulShutdownProgress = Promise[Done]() CoordinatedShutdown(context.system).addTask( CoordinatedShutdown.PhaseClusterShardingShutdownRegion, - "region-shutdown") { () ⇒ + "region-shutdown") { () => if (cluster.isTerminated || cluster.selfMember.status == MemberStatus.Down) { Future.successful(Done) } else { @@ -453,15 +453,15 @@ private[akka] class ShardRegion( // when using proxy the data center can be different from the own data center private val targetDcRole = dataCenter match { - case Some(t) ⇒ ClusterSettings.DcRolePrefix + t - case None ⇒ ClusterSettings.DcRolePrefix + cluster.settings.SelfDataCenter + case Some(t) => ClusterSettings.DcRolePrefix + t + case None => ClusterSettings.DcRolePrefix + cluster.settings.SelfDataCenter } def matchingRole(member: Member): Boolean = member.hasRole(targetDcRole) && role.forall(member.hasRole) def coordinatorSelection: Option[ActorSelection] = - membersByAge.headOption.map(m ⇒ context.actorSelection(RootActorPath(m.address) + coordinatorPath)) + membersByAge.headOption.map(m => context.actorSelection(RootActorPath(m.address) + coordinatorPath)) /** * When leaving the coordinator singleton is started rather quickly on next @@ -469,7 +469,7 @@ private[akka] class ShardRegion( * the likely locations of the coordinator. */ def gracefulShutdownCoordinatorSelections: List[ActorSelection] = - membersByAge.take(2).toList.map(m ⇒ context.actorSelection(RootActorPath(m.address) + coordinatorPath)) + membersByAge.take(2).toList.map(m => context.actorSelection(RootActorPath(m.address) + coordinatorPath)) var coordinator: Option[ActorRef] = None @@ -486,49 +486,49 @@ private[akka] class ShardRegion( } def receive: Receive = { - case Terminated(ref) ⇒ receiveTerminated(ref) - case ShardInitialized(shardId) ⇒ initializeShard(shardId, sender()) - case evt: ClusterDomainEvent ⇒ receiveClusterEvent(evt) - case state: CurrentClusterState ⇒ receiveClusterState(state) - case msg: CoordinatorMessage ⇒ receiveCoordinatorMessage(msg) - case cmd: ShardRegionCommand ⇒ receiveCommand(cmd) - case query: ShardRegionQuery ⇒ receiveQuery(query) - case msg: RestartShard ⇒ deliverMessage(msg, sender()) - case msg: StartEntity ⇒ deliverStartEntity(msg, sender()) - case msg if extractEntityId.isDefinedAt(msg) ⇒ deliverMessage(msg, sender()) - case unknownMsg ⇒ log.warning("Message does not have an extractor defined in shard [{}] so it was ignored: {}", typeName, unknownMsg) + case Terminated(ref) => receiveTerminated(ref) + case ShardInitialized(shardId) => initializeShard(shardId, sender()) + case evt: ClusterDomainEvent => receiveClusterEvent(evt) + case state: CurrentClusterState => receiveClusterState(state) + case msg: CoordinatorMessage => receiveCoordinatorMessage(msg) + case cmd: ShardRegionCommand => receiveCommand(cmd) + case query: ShardRegionQuery => receiveQuery(query) + case msg: RestartShard => deliverMessage(msg, sender()) + case msg: StartEntity => deliverStartEntity(msg, sender()) + case msg if extractEntityId.isDefinedAt(msg) => deliverMessage(msg, sender()) + case unknownMsg => log.warning("Message does not have an extractor defined in shard [{}] so it was ignored: {}", typeName, unknownMsg) } def receiveClusterState(state: CurrentClusterState): Unit = { - changeMembers(immutable.SortedSet.empty(ageOrdering) union state.members.filter(m ⇒ + changeMembers(immutable.SortedSet.empty(ageOrdering) union state.members.filter(m => m.status == MemberStatus.Up && matchingRole(m))) } def receiveClusterEvent(evt: ClusterDomainEvent): Unit = evt match { - case MemberUp(m) ⇒ + case MemberUp(m) => if (matchingRole(m)) // replace, it's possible that the upNumber is changed changeMembers(membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) + m) - case MemberRemoved(m, _) ⇒ + case MemberRemoved(m, _) => if (m.uniqueAddress == cluster.selfUniqueAddress) context.stop(self) else if (matchingRole(m)) changeMembers(membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress)) - case MemberDowned(m) ⇒ + case MemberDowned(m) => if (m.uniqueAddress == cluster.selfUniqueAddress) { log.info("Self downed, stopping ShardRegion [{}]", self.path) context.stop(self) } - case _: MemberEvent ⇒ // these are expected, no need to warn about them + case _: MemberEvent => // these are expected, no need to warn about them - case _ ⇒ unhandled(evt) + case _ => unhandled(evt) } def receiveCoordinatorMessage(msg: CoordinatorMessage): Unit = msg match { - case HostShard(shard) ⇒ + case HostShard(shard) => log.debug("Host Shard [{}] ", shard) regionByShard = regionByShard.updated(shard, self) regions = regions.updated(self, regions.getOrElse(self, Set.empty) + shard) @@ -538,13 +538,13 @@ private[akka] class ShardRegion( sender() ! ShardStarted(shard) - case ShardHome(shard, ref) ⇒ + case ShardHome(shard, ref) => log.debug("Shard [{}] located at [{}]", shard, ref) regionByShard.get(shard) match { - case Some(r) if r == self && ref != self ⇒ + case Some(r) if r == self && ref != self => // should not happen, inconsistency between ShardRegion and ShardCoordinator throw new IllegalStateException(s"Unexpected change of shard [$shard] from self to [$ref]") - case _ ⇒ + case _ => } regionByShard = regionByShard.updated(shard, ref) regions = regions.updated(ref, regions.getOrElse(ref, Set.empty) + shard) @@ -557,12 +557,12 @@ private[akka] class ShardRegion( else deliverBufferedMessages(shard, ref) - case RegisterAck(coord) ⇒ + case RegisterAck(coord) => context.watch(coord) coordinator = Some(coord) requestShardBufferHomes() - case BeginHandOff(shard) ⇒ + case BeginHandOff(shard) => log.debug("BeginHandOff shard [{}]", shard) if (regionByShard.contains(shard)) { val regionRef = regionByShard(shard) @@ -573,7 +573,7 @@ private[akka] class ShardRegion( } sender() ! BeginHandOffAck(shard) - case msg @ HandOff(shard) ⇒ + case msg @ HandOff(shard) => log.debug("HandOff shard [{}]", shard) // must drop requests that came in between the BeginHandOff and now, @@ -590,12 +590,12 @@ private[akka] class ShardRegion( } else sender() ! ShardStopped(shard) - case _ ⇒ unhandled(msg) + case _ => unhandled(msg) } def receiveCommand(cmd: ShardRegionCommand): Unit = cmd match { - case Retry ⇒ + case Retry => sendGracefulShutdownToCoordinator() if (shardBuffers.nonEmpty) @@ -608,32 +608,32 @@ private[akka] class ShardRegion( tryCompleteGracefulShutdown() - case GracefulShutdown ⇒ + case GracefulShutdown => log.debug("Starting graceful shutdown of region and all its shards") gracefulShutdownInProgress = true sendGracefulShutdownToCoordinator() tryCompleteGracefulShutdown() - case _ ⇒ unhandled(cmd) + case _ => unhandled(cmd) } def receiveQuery(query: ShardRegionQuery): Unit = query match { - case GetCurrentRegions ⇒ + case GetCurrentRegions => coordinator match { - case Some(c) ⇒ c.forward(GetCurrentRegions) - case None ⇒ sender() ! CurrentRegions(Set.empty) + case Some(c) => c.forward(GetCurrentRegions) + case None => sender() ! CurrentRegions(Set.empty) } - case GetShardRegionState ⇒ + case GetShardRegionState => replyToRegionStateQuery(sender()) - case GetShardRegionStats ⇒ + case GetShardRegionStats => replyToRegionStatsQuery(sender()) - case msg: GetClusterShardingStats ⇒ + case msg: GetClusterShardingStats => coordinator.fold(sender ! ClusterShardingStats(Map.empty))(_ forward msg) - case _ ⇒ unhandled(query) + case _ => unhandled(query) } def receiveTerminated(ref: ActorRef): Unit = { @@ -667,29 +667,29 @@ private[akka] class ShardRegion( } def replyToRegionStateQuery(ref: ActorRef): Unit = { - askAllShards[Shard.CurrentShardState](Shard.GetCurrentShardState).map { shardStates ⇒ + askAllShards[Shard.CurrentShardState](Shard.GetCurrentShardState).map { shardStates => CurrentShardRegionState(shardStates.map { - case (shardId, state) ⇒ ShardRegion.ShardState(shardId, state.entityIds) + case (shardId, state) => ShardRegion.ShardState(shardId, state.entityIds) }.toSet) }.recover { - case _: AskTimeoutException ⇒ CurrentShardRegionState(Set.empty) + case _: AskTimeoutException => CurrentShardRegionState(Set.empty) }.pipeTo(ref) } def replyToRegionStatsQuery(ref: ActorRef): Unit = { - askAllShards[Shard.ShardStats](Shard.GetShardStats).map { shardStats ⇒ + askAllShards[Shard.ShardStats](Shard.GetShardStats).map { shardStats => ShardRegionStats(shardStats.map { - case (shardId, stats) ⇒ (shardId, stats.entityCount) + case (shardId, stats) => (shardId, stats.entityCount) }.toMap) }.recover { - case x: AskTimeoutException ⇒ ShardRegionStats(Map.empty) + case x: AskTimeoutException => ShardRegionStats(Map.empty) }.pipeTo(ref) } def askAllShards[T: ClassTag](msg: Any): Future[Seq[(ShardId, T)]] = { implicit val timeout: Timeout = 3.seconds Future.sequence(shards.toSeq.map { - case (shardId, ref) ⇒ (ref ? msg).mapTo[T].map(t ⇒ (shardId, t)) + case (shardId, ref) => (ref ? msg).mapTo[T].map(t => (shardId, t)) }) } @@ -701,7 +701,7 @@ private[akka] class ShardRegion( def register(): Unit = { coordinatorSelection.foreach(_ ! registrationMessage) if (shardBuffers.nonEmpty && retryCount >= 5) coordinatorSelection match { - case Some(actorSelection) ⇒ + case Some(actorSelection) => val coordinatorMessage = if (cluster.state.unreachable(membersByAge.head)) s"Coordinator [${membersByAge.head}] is unreachable." else s"Coordinator [${membersByAge.head}] is reachable." @@ -709,7 +709,7 @@ private[akka] class ShardRegion( "Trying to register to coordinator at [{}], but no acknowledgement. Total [{}] buffered messages. [{}]", actorSelection, shardBuffers.totalSize, coordinatorMessage ) - case None ⇒ log.warning( + case None => log.warning( "No coordinator found to register. Probably, no seed-nodes configured and manual cluster join not performed? Total [{}] buffered messages.", shardBuffers.totalSize) } @@ -720,7 +720,7 @@ private[akka] class ShardRegion( def requestShardBufferHomes(): Unit = { shardBuffers.foreach { - case (shard, buf) ⇒ coordinator.foreach { c ⇒ + case (shard, buf) => coordinator.foreach { c => val logMsg = "Retry request for shard [{}] homes from coordinator at [{}]. [{}] buffered messages." if (retryCount >= 5) log.warning(logMsg, shard, c, buf.size) @@ -767,7 +767,7 @@ private[akka] class ShardRegion( if (shardBuffers.contains(shardId)) { val buf = shardBuffers.getOrEmpty(shardId) log.debug("Deliver [{}] buffered messages for shard [{}]", buf.size, shardId) - buf.foreach { case (msg, snd) ⇒ receiver.tell(msg, snd) } + buf.foreach { case (msg, snd) => receiver.tell(msg, snd) } shardBuffers.remove(shardId) } loggedFullBufferWarning = false @@ -778,19 +778,19 @@ private[akka] class ShardRegion( try { deliverMessage(msg, snd) } catch { - case ex: MatchError ⇒ + case ex: MatchError => log.error(ex, "When using remember-entities the shard id extractor must handle ShardRegion.StartEntity(id).") } } def deliverMessage(msg: Any, snd: ActorRef): Unit = msg match { - case RestartShard(shardId) ⇒ + case RestartShard(shardId) => regionByShard.get(shardId) match { - case Some(ref) ⇒ + case Some(ref) => if (ref == self) getShard(shardId) - case None ⇒ + case None => if (!shardBuffers.contains(shardId)) { log.debug("Request shard [{}] home. Coordinator [{}]", shardId, coordinator) coordinator.foreach(_ ! GetShardHome(shardId)) @@ -800,26 +800,26 @@ private[akka] class ShardRegion( shardBuffers.append(shardId, msg, snd) } - case _ ⇒ + case _ => val shardId = extractShardId(msg) regionByShard.get(shardId) match { - case Some(ref) if ref == self ⇒ + case Some(ref) if ref == self => getShard(shardId) match { - case Some(shard) ⇒ + case Some(shard) => if (shardBuffers.contains(shardId)) { // Since now messages to a shard is buffered then those messages must be in right order bufferMessage(shardId, msg, snd) deliverBufferedMessages(shardId, shard) } else shard.tell(msg, snd) - case None ⇒ bufferMessage(shardId, msg, snd) + case None => bufferMessage(shardId, msg, snd) } - case Some(ref) ⇒ + case Some(ref) => log.debug("Forwarding request for shard [{}] to [{}]", shardId, ref) ref.tell(msg, snd) - case None if shardId == null || shardId == "" ⇒ + case None if shardId == null || shardId == "" => log.warning("Shard must not be empty, dropping message [{}]", msg.getClass.getName) context.system.deadLetters ! msg - case None ⇒ + case None => if (!shardBuffers.contains(shardId)) { log.debug("Request shard [{}] home. Coordinator [{}]", shardId, coordinator) coordinator.foreach(_ ! GetShardHome(shardId)) @@ -834,7 +834,7 @@ private[akka] class ShardRegion( else { shards.get(id).orElse( entityProps match { - case Some(props) if !shardsByRef.values.exists(_ == id) ⇒ + case Some(props) if !shardsByRef.values.exists(_ == id) => log.debug("Starting shard [{}] in region", id) val name = URLEncoder.encode(id, "utf-8") @@ -854,9 +854,9 @@ private[akka] class ShardRegion( shards = shards.updated(id, shard) startingShards += id None - case Some(props) ⇒ + case Some(props) => None - case None ⇒ + case None => throw new IllegalStateException("Shard must not be allocated to a proxy only ShardRegion") }) } diff --git a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/protobuf/ClusterShardingMessageSerializer.scala b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/protobuf/ClusterShardingMessageSerializer.scala index 7e1f4265ea..5eee5fde82 100644 --- a/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/protobuf/ClusterShardingMessageSerializer.scala +++ b/akka-cluster-sharding/src/main/scala/akka/cluster/sharding/protobuf/ClusterShardingMessageSerializer.scala @@ -15,7 +15,7 @@ import akka.actor.ActorRef import akka.actor.ExtendedActorSystem import akka.cluster.sharding.Shard import akka.cluster.sharding.ShardCoordinator -import akka.cluster.sharding.protobuf.msg.{ ClusterShardingMessages ⇒ sm } +import akka.cluster.sharding.protobuf.msg.{ ClusterShardingMessages => sm } import akka.serialization.BaseSerializer import akka.serialization.Serialization import akka.serialization.SerializerWithStringManifest @@ -32,7 +32,7 @@ private[akka] class ClusterShardingMessageSerializer(val system: ExtendedActorSy extends SerializerWithStringManifest with BaseSerializer { import ShardCoordinator.Internal._ import Shard.{ GetShardStats, ShardStats } - import Shard.{ State ⇒ EntityState, EntityStarted, EntityStopped } + import Shard.{ State => EntityState, EntityStarted, EntityStopped } private final val BufferSize = 1024 * 4 @@ -69,142 +69,142 @@ private[akka] class ClusterShardingMessageSerializer(val system: ExtendedActorSy private val GetShardRegionStatsManifest = "DC" private val ShardRegionStatsManifest = "DD" - private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] ⇒ AnyRef]( - EntityStateManifest → entityStateFromBinary, - EntityStartedManifest → entityStartedFromBinary, - EntityStoppedManifest → entityStoppedFromBinary, + private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] => AnyRef]( + EntityStateManifest -> entityStateFromBinary, + EntityStartedManifest -> entityStartedFromBinary, + EntityStoppedManifest -> entityStoppedFromBinary, - CoordinatorStateManifest → coordinatorStateFromBinary, - ShardRegionRegisteredManifest → { bytes ⇒ ShardRegionRegistered(actorRefMessageFromBinary(bytes)) }, - ShardRegionProxyRegisteredManifest → { bytes ⇒ ShardRegionProxyRegistered(actorRefMessageFromBinary(bytes)) }, - ShardRegionTerminatedManifest → { bytes ⇒ ShardRegionTerminated(actorRefMessageFromBinary(bytes)) }, - ShardRegionProxyTerminatedManifest → { bytes ⇒ ShardRegionProxyTerminated(actorRefMessageFromBinary(bytes)) }, - ShardHomeAllocatedManifest → shardHomeAllocatedFromBinary, - ShardHomeDeallocatedManifest → { bytes ⇒ ShardHomeDeallocated(shardIdMessageFromBinary(bytes)) }, + CoordinatorStateManifest -> coordinatorStateFromBinary, + ShardRegionRegisteredManifest -> { bytes => ShardRegionRegistered(actorRefMessageFromBinary(bytes)) }, + ShardRegionProxyRegisteredManifest -> { bytes => ShardRegionProxyRegistered(actorRefMessageFromBinary(bytes)) }, + ShardRegionTerminatedManifest -> { bytes => ShardRegionTerminated(actorRefMessageFromBinary(bytes)) }, + ShardRegionProxyTerminatedManifest -> { bytes => ShardRegionProxyTerminated(actorRefMessageFromBinary(bytes)) }, + ShardHomeAllocatedManifest -> shardHomeAllocatedFromBinary, + ShardHomeDeallocatedManifest -> { bytes => ShardHomeDeallocated(shardIdMessageFromBinary(bytes)) }, - RegisterManifest → { bytes ⇒ Register(actorRefMessageFromBinary(bytes)) }, - RegisterProxyManifest → { bytes ⇒ RegisterProxy(actorRefMessageFromBinary(bytes)) }, - RegisterAckManifest → { bytes ⇒ RegisterAck(actorRefMessageFromBinary(bytes)) }, - GetShardHomeManifest → { bytes ⇒ GetShardHome(shardIdMessageFromBinary(bytes)) }, - ShardHomeManifest → shardHomeFromBinary, - HostShardManifest → { bytes ⇒ HostShard(shardIdMessageFromBinary(bytes)) }, - ShardStartedManifest → { bytes ⇒ ShardStarted(shardIdMessageFromBinary(bytes)) }, - BeginHandOffManifest → { bytes ⇒ BeginHandOff(shardIdMessageFromBinary(bytes)) }, - BeginHandOffAckManifest → { bytes ⇒ BeginHandOffAck(shardIdMessageFromBinary(bytes)) }, - HandOffManifest → { bytes ⇒ HandOff(shardIdMessageFromBinary(bytes)) }, - ShardStoppedManifest → { bytes ⇒ ShardStopped(shardIdMessageFromBinary(bytes)) }, - GracefulShutdownReqManifest → { bytes ⇒ GracefulShutdownReq(actorRefMessageFromBinary(bytes)) }, + RegisterManifest -> { bytes => Register(actorRefMessageFromBinary(bytes)) }, + RegisterProxyManifest -> { bytes => RegisterProxy(actorRefMessageFromBinary(bytes)) }, + RegisterAckManifest -> { bytes => RegisterAck(actorRefMessageFromBinary(bytes)) }, + GetShardHomeManifest -> { bytes => GetShardHome(shardIdMessageFromBinary(bytes)) }, + ShardHomeManifest -> shardHomeFromBinary, + HostShardManifest -> { bytes => HostShard(shardIdMessageFromBinary(bytes)) }, + ShardStartedManifest -> { bytes => ShardStarted(shardIdMessageFromBinary(bytes)) }, + BeginHandOffManifest -> { bytes => BeginHandOff(shardIdMessageFromBinary(bytes)) }, + BeginHandOffAckManifest -> { bytes => BeginHandOffAck(shardIdMessageFromBinary(bytes)) }, + HandOffManifest -> { bytes => HandOff(shardIdMessageFromBinary(bytes)) }, + ShardStoppedManifest -> { bytes => ShardStopped(shardIdMessageFromBinary(bytes)) }, + GracefulShutdownReqManifest -> { bytes => GracefulShutdownReq(actorRefMessageFromBinary(bytes)) }, - GetShardStatsManifest → { bytes ⇒ GetShardStats }, - ShardStatsManifest → { bytes ⇒ shardStatsFromBinary(bytes) }, - GetShardRegionStatsManifest → { bytes ⇒ GetShardRegionStats }, - ShardRegionStatsManifest → { bytes ⇒ shardRegionStatsFromBinary(bytes) }, + GetShardStatsManifest -> { bytes => GetShardStats }, + ShardStatsManifest -> { bytes => shardStatsFromBinary(bytes) }, + GetShardRegionStatsManifest -> { bytes => GetShardRegionStats }, + ShardRegionStatsManifest -> { bytes => shardRegionStatsFromBinary(bytes) }, - StartEntityManifest → { startEntityFromBinary(_) }, - StartEntityAckManifest → { startEntityAckFromBinary(_) } + StartEntityManifest -> { startEntityFromBinary(_) }, + StartEntityAckManifest -> { startEntityAckFromBinary(_) } ) override def manifest(obj: AnyRef): String = obj match { - case _: EntityState ⇒ EntityStateManifest - case _: EntityStarted ⇒ EntityStartedManifest - case _: EntityStopped ⇒ EntityStoppedManifest + case _: EntityState => EntityStateManifest + case _: EntityStarted => EntityStartedManifest + case _: EntityStopped => EntityStoppedManifest - case _: State ⇒ CoordinatorStateManifest - case _: ShardRegionRegistered ⇒ ShardRegionRegisteredManifest - case _: ShardRegionProxyRegistered ⇒ ShardRegionProxyRegisteredManifest - case _: ShardRegionTerminated ⇒ ShardRegionTerminatedManifest - case _: ShardRegionProxyTerminated ⇒ ShardRegionProxyTerminatedManifest - case _: ShardHomeAllocated ⇒ ShardHomeAllocatedManifest - case _: ShardHomeDeallocated ⇒ ShardHomeDeallocatedManifest + case _: State => CoordinatorStateManifest + case _: ShardRegionRegistered => ShardRegionRegisteredManifest + case _: ShardRegionProxyRegistered => ShardRegionProxyRegisteredManifest + case _: ShardRegionTerminated => ShardRegionTerminatedManifest + case _: ShardRegionProxyTerminated => ShardRegionProxyTerminatedManifest + case _: ShardHomeAllocated => ShardHomeAllocatedManifest + case _: ShardHomeDeallocated => ShardHomeDeallocatedManifest - case _: Register ⇒ RegisterManifest - case _: RegisterProxy ⇒ RegisterProxyManifest - case _: RegisterAck ⇒ RegisterAckManifest - case _: GetShardHome ⇒ GetShardHomeManifest - case _: ShardHome ⇒ ShardHomeManifest - case _: HostShard ⇒ HostShardManifest - case _: ShardStarted ⇒ ShardStartedManifest - case _: BeginHandOff ⇒ BeginHandOffManifest - case _: BeginHandOffAck ⇒ BeginHandOffAckManifest - case _: HandOff ⇒ HandOffManifest - case _: ShardStopped ⇒ ShardStoppedManifest - case _: GracefulShutdownReq ⇒ GracefulShutdownReqManifest + case _: Register => RegisterManifest + case _: RegisterProxy => RegisterProxyManifest + case _: RegisterAck => RegisterAckManifest + case _: GetShardHome => GetShardHomeManifest + case _: ShardHome => ShardHomeManifest + case _: HostShard => HostShardManifest + case _: ShardStarted => ShardStartedManifest + case _: BeginHandOff => BeginHandOffManifest + case _: BeginHandOffAck => BeginHandOffAckManifest + case _: HandOff => HandOffManifest + case _: ShardStopped => ShardStoppedManifest + case _: GracefulShutdownReq => GracefulShutdownReqManifest - case _: StartEntity ⇒ StartEntityManifest - case _: StartEntityAck ⇒ StartEntityAckManifest + case _: StartEntity => StartEntityManifest + case _: StartEntityAck => StartEntityAckManifest - case GetShardStats ⇒ GetShardStatsManifest - case _: ShardStats ⇒ ShardStatsManifest - case GetShardRegionStats ⇒ GetShardRegionStatsManifest - case _: ShardRegionStats ⇒ ShardRegionStatsManifest - case _ ⇒ + case GetShardStats => GetShardStatsManifest + case _: ShardStats => ShardStatsManifest + case GetShardRegionStats => GetShardRegionStatsManifest + case _: ShardRegionStats => ShardRegionStatsManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: State ⇒ compress(coordinatorStateToProto(m)) - case ShardRegionRegistered(ref) ⇒ actorRefMessageToProto(ref).toByteArray - case ShardRegionProxyRegistered(ref) ⇒ actorRefMessageToProto(ref).toByteArray - case ShardRegionTerminated(ref) ⇒ actorRefMessageToProto(ref).toByteArray - case ShardRegionProxyTerminated(ref) ⇒ actorRefMessageToProto(ref).toByteArray - case m: ShardHomeAllocated ⇒ shardHomeAllocatedToProto(m).toByteArray - case ShardHomeDeallocated(shardId) ⇒ shardIdMessageToProto(shardId).toByteArray + case m: State => compress(coordinatorStateToProto(m)) + case ShardRegionRegistered(ref) => actorRefMessageToProto(ref).toByteArray + case ShardRegionProxyRegistered(ref) => actorRefMessageToProto(ref).toByteArray + case ShardRegionTerminated(ref) => actorRefMessageToProto(ref).toByteArray + case ShardRegionProxyTerminated(ref) => actorRefMessageToProto(ref).toByteArray + case m: ShardHomeAllocated => shardHomeAllocatedToProto(m).toByteArray + case ShardHomeDeallocated(shardId) => shardIdMessageToProto(shardId).toByteArray - case Register(ref) ⇒ actorRefMessageToProto(ref).toByteArray - case RegisterProxy(ref) ⇒ actorRefMessageToProto(ref).toByteArray - case RegisterAck(ref) ⇒ actorRefMessageToProto(ref).toByteArray - case GetShardHome(shardId) ⇒ shardIdMessageToProto(shardId).toByteArray - case m: ShardHome ⇒ shardHomeToProto(m).toByteArray - case HostShard(shardId) ⇒ shardIdMessageToProto(shardId).toByteArray - case ShardStarted(shardId) ⇒ shardIdMessageToProto(shardId).toByteArray - case BeginHandOff(shardId) ⇒ shardIdMessageToProto(shardId).toByteArray - case BeginHandOffAck(shardId) ⇒ shardIdMessageToProto(shardId).toByteArray - case HandOff(shardId) ⇒ shardIdMessageToProto(shardId).toByteArray - case ShardStopped(shardId) ⇒ shardIdMessageToProto(shardId).toByteArray - case GracefulShutdownReq(ref) ⇒ + case Register(ref) => actorRefMessageToProto(ref).toByteArray + case RegisterProxy(ref) => actorRefMessageToProto(ref).toByteArray + case RegisterAck(ref) => actorRefMessageToProto(ref).toByteArray + case GetShardHome(shardId) => shardIdMessageToProto(shardId).toByteArray + case m: ShardHome => shardHomeToProto(m).toByteArray + case HostShard(shardId) => shardIdMessageToProto(shardId).toByteArray + case ShardStarted(shardId) => shardIdMessageToProto(shardId).toByteArray + case BeginHandOff(shardId) => shardIdMessageToProto(shardId).toByteArray + case BeginHandOffAck(shardId) => shardIdMessageToProto(shardId).toByteArray + case HandOff(shardId) => shardIdMessageToProto(shardId).toByteArray + case ShardStopped(shardId) => shardIdMessageToProto(shardId).toByteArray + case GracefulShutdownReq(ref) => actorRefMessageToProto(ref).toByteArray - case m: EntityState ⇒ entityStateToProto(m).toByteArray - case m: EntityStarted ⇒ entityStartedToProto(m).toByteArray - case m: EntityStopped ⇒ entityStoppedToProto(m).toByteArray + case m: EntityState => entityStateToProto(m).toByteArray + case m: EntityStarted => entityStartedToProto(m).toByteArray + case m: EntityStopped => entityStoppedToProto(m).toByteArray - case s: StartEntity ⇒ startEntityToByteArray(s) - case s: StartEntityAck ⇒ startEntityAckToByteArray(s) + case s: StartEntity => startEntityToByteArray(s) + case s: StartEntityAck => startEntityAckToByteArray(s) - case GetShardStats ⇒ Array.emptyByteArray - case m: ShardStats ⇒ shardStatsToProto(m).toByteArray - case GetShardRegionStats ⇒ Array.emptyByteArray - case m: ShardRegionStats ⇒ shardRegionStatsToProto(m).toByteArray + case GetShardStats => Array.emptyByteArray + case m: ShardStats => shardStatsToProto(m).toByteArray + case GetShardRegionStats => Array.emptyByteArray + case m: ShardRegionStats => shardRegionStatsToProto(m).toByteArray - case _ ⇒ + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = fromBinaryMap.get(manifest) match { - case Some(f) ⇒ f(bytes) - case None ⇒ throw new NotSerializableException( + case Some(f) => f(bytes) + case None => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } private def coordinatorStateToProto(state: State): sm.CoordinatorState = { val regions = state.regions.map { - case (regionRef, _) ⇒ Serialization.serializedActorPath(regionRef) + case (regionRef, _) => Serialization.serializedActorPath(regionRef) }.toVector.asJava val builder = sm.CoordinatorState.newBuilder() state.shards.foreach { - case (shardId, regionRef) ⇒ + case (shardId, regionRef) => val b = sm.CoordinatorState.ShardEntry.newBuilder() .setShardId(shardId) .setRegionRef(Serialization.serializedActorPath(regionRef)) builder.addShards(b) } state.regions.foreach { - case (regionRef, _) ⇒ builder.addRegions(Serialization.serializedActorPath(regionRef)) + case (regionRef, _) => builder.addRegions(Serialization.serializedActorPath(regionRef)) } - state.regionProxies.foreach { ref ⇒ builder.addRegionProxies(Serialization.serializedActorPath(ref)) } + state.regionProxies.foreach { ref => builder.addRegionProxies(Serialization.serializedActorPath(ref)) } state.unallocatedShards.foreach { builder.addUnallocatedShards } builder.build() @@ -215,14 +215,14 @@ private[akka] class ClusterShardingMessageSerializer(val system: ExtendedActorSy private def coordinatorStateFromProto(state: sm.CoordinatorState): State = { val shards: Map[String, ActorRef] = - state.getShardsList.asScala.toVector.iterator.map { entry ⇒ - entry.getShardId → resolveActorRef(entry.getRegionRef) + state.getShardsList.asScala.toVector.iterator.map { entry => + entry.getShardId -> resolveActorRef(entry.getRegionRef) }.toMap val regionsZero: Map[ActorRef, Vector[String]] = - state.getRegionsList.asScala.toVector.iterator.map(resolveActorRef(_) → Vector.empty[String]).toMap + state.getRegionsList.asScala.toVector.iterator.map(resolveActorRef(_) -> Vector.empty[String]).toMap val regions: Map[ActorRef, Vector[String]] = - shards.foldLeft(regionsZero) { case (acc, (shardId, regionRef)) ⇒ acc.updated(regionRef, acc(regionRef) :+ shardId) } + shards.foldLeft(regionsZero) { case (acc, (shardId, regionRef)) => acc.updated(regionRef, acc(regionRef) :+ shardId) } val proxies: Set[ActorRef] = state.getRegionProxiesList.asScala.iterator.map { resolveActorRef }.to(immutable.Set) val unallocatedShards: Set[String] = state.getUnallocatedShardsList.asScala.toSet @@ -292,7 +292,7 @@ private[akka] class ClusterShardingMessageSerializer(val system: ExtendedActorSy private def shardRegionStatsToProto(evt: ShardRegionStats): sm.ShardRegionStats = { val b = sm.ShardRegionStats.newBuilder() evt.stats.foreach { - case (sid, no) ⇒ + case (sid, no) => b.addStats(sm.MapFieldEntry.newBuilder().setKey(sid).setValue(no).build()) } b.build() @@ -300,7 +300,7 @@ private[akka] class ClusterShardingMessageSerializer(val system: ExtendedActorSy private def shardRegionStatsFromBinary(bytes: Array[Byte]): ShardRegionStats = { val parsed = sm.ShardRegionStats.parseFrom(bytes) - val stats: Map[String, Int] = parsed.getStatsList.asScala.iterator.map(e ⇒ e.getKey -> e.getValue).toMap + val stats: Map[String, Int] = parsed.getStatsList.asScala.iterator.map(e => e.getKey -> e.getValue).toMap ShardRegionStats(stats) } @@ -345,8 +345,8 @@ private[akka] class ClusterShardingMessageSerializer(val system: ExtendedActorSy val buffer = new Array[Byte](BufferSize) @tailrec def readChunk(): Unit = in.read(buffer) match { - case -1 ⇒ () - case n ⇒ + case -1 => () + case n => out.write(buffer, 0, n) readChunk() } diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingCustomShardAllocationSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingCustomShardAllocationSpec.scala index 9681d42412..b82d6674ce 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingCustomShardAllocationSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingCustomShardAllocationSpec.scala @@ -26,16 +26,16 @@ import akka.pattern.ask object ClusterShardingCustomShardAllocationSpec { class Entity extends Actor { def receive = { - case id: Int ⇒ sender() ! id + case id: Int => sender() ! id } } val extractEntityId: ShardRegion.ExtractEntityId = { - case id: Int ⇒ (id.toString, id) + case id: Int => (id.toString, id) } val extractShardId: ShardRegion.ExtractShardId = { - case id: Int ⇒ id.toString + case id: Int => id.toString } case object AllocateReq @@ -49,15 +49,15 @@ object ClusterShardingCustomShardAllocationSpec { var useRegion: Option[ActorRef] = None var rebalance = Set.empty[String] def receive = { - case UseRegion(region) ⇒ + case UseRegion(region) => useRegion = Some(region) sender() ! UseRegionAck - case AllocateReq ⇒ + case AllocateReq => useRegion.foreach { sender() ! _ } - case RebalanceShards(shards) ⇒ + case RebalanceShards(shards) => rebalance = shards sender() ! RebalanceShardsAck - case RebalanceReq ⇒ + case RebalanceReq => sender() ! rebalance rebalance = Set.empty } diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingFailureSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingFailureSpec.scala index 1c370798d4..6109790887 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingFailureSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingFailureSpec.scala @@ -33,19 +33,19 @@ object ClusterShardingFailureSpec { var n = 0 def receive = { - case Get(id) ⇒ sender() ! Value(id, n) - case Add(_, i) ⇒ n += i + case Get(id) => sender() ! Value(id, n) + case Add(_, i) => n += i } } val extractEntityId: ShardRegion.ExtractEntityId = { - case m @ Get(id) ⇒ (id, m) - case m @ Add(id, _) ⇒ (id, m) + case m @ Get(id) => (id, m) + case m @ Add(id, _) => (id, m) } val extractShardId: ShardRegion.ExtractShardId = { - case Get(id) ⇒ id.charAt(0).toString - case Add(id, _) ⇒ id.charAt(0).toString + case Get(id) => id.charAt(0).toString + case Add(id, _) => id.charAt(0).toString } } @@ -109,12 +109,12 @@ abstract class ClusterShardingFailureSpec(config: ClusterShardingFailureSpecConf "akka.cluster.sharding.distributed-data.durable.lmdb.dir")).getParentFile) override protected def atStartup(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) enterBarrier("startup") } override protected def afterTermination(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) } val cluster = Cluster(system) diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGetStateSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGetStateSpec.scala index 930f127c7c..79e3786c16 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGetStateSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGetStateSpec.scala @@ -22,19 +22,19 @@ object ClusterShardingGetStateSpec { class ShardedActor extends Actor with ActorLogging { log.info(self.path.toString) def receive = { - case Stop ⇒ context.stop(self) - case _: Ping ⇒ sender() ! Pong + case Stop => context.stop(self) + case _: Ping => sender() ! Pong } } val extractEntityId: ShardRegion.ExtractEntityId = { - case msg @ Ping(id) ⇒ (id.toString, msg) + case msg @ Ping(id) => (id.toString, msg) } val numberOfShards = 2 val extractShardId: ShardRegion.ExtractShardId = { - case Ping(id) ⇒ (id % numberOfShards).toString + case Ping(id) => (id % numberOfShards).toString } val shardTypeName = "Ping" @@ -144,9 +144,9 @@ abstract class ClusterShardingGetStateSpec extends MultiNodeSpec(ClusterSharding awaitAssert { val pingProbe = TestProbe() // trigger starting of 4 entities - (1 to 4).foreach(n ⇒ region.tell(Ping(n), pingProbe.ref)) + (1 to 4).foreach(n => region.tell(Ping(n), pingProbe.ref)) pingProbe.receiveWhile(messages = 4) { - case Pong ⇒ () + case Pong => () } } } @@ -164,18 +164,18 @@ abstract class ClusterShardingGetStateSpec extends MultiNodeSpec(ClusterSharding region.tell(ShardRegion.GetCurrentRegions, probe.ref) val regions = probe.expectMsgType[ShardRegion.CurrentRegions].regions regions.size === 2 - regions.foreach { region ⇒ + regions.foreach { region => val path = RootActorPath(region) / "system" / "sharding" / shardTypeName system.actorSelection(path).tell(ShardRegion.GetShardRegionState, probe.ref) } val states = probe.receiveWhile(messages = regions.size) { - case msg: ShardRegion.CurrentShardRegionState ⇒ msg + case msg: ShardRegion.CurrentShardRegionState => msg } val allEntityIds = for { - state ← states - shard ← state.shards - entityId ← shard.entityIds + state <- states + shard <- state.shards + entityId <- shard.entityIds } yield entityId allEntityIds.toSet === Set("1", "2", "3", "4") diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGetStatsSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGetStatsSpec.scala index adebdb48d9..4136a77ee5 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGetStatsSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGetStatsSpec.scala @@ -21,19 +21,19 @@ object ClusterShardingGetStatsSpec { class ShardedActor extends Actor with ActorLogging { log.info(s"entity started {}", self.path) def receive = { - case Stop ⇒ context.stop(self) - case _: Ping ⇒ sender() ! Pong + case Stop => context.stop(self) + case _: Ping => sender() ! Pong } } val extractEntityId: ShardRegion.ExtractEntityId = { - case msg @ Ping(id) ⇒ (id.toString, msg) + case msg @ Ping(id) => (id.toString, msg) } val numberOfShards = 3 val extractShardId: ShardRegion.ExtractShardId = { - case Ping(id) ⇒ (id % numberOfShards).toString + case Ping(id) => (id % numberOfShards).toString } val shardTypeName = "Ping" @@ -154,9 +154,9 @@ abstract class ClusterShardingGetStatsSpec extends MultiNodeSpec(ClusterSharding val pingProbe = TestProbe() // trigger starting of 2 entities on first and second node // but leave third node without entities - List(1, 2, 4, 6).foreach(n ⇒ region.tell(Ping(n), pingProbe.ref)) + List(1, 2, 4, 6).foreach(n => region.tell(Ping(n), pingProbe.ref)) pingProbe.receiveWhile(messages = 4) { - case Pong ⇒ () + case Pong => () } } } @@ -201,9 +201,9 @@ abstract class ClusterShardingGetStatsSpec extends MultiNodeSpec(ClusterSharding awaitAssert { val pingProbe = TestProbe() // make sure we have the 4 entities still alive across the fewer nodes - List(1, 2, 4, 6).foreach(n ⇒ region.tell(Ping(n), pingProbe.ref)) + List(1, 2, 4, 6).foreach(n => region.tell(Ping(n), pingProbe.ref)) pingProbe.receiveWhile(messages = 4) { - case Pong ⇒ () + case Pong => () } } } diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGracefulShutdownSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGracefulShutdownSpec.scala index 1f5a2d698f..f1c1335fff 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGracefulShutdownSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingGracefulShutdownSpec.scala @@ -25,18 +25,18 @@ object ClusterShardingGracefulShutdownSpec { class Entity extends Actor { def receive = { - case id: Int ⇒ sender() ! id - case StopEntity ⇒ + case id: Int => sender() ! id + case StopEntity => context.stop(self) } } val extractEntityId: ShardRegion.ExtractEntityId = { - case id: Int ⇒ (id.toString, id) + case id: Int => (id.toString, id) } - val extractShardId: ShardRegion.ExtractShardId = msg ⇒ msg match { - case id: Int ⇒ id.toString + val extractShardId: ShardRegion.ExtractShardId = msg => msg match { + case id: Int => id.toString } } @@ -89,12 +89,12 @@ abstract class ClusterShardingGracefulShutdownSpec(config: ClusterShardingGracef "akka.cluster.sharding.distributed-data.durable.lmdb.dir")).getParentFile) override protected def atStartup(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) enterBarrier("startup") } override protected def afterTermination(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) } def join(from: RoleName, to: RoleName): Unit = { @@ -148,7 +148,7 @@ abstract class ClusterShardingGracefulShutdownSpec(config: ClusterShardingGracef awaitAssert { val p = TestProbe() - val regionAddresses = (1 to 100).map { n ⇒ + val regionAddresses = (1 to 100).map { n => region.tell(n, p.ref) p.expectMsg(1.second, n) p.lastSender.path.address @@ -166,7 +166,7 @@ abstract class ClusterShardingGracefulShutdownSpec(config: ClusterShardingGracef runOn(first) { awaitAssert { val p = TestProbe() - for (n ← 1 to 200) { + for (n <- 1 to 200) { region.tell(n, p.ref) p.expectMsg(1.second, n) p.lastSender.path should be(region.path / n.toString / n.toString) diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingIncorrectSetupSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingIncorrectSetupSpec.scala index e3c6ed8490..3b94c9a2dd 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingIncorrectSetupSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingIncorrectSetupSpec.scala @@ -29,11 +29,11 @@ class ClusterShardingIncorrectSetupMultiJvmNode2 extends ClusterShardingIncorrec object ClusterShardingIncorrectSetupSpec { val extractEntityId: ShardRegion.ExtractEntityId = { - case id: Int ⇒ (id.toString, id) + case id: Int => (id.toString, id) } val extractShardId: ShardRegion.ExtractShardId = { - case id: Int ⇒ id.toString + case id: Int => id.toString } } diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingLeavingSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingLeavingSpec.scala index 6390061e35..3363fdf36f 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingLeavingSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingLeavingSpec.scala @@ -29,7 +29,7 @@ object ClusterShardingLeavingSpec { class Entity extends Actor { def receive = { - case Ping(_) ⇒ sender() ! self + case Ping(_) => sender() ! self } } @@ -39,17 +39,17 @@ object ClusterShardingLeavingSpec { class ShardLocations extends Actor { var locations: Locations = _ def receive = { - case GetLocations ⇒ sender() ! locations - case l: Locations ⇒ locations = l + case GetLocations => sender() ! locations + case l: Locations => locations = l } } val extractEntityId: ShardRegion.ExtractEntityId = { - case m @ Ping(id) ⇒ (id, m) + case m @ Ping(id) => (id, m) } val extractShardId: ShardRegion.ExtractShardId = { - case Ping(id: String) ⇒ id.charAt(0).toString + case Ping(id: String) => id.charAt(0).toString } } @@ -108,12 +108,12 @@ abstract class ClusterShardingLeavingSpec(config: ClusterShardingLeavingSpecConf "akka.cluster.sharding.distributed-data.durable.lmdb.dir")).getParentFile) override protected def atStartup(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) enterBarrier("startup") } override protected def afterTermination(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) } val cluster = Cluster(system) @@ -123,7 +123,7 @@ abstract class ClusterShardingLeavingSpec(config: ClusterShardingLeavingSpecConf cluster join node(to).address startSharding() within(15.seconds) { - awaitAssert(cluster.state.members.exists { m ⇒ + awaitAssert(cluster.state.members.exists { m => m.uniqueAddress == cluster.selfUniqueAddress && m.status == MemberStatus.Up } should be(true)) } @@ -175,10 +175,10 @@ abstract class ClusterShardingLeavingSpec(config: ClusterShardingLeavingSpecConf "initialize shards" in { runOn(first) { val shardLocations = system.actorOf(Props[ShardLocations], "shardLocations") - val locations = (for (n ← 1 to 10) yield { + val locations = (for (n <- 1 to 10) yield { val id = n.toString region ! Ping(id) - id → expectMsgType[ActorRef] + id -> expectMsgType[ActorRef] }).toMap shardLocations ! Locations(locations) } @@ -205,7 +205,7 @@ abstract class ClusterShardingLeavingSpec(config: ClusterShardingLeavingSpecConf awaitAssert { val probe = TestProbe() originalLocations.foreach { - case (id, ref) ⇒ + case (id, ref) => region.tell(Ping(id), probe.ref) if (ref.path.address == firstAddress) probe.expectMsgType[ActorRef](1.second) should not be (ref) diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingMinMembersSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingMinMembersSpec.scala index 627a170747..5ef7953fa3 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingMinMembersSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingMinMembersSpec.scala @@ -25,11 +25,11 @@ object ClusterShardingMinMembersSpec { case object StopEntity val extractEntityId: ShardRegion.ExtractEntityId = { - case id: Int ⇒ (id.toString, id) + case id: Int => (id.toString, id) } - val extractShardId: ShardRegion.ExtractShardId = msg ⇒ msg match { - case id: Int ⇒ id.toString + val extractShardId: ShardRegion.ExtractShardId = msg => msg match { + case id: Int => id.toString } } @@ -87,12 +87,12 @@ abstract class ClusterShardingMinMembersSpec(config: ClusterShardingMinMembersSp "akka.cluster.sharding.distributed-data.durable.lmdb.dir")).getParentFile) override protected def atStartup(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) enterBarrier("startup") } override protected def afterTermination(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) } def join(from: RoleName, to: RoleName): Unit = { diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingRememberEntitiesNewExtractorSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingRememberEntitiesNewExtractorSpec.scala index 4c2575ea7e..d6dffd9dfb 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingRememberEntitiesNewExtractorSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingRememberEntitiesNewExtractorSpec.scala @@ -29,25 +29,25 @@ object ClusterShardingRememberEntitiesNewExtractorSpec { probe.foreach(_ ! Started(self)) def receive = { - case m ⇒ sender() ! m + case m => sender() ! m } } val shardCount = 5 val extractEntityId: ShardRegion.ExtractEntityId = { - case id: Int ⇒ (id.toString, id) + case id: Int => (id.toString, id) } val extractShardId1: ShardRegion.ExtractShardId = { - case id: Int ⇒ (id % shardCount).toString - case ShardRegion.StartEntity(id) ⇒ extractShardId1(id.toInt) + case id: Int => (id % shardCount).toString + case ShardRegion.StartEntity(id) => extractShardId1(id.toInt) } val extractShardId2: ShardRegion.ExtractShardId = { // always bump it one shard id - case id: Int ⇒ ((id + 1) % shardCount).toString - case ShardRegion.StartEntity(id) ⇒ extractShardId2(id.toInt) + case id: Int => ((id + 1) % shardCount).toString + case ShardRegion.StartEntity(id) => extractShardId2(id.toInt) } } @@ -134,12 +134,12 @@ abstract class ClusterShardingRememberEntitiesNewExtractorSpec(config: ClusterSh "akka.cluster.sharding.distributed-data.durable.lmdb.dir")).getParentFile) override protected def atStartup(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) enterBarrier("startup") } override protected def afterTermination(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) } def join(from: RoleName, to: RoleName): Unit = { @@ -213,7 +213,7 @@ abstract class ClusterShardingRememberEntitiesNewExtractorSpec(config: ClusterSh runOn(second, third) { // one entity for each shard id - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => region() ! n expectMsg(n) } @@ -277,8 +277,8 @@ abstract class ClusterShardingRememberEntitiesNewExtractorSpec(config: ClusterSh } for { - shardState ← stats.shards - entityId ← shardState.entityIds + shardState <- stats.shards + entityId <- shardState.entityIds } { val calculatedShardId = extractShardId2(entityId.toInt) calculatedShardId should ===(shardState.shardId) diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingRememberEntitiesSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingRememberEntitiesSpec.scala index 92903f0770..a5d3fc01b9 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingRememberEntitiesSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingRememberEntitiesSpec.scala @@ -29,17 +29,17 @@ object ClusterShardingRememberEntitiesSpec { probe ! Started(self) def receive = { - case m ⇒ sender() ! m + case m => sender() ! m } } val extractEntityId: ShardRegion.ExtractEntityId = { - case id: Int ⇒ (id.toString, id) + case id: Int => (id.toString, id) } - val extractShardId: ShardRegion.ExtractShardId = msg ⇒ msg match { - case id: Int ⇒ id.toString - case ShardRegion.StartEntity(id) ⇒ id + val extractShardId: ShardRegion.ExtractShardId = msg => msg match { + case id: Int => id.toString + case ShardRegion.StartEntity(id) => id } } @@ -108,12 +108,12 @@ abstract class ClusterShardingRememberEntitiesSpec(config: ClusterShardingRememb "akka.cluster.sharding.distributed-data.durable.lmdb.dir")).getParentFile) override protected def atStartup(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) enterBarrier("startup") } override protected def afterTermination(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) } def join(from: RoleName, to: RoleName): Unit = { diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingSingleShardPerEntitySpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingSingleShardPerEntitySpec.scala index e2e10f2ff8..cf1871611e 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingSingleShardPerEntitySpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingSingleShardPerEntitySpec.scala @@ -23,16 +23,16 @@ import com.typesafe.config.ConfigFactory object ClusterShardingSingleShardPerEntitySpec { class Entity extends Actor { def receive = { - case id: Int ⇒ sender() ! id + case id: Int => sender() ! id } } val extractEntityId: ShardRegion.ExtractEntityId = { - case id: Int ⇒ (id.toString, id) + case id: Int => (id.toString, id) } val extractShardId: ShardRegion.ExtractShardId = { - case id: Int ⇒ id.toString + case id: Int => id.toString } } diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingSpec.scala index 2c37aef12b..3ff8022d21 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/ClusterShardingSpec.scala @@ -64,30 +64,30 @@ object ClusterShardingSpec { count += event.delta override def receiveRecover: Receive = { - case evt: CounterChanged ⇒ updateState(evt) + case evt: CounterChanged => updateState(evt) } override def receiveCommand: Receive = { - case Increment ⇒ persist(CounterChanged(+1))(updateState) - case Decrement ⇒ persist(CounterChanged(-1))(updateState) - case Get(_) ⇒ sender() ! count - case ReceiveTimeout ⇒ context.parent ! Passivate(stopMessage = Stop) - case Stop ⇒ context.stop(self) + case Increment => persist(CounterChanged(+1))(updateState) + case Decrement => persist(CounterChanged(-1))(updateState) + case Get(_) => sender() ! count + case ReceiveTimeout => context.parent ! Passivate(stopMessage = Stop) + case Stop => context.stop(self) } } //#counter-actor val extractEntityId: ShardRegion.ExtractEntityId = { - case EntityEnvelope(id, payload) ⇒ (id.toString, payload) - case msg @ Get(id) ⇒ (id.toString, msg) + case EntityEnvelope(id, payload) => (id.toString, payload) + case msg @ Get(id) => (id.toString, msg) } val numberOfShards = 12 val extractShardId: ShardRegion.ExtractShardId = { - case EntityEnvelope(id, _) ⇒ (id % numberOfShards).toString - case Get(id) ⇒ (id % numberOfShards).toString - case ShardRegion.StartEntity(id) ⇒ (id.toLong % numberOfShards).toString + case EntityEnvelope(id, _) => (id % numberOfShards).toString + case Get(id) => (id % numberOfShards).toString + case ShardRegion.StartEntity(id) => (id.toLong % numberOfShards).toString } def qualifiedCounterProps(typeName: String): Props = @@ -104,14 +104,14 @@ object ClusterShardingSpec { val counter = context.actorOf(Props[Counter], "theCounter") override val supervisorStrategy = OneForOneStrategy() { - case _: IllegalArgumentException ⇒ SupervisorStrategy.Resume - case _: ActorInitializationException ⇒ SupervisorStrategy.Stop - case _: DeathPactException ⇒ SupervisorStrategy.Stop - case _: Exception ⇒ SupervisorStrategy.Restart + case _: IllegalArgumentException => SupervisorStrategy.Resume + case _: ActorInitializationException => SupervisorStrategy.Stop + case _: DeathPactException => SupervisorStrategy.Stop + case _: Exception => SupervisorStrategy.Restart } def receive = { - case msg ⇒ counter forward msg + case msg => counter forward msg } } //#supervisor @@ -179,16 +179,16 @@ object ClusterShardingDocCode { //#counter-extractor val extractEntityId: ShardRegion.ExtractEntityId = { - case EntityEnvelope(id, payload) ⇒ (id.toString, payload) - case msg @ Get(id) ⇒ (id.toString, msg) + case EntityEnvelope(id, payload) => (id.toString, payload) + case msg @ Get(id) => (id.toString, msg) } val numberOfShards = 100 val extractShardId: ShardRegion.ExtractShardId = { - case EntityEnvelope(id, _) ⇒ (id % numberOfShards).toString - case Get(id) ⇒ (id % numberOfShards).toString - case ShardRegion.StartEntity(id) ⇒ + case EntityEnvelope(id, _) => (id % numberOfShards).toString + case Get(id) => (id % numberOfShards).toString + case ShardRegion.StartEntity(id) => // StartEntity is used by remembering entities feature (id.toLong % numberOfShards).toString } @@ -197,9 +197,9 @@ object ClusterShardingDocCode { { //#extractShardId-StartEntity val extractShardId: ShardRegion.ExtractShardId = { - case EntityEnvelope(id, _) ⇒ (id % numberOfShards).toString - case Get(id) ⇒ (id % numberOfShards).toString - case ShardRegion.StartEntity(id) ⇒ + case EntityEnvelope(id, _) => (id % numberOfShards).toString + case Get(id) => (id % numberOfShards).toString + case ShardRegion.StartEntity(id) => // StartEntity is used by remembering entities feature (id.toLong % numberOfShards).toString } @@ -263,12 +263,12 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu "akka.cluster.sharding.distributed-data.durable.lmdb.dir")).getParentFile) override protected def atStartup(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) enterBarrier("startup") } override protected def afterTermination(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteQuietly(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) } def join(from: RoleName, to: RoleName): Unit = { @@ -301,7 +301,7 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu } List("counter", "rebalancingCounter", "RememberCounterEntities", "AnotherRememberCounter", - "RememberCounter", "RebalancingRememberCounter", "AutoMigrateRememberRegionTest").foreach { typeName ⇒ + "RememberCounter", "RebalancingRememberCounter", "AutoMigrateRememberRegionTest").foreach { typeName => val rebalanceEnabled = typeName.toLowerCase.startsWith("rebalancing") val rememberEnabled = typeName.toLowerCase.contains("remember") val singletonProps = BackoffSupervisor.props( @@ -332,7 +332,7 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu system.actorOf( ShardRegion.props( typeName = typeName, - entityProps = _ ⇒ qualifiedCounterProps(typeName), + entityProps = _ => qualifiedCounterProps(typeName), settings = settings, coordinatorPath = "/user/" + typeName + "Coordinator/singleton/coordinator", extractEntityId = extractEntityId, @@ -517,7 +517,7 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu join(third, first) runOn(third) { - for (_ ← 1 to 10) + for (_ <- 1 to 10) region ! EntityEnvelope(3, Increment) region ! Get(3) expectMsg(10) @@ -528,7 +528,7 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu join(fourth, first) runOn(fourth) { - for (_ ← 1 to 20) + for (_ <- 1 to 20) region ! EntityEnvelope(4, Increment) region ! Get(4) expectMsg(20) @@ -597,7 +597,7 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu "rebalance to nodes with less shards" in within(60 seconds) { runOn(fourth) { - for (n ← 1 to 10) { + for (n <- 1 to 10) { rebalancingRegion ! EntityEnvelope(n, Increment) rebalancingRegion ! Get(n) expectMsg(1) @@ -612,7 +612,7 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu val probe = TestProbe() within(3.seconds) { var count = 0 - for (n ← 1 to 10) { + for (n <- 1 to 10) { rebalancingRegion.tell(Get(n), probe.ref) probe.expectMsgType[Int] if (probe.lastSender.path == rebalancingRegion.path / (n % 12).toString / n.toString) @@ -674,7 +674,7 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu // sixth is a frontend node, i.e. proxy only runOn(sixth) { - for (n ← 1000 to 1010) { + for (n <- 1000 to 1010) { ClusterSharding(system).shardRegion("Counter") ! EntityEnvelope(n, Increment) ClusterSharding(system).shardRegion("Counter") ! Get(n) expectMsg(1) @@ -925,11 +925,11 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu "ensure rebalance restarts shards" in within(50.seconds) { runOn(fourth) { - for (i ← 2 to 12) { + for (i <- 2 to 12) { rebalancingPersistentRegion ! EntityEnvelope(i, Increment) } - for (i ← 2 to 12) { + for (i <- 2 to 12) { rebalancingPersistentRegion ! Get(i) expectMsg(1) } @@ -944,12 +944,12 @@ abstract class ClusterShardingSpec(config: ClusterShardingSpecConfig) extends Mu runOn(fifth) { awaitAssert { var count = 0 - for (n ← 2 to 12) { + for (n <- 2 to 12) { val entity = system.actorSelection(rebalancingPersistentRegion.path / (n % 12).toString / n.toString) entity ! Identify(n) receiveOne(3 seconds) match { - case ActorIdentity(id, Some(_)) if id == n ⇒ count = count + 1 - case ActorIdentity(id, None) ⇒ //Not on the fifth shard + case ActorIdentity(id, Some(_)) if id == n => count = count + 1 + case ActorIdentity(id, None) => //Not on the fifth shard } } count should be >= (2) diff --git a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/MultiDcClusterShardingSpec.scala b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/MultiDcClusterShardingSpec.scala index 1870d2bdd2..75e6f7c7fd 100644 --- a/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/MultiDcClusterShardingSpec.scala +++ b/akka-cluster-sharding/src/multi-jvm/scala/akka/cluster/sharding/MultiDcClusterShardingSpec.scala @@ -30,20 +30,20 @@ object MultiDcClusterShardingSpec { class Entity extends Actor { var count = 0 def receive = { - case Ping(_) ⇒ + case Ping(_) => count += 1 sender() ! self - case GetCount(_) ⇒ + case GetCount(_) => sender() ! count } } val extractEntityId: ShardRegion.ExtractEntityId = { - case m: EntityMsg ⇒ (m.id, m) + case m: EntityMsg => (m.id, m) } val extractShardId: ShardRegion.ExtractShardId = { - case m: EntityMsg ⇒ m.id.charAt(0).toString + case m: EntityMsg => m.id.charAt(0).toString } } @@ -91,7 +91,7 @@ abstract class MultiDcClusterShardingSpec extends MultiNodeSpec(MultiDcClusterSh startSharding() withClue(s"Failed waiting for ${cluster.selfUniqueAddress} to be up. Current state: ${cluster.state}" + cluster.state) { within(15.seconds) { - awaitAssert(cluster.state.members.exists { m ⇒ + awaitAssert(cluster.state.members.exists { m => m.uniqueAddress == cluster.selfUniqueAddress && m.status == MemberStatus.Up } should be(true)) } @@ -137,10 +137,10 @@ abstract class MultiDcClusterShardingSpec extends MultiNodeSpec(MultiDcClusterSh }, 10.seconds) runOn(first, second) { - assertCurrentRegions(Set(first, second).map(r ⇒ node(r).address)) + assertCurrentRegions(Set(first, second).map(r => node(r).address)) } runOn(third, fourth) { - assertCurrentRegions(Set(third, fourth).map(r ⇒ node(r).address)) + assertCurrentRegions(Set(third, fourth).map(r => node(r).address)) } enterBarrier("after-1") @@ -148,29 +148,29 @@ abstract class MultiDcClusterShardingSpec extends MultiNodeSpec(MultiDcClusterSh "initialize shards" in { runOn(first) { - val locations = (for (n ← 1 to 10) yield { + val locations = (for (n <- 1 to 10) yield { val id = n.toString region ! Ping(id) - id → expectMsgType[ActorRef] + id -> expectMsgType[ActorRef] }).toMap val firstAddress = node(first).address val secondAddress = node(second).address - val hosts = locations.values.map(ref ⇒ fillAddress(ref.path.address)).toSet + val hosts = locations.values.map(ref => fillAddress(ref.path.address)).toSet hosts should ===(Set(firstAddress, secondAddress)) } runOn(third) { - val locations = (for (n ← 1 to 10) yield { + val locations = (for (n <- 1 to 10) yield { val id = n.toString region ! Ping(id) val ref1 = expectMsgType[ActorRef] region ! Ping(id) val ref2 = expectMsgType[ActorRef] ref1 should ===(ref2) - id → ref1 + id -> ref1 }).toMap val thirdAddress = node(third).address val fourthAddress = node(fourth).address - val hosts = locations.values.map(ref ⇒ fillAddress(ref.path.address)).toSet + val hosts = locations.values.map(ref => fillAddress(ref.path.address)).toSet hosts should ===(Set(thirdAddress, fourthAddress)) } enterBarrier("after-2") diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ClusterShardingInternalsSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ClusterShardingInternalsSpec.scala index f263901410..c459ddc8ef 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ClusterShardingInternalsSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ClusterShardingInternalsSpec.scala @@ -19,7 +19,7 @@ object ClusterShardingInternalsSpec { case class HandOffStopMessage() extends NoSerializationVerificationNeeded class EmptyHandlerActor extends Actor { override def receive: Receive = { - case _ ⇒ + case _ => } override def postStop(): Unit = { diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ConcurrentStartupShardingSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ConcurrentStartupShardingSpec.scala index cb3c384ac6..c0c6125e53 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ConcurrentStartupShardingSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ConcurrentStartupShardingSpec.scala @@ -45,13 +45,13 @@ object ConcurrentStartupShardingSpec { override def preStart(): Unit = { val region = ClusterSharding(context.system).start(s"type-$n", Props.empty, ClusterShardingSettings(context.system), - { case msg ⇒ (msg.toString, msg) }, - _ ⇒ "1") + { case msg => (msg.toString, msg) }, + _ => "1") probe ! region } def receive = { - case _ ⇒ + case _ => } } } @@ -72,7 +72,7 @@ class ConcurrentStartupShardingSpec extends AkkaSpec(ConcurrentStartupShardingSp awaitAssert(Cluster(system).selfMember.status should ===(MemberStatus.Up)) val total = 20 - (1 to total).foreach { n ⇒ + (1 to total).foreach { n => system.actorOf(Starter.props(n, testActor)) } diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ConstantRateEntityRecoveryStrategySpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ConstantRateEntityRecoveryStrategySpec.scala index e60950ca0c..0c9863ab3e 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ConstantRateEntityRecoveryStrategySpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ConstantRateEntityRecoveryStrategySpec.scala @@ -19,10 +19,10 @@ class ConstantRateEntityRecoveryStrategySpec extends AkkaSpec { val entities = Set[EntityId]("1", "2", "3", "4", "5") val startTime = System.nanoTime() val resultWithTimes = strategy.recoverEntities(entities).map( - _.map(entityIds ⇒ entityIds → (System.nanoTime() - startTime).nanos)) + _.map(entityIds => entityIds -> (System.nanoTime() - startTime).nanos)) val result = Await.result(Future.sequence(resultWithTimes), 6.seconds) - .toVector.sortBy { case (_, duration) ⇒ duration } + .toVector.sortBy { case (_, duration) => duration } result.size should ===(3) val scheduledEntities = result.map(_._1) diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/CoordinatedShutdownShardingSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/CoordinatedShutdownShardingSpec.scala index 344de1f588..a2eb6d3b37 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/CoordinatedShutdownShardingSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/CoordinatedShutdownShardingSpec.scala @@ -28,11 +28,11 @@ object CoordinatedShutdownShardingSpec { """ val extractEntityId: ShardRegion.ExtractEntityId = { - case msg: Int ⇒ (msg.toString, msg) + case msg: Int => (msg.toString, msg) } val extractShardId: ShardRegion.ExtractShardId = { - case msg: Int ⇒ (msg % 10).toString + case msg: Int => (msg % 10).toString } } @@ -54,15 +54,15 @@ class CoordinatedShutdownShardingSpec extends AkkaSpec(CoordinatedShutdownShardi val probe2 = TestProbe()(sys2) val probe3 = TestProbe()(sys3) - CoordinatedShutdown(sys1).addTask(CoordinatedShutdown.PhaseBeforeServiceUnbind, "unbind") { () ⇒ + CoordinatedShutdown(sys1).addTask(CoordinatedShutdown.PhaseBeforeServiceUnbind, "unbind") { () => probe1.ref ! "CS-unbind-1" Future.successful(Done) } - CoordinatedShutdown(sys2).addTask(CoordinatedShutdown.PhaseBeforeServiceUnbind, "unbind") { () ⇒ + CoordinatedShutdown(sys2).addTask(CoordinatedShutdown.PhaseBeforeServiceUnbind, "unbind") { () => probe2.ref ! "CS-unbind-2" Future.successful(Done) } - CoordinatedShutdown(sys3).addTask(CoordinatedShutdown.PhaseBeforeServiceUnbind, "unbind") { () ⇒ + CoordinatedShutdown(sys3).addTask(CoordinatedShutdown.PhaseBeforeServiceUnbind, "unbind") { () => probe3.ref ! "CS-unbind-3" Future.successful(Done) } diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/GetShardTypeNamesSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/GetShardTypeNamesSpec.scala index b9f0023c28..0c35711f0d 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/GetShardTypeNamesSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/GetShardTypeNamesSpec.scala @@ -19,11 +19,11 @@ object GetShardTypeNamesSpec { """ val extractEntityId: ShardRegion.ExtractEntityId = { - case msg: Int ⇒ (msg.toString, msg) + case msg: Int => (msg.toString, msg) } val extractShardId: ShardRegion.ExtractShardId = { - case msg: Int ⇒ (msg % 10).toString + case msg: Int => (msg % 10).toString } } diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/InactiveEntityPassivationSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/InactiveEntityPassivationSpec.scala index d553875e6e..530bdfdcb1 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/InactiveEntityPassivationSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/InactiveEntityPassivationSpec.scala @@ -32,20 +32,20 @@ object InactiveEntityPassivationSpec { def id = context.self.path.name def receive = { - case Passivate ⇒ + case Passivate => probe ! id + " passivating" context.stop(self) - case msg ⇒ probe ! GotIt(id, msg, System.nanoTime()) + case msg => probe ! GotIt(id, msg, System.nanoTime()) } } val extractEntityId: ShardRegion.ExtractEntityId = { - case msg: Int ⇒ (msg.toString, msg) + case msg: Int => (msg.toString, msg) } val extractShardId: ShardRegion.ExtractShardId = { - case msg: Int ⇒ (msg % 10).toString + case msg: Int => (msg % 10).toString } } diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/JoinConfigCompatCheckShardingSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/JoinConfigCompatCheckShardingSpec.scala index 64cda3aa9f..730df9b19e 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/JoinConfigCompatCheckShardingSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/JoinConfigCompatCheckShardingSpec.scala @@ -9,7 +9,7 @@ import akka.cluster.{ Cluster, ClusterReadView } import akka.testkit.{ AkkaSpec, LongRunningTest } import com.typesafe.config.{ Config, ConfigFactory } import scala.concurrent.duration._ -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } class JoinConfigCompatCheckShardingSpec extends AkkaSpec() { diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/LeastShardAllocationStrategySpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/LeastShardAllocationStrategySpec.scala index a96eca8bb9..5a83040310 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/LeastShardAllocationStrategySpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/LeastShardAllocationStrategySpec.scala @@ -16,7 +16,7 @@ class LeastShardAllocationStrategySpec extends AkkaSpec { val regionC = system.actorOf(Props.empty, "regionC") def createAllocations(aCount: Int, bCount: Int = 0, cCount: Int = 0): Map[ActorRef, Vector[String]] = { - val shards = (1 to (aCount + bCount + cCount)).map(n ⇒ ("00" + n.toString).takeRight(3)) + val shards = (1 to (aCount + bCount + cCount)).map(n => ("00" + n.toString).takeRight(3)) Map( regionA -> shards.take(aCount).toVector, regionB -> shards.slice(aCount, aCount + bCount).toVector, diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/PersistentShardSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/PersistentShardSpec.scala index bb3777e3a3..f915c26b71 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/PersistentShardSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/PersistentShardSpec.scala @@ -15,7 +15,7 @@ import org.scalatest.WordSpecLike object PersistentShardSpec { class EntityActor(id: String) extends Actor { override def receive: Receive = { - case _ ⇒ + case _ => } } @@ -33,12 +33,12 @@ class PersistentShardSpec extends AkkaSpec(PersistentShardSpec.config) with Word val props = Props(new PersistentShard( "cats", "shard-1", - id ⇒ Props(new EntityActor(id)), + id => Props(new EntityActor(id)), ClusterShardingSettings(system), { - case _ ⇒ ("entity-1", "msg") + case _ => ("entity-1", "msg") }, - _ ⇒ "shard-1", + _ => "shard-1", PoisonPill )) val persistentShard = system.actorOf(props) diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ProxyShardingSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ProxyShardingSpec.scala index 21e868e5ba..26b97bff5a 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ProxyShardingSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/ProxyShardingSpec.scala @@ -30,11 +30,11 @@ class ProxyShardingSpec extends AkkaSpec(ProxyShardingSpec.config) { } val idExtractor: ShardRegion.ExtractEntityId = { - case msg @ id ⇒ (id.toString, msg) + case msg @ id => (id.toString, msg) } val shardResolver: ShardRegion.ExtractShardId = { - case id: Int ⇒ id.toString + case id: Int => id.toString } val shardProxy: ActorRef = diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/RemoveInternalClusterShardingDataSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/RemoveInternalClusterShardingDataSpec.scala index 21fa2f61a3..3e6882ae63 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/RemoveInternalClusterShardingDataSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/RemoveInternalClusterShardingDataSpec.scala @@ -44,11 +44,11 @@ object RemoveInternalClusterShardingDataSpec { """ val extractEntityId: ShardRegion.ExtractEntityId = { - case msg: Int ⇒ (msg.toString, msg) + case msg: Int => (msg.toString, msg) } val extractShardId: ShardRegion.ExtractShardId = { - case msg: Int ⇒ (msg % 10).toString + case msg: Int => (msg % 10).toString } class HasSnapshots(override val persistenceId: String, replyTo: ActorRef) extends PersistentActor { @@ -56,17 +56,17 @@ object RemoveInternalClusterShardingDataSpec { var hasSnapshots = false override def receiveRecover: Receive = { - case SnapshotOffer(_, _) ⇒ + case SnapshotOffer(_, _) => hasSnapshots = true - case RecoveryCompleted ⇒ + case RecoveryCompleted => replyTo ! hasSnapshots context.stop(self) - case _ ⇒ + case _ => } override def receiveCommand: Receive = { - case _ ⇒ + case _ => } } @@ -77,15 +77,15 @@ object RemoveInternalClusterShardingDataSpec { override def recovery: Recovery = Recovery(fromSnapshot = SnapshotSelectionCriteria.None) override def receiveRecover: Receive = { - case event: ShardCoordinator.Internal.DomainEvent ⇒ + case event: ShardCoordinator.Internal.DomainEvent => hasEvents = true - case RecoveryCompleted ⇒ + case RecoveryCompleted => replyTo ! hasEvents context.stop(self) } override def receiveCommand: Receive = { - case _ ⇒ + case _ => } } @@ -97,14 +97,14 @@ class RemoveInternalClusterShardingDataSpec extends AkkaSpec(RemoveInternalClust val storageLocations = List( "akka.persistence.journal.leveldb.dir", - "akka.persistence.snapshot-store.local.dir").map(s ⇒ new File(system.settings.config.getString(s))) + "akka.persistence.snapshot-store.local.dir").map(s => new File(system.settings.config.getString(s))) override protected def atStartup(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteDirectory(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteDirectory(dir)) } override protected def afterTermination(): Unit = { - storageLocations.foreach(dir ⇒ if (dir.exists) FileUtils.deleteDirectory(dir)) + storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteDirectory(dir)) } // same persistenceId as is used by ShardCoordinator @@ -180,13 +180,13 @@ class RemoveInternalClusterShardingDataSpec extends AkkaSpec(RemoveInternalClust "setup sharding" in { Cluster(system).join(Cluster(system).selfAddress) val settings = ClusterShardingSettings(system) - typeNames.foreach { typeName ⇒ + typeNames.foreach { typeName => ClusterSharding(system).start(typeName, Props[EchoActor](), settings, extractEntityId, extractShardId) } } "remove all events and snapshots" in within(10.seconds) { - typeNames.foreach { typeName ⇒ + typeNames.foreach { typeName => val region = ClusterSharding(system).shardRegion(typeName) (1 to 10).foreach(region ! _) receiveN(10).toSet should be((1 to 10).toSet) @@ -202,7 +202,7 @@ class RemoveInternalClusterShardingDataSpec extends AkkaSpec(RemoveInternalClust terminateSystem = false, remove2dot3Data = true) Await.ready(result, remaining) - typeNames.foreach { typeName ⇒ + typeNames.foreach { typeName => hasSnapshots(typeName) should ===(false) hasEvents(typeName) should ===(false) } diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/SupervisionSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/SupervisionSpec.scala index 9f37e60281..23853552f2 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/SupervisionSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/SupervisionSpec.scala @@ -26,11 +26,11 @@ object SupervisionSpec { case object StopMessage val idExtractor: ShardRegion.ExtractEntityId = { - case Msg(id, msg) ⇒ (id.toString, msg) + case Msg(id, msg) => (id.toString, msg) } val shardResolver: ShardRegion.ExtractShardId = { - case Msg(id, msg) ⇒ (id % 2).toString + case Msg(id, msg) => (id % 2).toString } class PassivatingActor extends Actor with ActorLogging { @@ -44,15 +44,15 @@ object SupervisionSpec { } override def receive: Receive = { - case "passivate" ⇒ + case "passivate" => log.info("Passivating") context.parent ! Passivate(StopMessage) // simulate another message causing a stop before the region sends the stop message // e.g. a persistent actor having a persist failure while processing the next message context.stop(self) - case "hello" ⇒ + case "hello" => sender() ! Response(self) - case StopMessage ⇒ + case StopMessage => log.info("Received stop from region") context.parent ! PoisonPill } diff --git a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/protobuf/ClusterShardingMessageSerializerSpec.scala b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/protobuf/ClusterShardingMessageSerializerSpec.scala index 406c00eb2d..4ef42ca059 100644 --- a/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/protobuf/ClusterShardingMessageSerializerSpec.scala +++ b/akka-cluster-sharding/src/test/scala/akka/cluster/sharding/protobuf/ClusterShardingMessageSerializerSpec.scala @@ -31,8 +31,8 @@ class ClusterShardingMessageSerializerSpec extends AkkaSpec { "be able to serialize ShardCoordinator snapshot State" in { val state = State( - shards = Map("a" → region1, "b" → region2, "c" → region2), - regions = Map(region1 → Vector("a"), region2 → Vector("b", "c"), region3 → Vector.empty[String]), + shards = Map("a" -> region1, "b" -> region2, "c" -> region2), + regions = Map(region1 -> Vector("a"), region2 -> Vector("b", "c"), region3 -> Vector.empty[String]), regionProxies = Set(regionProxy1, regionProxy2), unallocatedShards = Set("d")) checkSerialization(state) diff --git a/akka-cluster-tools/src/main/scala/akka/cluster/client/ClusterClient.scala b/akka-cluster-tools/src/main/scala/akka/cluster/client/ClusterClient.scala index 63277d503f..22db792c08 100644 --- a/akka-cluster-tools/src/main/scala/akka/cluster/client/ClusterClient.scala +++ b/akka-cluster-tools/src/main/scala/akka/cluster/client/ClusterClient.scala @@ -63,8 +63,8 @@ object ClusterClientSettings { acceptableHeartbeatPause = config.getDuration("acceptable-heartbeat-pause", MILLISECONDS).millis, bufferSize = config.getInt("buffer-size"), reconnectTimeout = config.getString("reconnect-timeout") match { - case "off" ⇒ None - case _ ⇒ Some(config.getDuration("reconnect-timeout", MILLISECONDS).millis) + case "off" => None + case _ => Some(config.getDuration("reconnect-timeout", MILLISECONDS).millis) }) } @@ -367,19 +367,19 @@ final class ClusterClient(settings: ClusterClientSettings) extends Actor with Ac def receive = establishing orElse contactPointMessages def establishing: Actor.Receive = { - val connectTimerCancelable = settings.reconnectTimeout.map { timeout ⇒ + val connectTimerCancelable = settings.reconnectTimeout.map { timeout => context.system.scheduler.scheduleOnce(timeout, self, ReconnectTimeout) } { - case Contacts(contactPoints) ⇒ + case Contacts(contactPoints) => if (contactPoints.nonEmpty) { contactPaths = contactPoints.map(ActorPath.fromString).to(HashSet) contacts = contactPaths.map(context.actorSelection) contacts foreach { _ ! Identify(Array.emptyByteArray) } } publishContactPoints() - case ActorIdentity(_, Some(receptionist)) ⇒ + case ActorIdentity(_, Some(receptionist)) => log.info("Connected to [{}]", receptionist.path) scheduleRefreshContactsTick(refreshContactsInterval) sendBuffered(receptionist) @@ -387,49 +387,49 @@ final class ClusterClient(settings: ClusterClientSettings) extends Actor with Ac connectTimerCancelable.foreach(_.cancel()) failureDetector.heartbeat() self ! HeartbeatTick // will register us as active client of the selected receptionist - case ActorIdentity(_, None) ⇒ // ok, use another instead - case HeartbeatTick ⇒ + case ActorIdentity(_, None) => // ok, use another instead + case HeartbeatTick => failureDetector.heartbeat() - case RefreshContactsTick ⇒ sendGetContacts() - case Send(path, msg, localAffinity) ⇒ + case RefreshContactsTick => sendGetContacts() + case Send(path, msg, localAffinity) => buffer(DistributedPubSubMediator.Send(path, msg, localAffinity)) - case SendToAll(path, msg) ⇒ + case SendToAll(path, msg) => buffer(DistributedPubSubMediator.SendToAll(path, msg)) - case Publish(topic, msg) ⇒ + case Publish(topic, msg) => buffer(DistributedPubSubMediator.Publish(topic, msg)) - case ReconnectTimeout ⇒ + case ReconnectTimeout => log.warning("Receptionist reconnect not successful within {} stopping cluster client", settings.reconnectTimeout) context.stop(self) - case ReceptionistShutdown ⇒ // ok, haven't chosen a receptionist yet + case ReceptionistShutdown => // ok, haven't chosen a receptionist yet } } def active(receptionist: ActorRef): Actor.Receive = { - case Send(path, msg, localAffinity) ⇒ + case Send(path, msg, localAffinity) => receptionist forward DistributedPubSubMediator.Send(path, msg, localAffinity) - case SendToAll(path, msg) ⇒ + case SendToAll(path, msg) => receptionist forward DistributedPubSubMediator.SendToAll(path, msg) - case Publish(topic, msg) ⇒ + case Publish(topic, msg) => receptionist forward DistributedPubSubMediator.Publish(topic, msg) - case HeartbeatTick ⇒ + case HeartbeatTick => if (!failureDetector.isAvailable) { log.info("Lost contact with [{}], reestablishing connection", receptionist) reestablish() } else receptionist ! Heartbeat - case HeartbeatRsp ⇒ + case HeartbeatRsp => failureDetector.heartbeat() - case RefreshContactsTick ⇒ + case RefreshContactsTick => receptionist ! GetContacts - case Contacts(contactPoints) ⇒ + case Contacts(contactPoints) => // refresh of contacts if (contactPoints.nonEmpty) { contactPaths = contactPoints.map(ActorPath.fromString).to(HashSet) contacts = contactPaths.map(context.actorSelection) } publishContactPoints() - case _: ActorIdentity ⇒ // ok, from previous establish, already handled - case ReceptionistShutdown ⇒ + case _: ActorIdentity => // ok, from previous establish, already handled + case ReceptionistShutdown => if (receptionist == sender()) { log.info("Receptionist [{}] is shutting down, reestablishing connection", receptionist) reestablish() @@ -437,17 +437,17 @@ final class ClusterClient(settings: ClusterClientSettings) extends Actor with Ac } def contactPointMessages: Actor.Receive = { - case SubscribeContactPoints ⇒ + case SubscribeContactPoints => val subscriber = sender() subscriber ! ContactPoints(contactPaths) subscribers :+= subscriber context.watch(subscriber) - case UnsubscribeContactPoints ⇒ + case UnsubscribeContactPoints => val subscriber = sender() subscribers = subscribers.filterNot(_ == subscriber) - case Terminated(subscriber) ⇒ + case Terminated(subscriber) => self.tell(UnsubscribeContactPoints, subscriber) - case GetContactPoints ⇒ + case GetContactPoints => sender() ! ContactPoints(contactPaths) } @@ -476,16 +476,16 @@ final class ClusterClient(settings: ClusterClientSettings) extends Actor with Ac def sendBuffered(receptionist: ActorRef): Unit = { log.debug("Sending buffered messages to receptionist") - buffer.foreach((msg, snd) ⇒ receptionist.tell(msg, snd)) + buffer.foreach((msg, snd) => receptionist.tell(msg, snd)) buffer = MessageBuffer.empty } def publishContactPoints(): Unit = { - for (cp ← contactPaths if !contactPathsPublished.contains(cp)) { + for (cp <- contactPaths if !contactPathsPublished.contains(cp)) { val contactPointAdded = ContactPointAdded(cp) subscribers.foreach(_ ! contactPointAdded) } - for (cp ← contactPathsPublished if !contactPaths.contains(cp)) { + for (cp <- contactPathsPublished if !contactPaths.contains(cp)) { val contactPointRemoved = ContactPointRemoved(cp) subscribers.foreach(_ ! contactPointRemoved) } @@ -518,8 +518,8 @@ final class ClusterClientReceptionist(system: ExtendedActorSystem) extends Exten private val config = system.settings.config.getConfig("akka.cluster.client.receptionist") private val role: Option[String] = config.getString("role") match { - case "" ⇒ None - case r ⇒ Some(r) + case "" => None + case r => Some(r) } /** @@ -573,8 +573,8 @@ final class ClusterClientReceptionist(system: ExtendedActorSystem) extends Exten else { val name = config.getString("name") val dispatcher = config.getString("use-dispatcher") match { - case "" ⇒ Dispatchers.DefaultDispatcherId - case id ⇒ id + case "" => Dispatchers.DefaultDispatcherId + case id => id } // important to use val mediator here to activate it outside of ClusterReceptionist constructor val mediator = pubSubMediator @@ -832,11 +832,11 @@ object ClusterReceptionist { } def receive = { - case Ping ⇒ // keep alive from client - case ReceiveTimeout ⇒ + case Ping => // keep alive from client + case ReceiveTimeout => log.debug("ClientResponseTunnel for client [{}] stopped due to inactivity", client.path) context stop self - case msg ⇒ + case msg => client.tell(msg, Actor.noSender) if (isAsk) context stop self @@ -887,11 +887,11 @@ final class ClusterReceptionist(pubSubMediator: ActorRef, settings: ClusterRecep var nodes: immutable.SortedSet[Address] = { def hashFor(node: Address): Int = node match { // cluster node identifier is the host and port of the address; protocol and system is assumed to be the same - case Address(_, _, Some(host), Some(port)) ⇒ MurmurHash.stringHash(s"$host:$port") - case _ ⇒ + case Address(_, _, Some(host), Some(port)) => MurmurHash.stringHash(s"$host:$port") + case _ => throw new IllegalStateException(s"Unexpected address without host/port: [$node]") } - implicit val ringOrdering: Ordering[Address] = Ordering.fromLessThan[Address] { (a, b) ⇒ + implicit val ringOrdering: Ordering[Address] = Ordering.fromLessThan[Address] { (a, b) => val ha = hashFor(a) val hb = hashFor(b) ha < hb || (ha == hb && Member.addressOrdering.compare(a, b) < 0) @@ -930,29 +930,29 @@ final class ClusterReceptionist(pubSubMediator: ActorRef, settings: ClusterRecep def responseTunnel(client: ActorRef): ActorRef = { val encName = URLEncoder.encode(client.path.toSerializationFormat, "utf-8") context.child(encName) match { - case Some(tunnel) ⇒ tunnel - case None ⇒ + case Some(tunnel) => tunnel + case None => context.actorOf(Props(classOf[ClientResponseTunnel], client, responseTunnelReceiveTimeout), encName) } } def receive = { - case msg @ (_: Send | _: SendToAll | _: Publish) ⇒ + case msg @ (_: Send | _: SendToAll | _: Publish) => val tunnel = responseTunnel(sender()) tunnel ! Ping // keep alive pubSubMediator.tell(msg, tunnel) - case Heartbeat ⇒ + case Heartbeat => if (verboseHeartbeat) log.debug("Heartbeat from client [{}]", sender().path) sender() ! HeartbeatRsp updateClientInteractions(sender()) - case GetContacts ⇒ + case GetContacts => // Consistent hashing is used to ensure that the reply to GetContacts // is the same from all nodes (most of the time) and it also // load balances the client connections among the nodes in the cluster. if (numberOfContacts >= nodes.size) { - val contacts = Contacts(nodes.iterator.map(a ⇒ self.path.toStringWithAddress(a)).to(immutable.IndexedSeq)) + val contacts = Contacts(nodes.iterator.map(a => self.path.toStringWithAddress(a)).to(immutable.IndexedSeq)) if (log.isDebugEnabled) log.debug("Client [{}] gets contactPoints [{}] (all nodes)", sender().path, contacts.contactPoints.mkString(",")) sender() ! contacts @@ -965,23 +965,23 @@ final class ClusterReceptionist(pubSubMediator: ActorRef, settings: ClusterRecep if (first.size == numberOfContacts) first else first union nodes.take(numberOfContacts - first.size) } - val contacts = Contacts(slice.iterator.map(a ⇒ self.path.toStringWithAddress(a)).to(immutable.IndexedSeq)) + val contacts = Contacts(slice.iterator.map(a => self.path.toStringWithAddress(a)).to(immutable.IndexedSeq)) if (log.isDebugEnabled) log.debug("Client [{}] gets contactPoints [{}]", sender().path, contacts.contactPoints.mkString(",")) sender() ! contacts } - case state: CurrentClusterState ⇒ - nodes = nodes.empty union state.members.collect { case m if m.status != MemberStatus.Joining && matchingRole(m) ⇒ m.address } + case state: CurrentClusterState => + nodes = nodes.empty union state.members.collect { case m if m.status != MemberStatus.Joining && matchingRole(m) => m.address } consistentHash = ConsistentHash(nodes, virtualNodesFactor) - case MemberUp(m) ⇒ + case MemberUp(m) => if (matchingRole(m)) { nodes += m.address consistentHash = ConsistentHash(nodes, virtualNodesFactor) } - case MemberRemoved(m, _) ⇒ + case MemberRemoved(m, _) => if (m.address == selfAddress) context stop self else if (matchingRole(m)) { @@ -989,27 +989,27 @@ final class ClusterReceptionist(pubSubMediator: ActorRef, settings: ClusterRecep consistentHash = ConsistentHash(nodes, virtualNodesFactor) } - case _: MemberEvent ⇒ // not of interest + case _: MemberEvent => // not of interest - case SubscribeClusterClients ⇒ + case SubscribeClusterClients => val subscriber = sender() subscriber ! ClusterClients(clientInteractions.keySet.to(HashSet)) subscribers :+= subscriber context.watch(subscriber) - case UnsubscribeClusterClients ⇒ + case UnsubscribeClusterClients => val subscriber = sender() subscribers = subscribers.filterNot(_ == subscriber) - case Terminated(subscriber) ⇒ + case Terminated(subscriber) => self.tell(UnsubscribeClusterClients, subscriber) - case GetClusterClients ⇒ + case GetClusterClients => sender() ! ClusterClients(clientInteractions.keySet.to(HashSet)) - case CheckDeadlines ⇒ + case CheckDeadlines => clientInteractions = clientInteractions.filter { - case (_, failureDetector) ⇒ + case (_, failureDetector) => failureDetector.isAvailable } publishClientsUnreachable() @@ -1017,12 +1017,12 @@ final class ClusterReceptionist(pubSubMediator: ActorRef, settings: ClusterRecep def updateClientInteractions(client: ActorRef): Unit = clientInteractions.get(client) match { - case Some(failureDetector) ⇒ + case Some(failureDetector) => failureDetector.heartbeat() - case None ⇒ + case None => val failureDetector = new DeadlineFailureDetector(acceptableHeartbeatPause, heartbeatInterval) failureDetector.heartbeat() - clientInteractions = clientInteractions + (client → failureDetector) + clientInteractions = clientInteractions + (client -> failureDetector) log.debug("Received new contact from [{}]", client.path) val clusterClientUp = ClusterClientUp(client) subscribers.foreach(_ ! clusterClientUp) @@ -1031,7 +1031,7 @@ final class ClusterReceptionist(pubSubMediator: ActorRef, settings: ClusterRecep def publishClientsUnreachable(): Unit = { val publishableClients = clientInteractions.keySet.to(HashSet) - for (c ← clientsPublished if !publishableClients.contains(c)) { + for (c <- clientsPublished if !publishableClients.contains(c)) { log.debug("Lost contact with [{}]", c.path) val clusterClientUnreachable = ClusterClientUnreachable(c) subscribers.foreach(_ ! clusterClientUnreachable) diff --git a/akka-cluster-tools/src/main/scala/akka/cluster/client/protobuf/ClusterClientMessageSerializer.scala b/akka-cluster-tools/src/main/scala/akka/cluster/client/protobuf/ClusterClientMessageSerializer.scala index fe3d14409d..da97d54f20 100644 --- a/akka-cluster-tools/src/main/scala/akka/cluster/client/protobuf/ClusterClientMessageSerializer.scala +++ b/akka-cluster-tools/src/main/scala/akka/cluster/client/protobuf/ClusterClientMessageSerializer.scala @@ -10,7 +10,7 @@ import akka.serialization.BaseSerializer import akka.serialization.SerializationExtension import akka.serialization.SerializerWithStringManifest import akka.cluster.client.ClusterReceptionist -import akka.cluster.client.protobuf.msg.{ ClusterClientMessages ⇒ cm } +import akka.cluster.client.protobuf.msg.{ ClusterClientMessages => cm } import java.io.NotSerializableException /** @@ -30,37 +30,37 @@ private[akka] class ClusterClientMessageSerializer(val system: ExtendedActorSyst private val emptyByteArray = Array.empty[Byte] - private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] ⇒ AnyRef]( - ContactsManifest → contactsFromBinary, - GetContactsManifest → { _ ⇒ GetContacts }, - HeartbeatManifest → { _ ⇒ Heartbeat }, - HeartbeatRspManifest → { _ ⇒ HeartbeatRsp }, - ReceptionistShutdownManifest → { _ ⇒ ReceptionistShutdown }) + private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] => AnyRef]( + ContactsManifest -> contactsFromBinary, + GetContactsManifest -> { _ => GetContacts }, + HeartbeatManifest -> { _ => Heartbeat }, + HeartbeatRspManifest -> { _ => HeartbeatRsp }, + ReceptionistShutdownManifest -> { _ => ReceptionistShutdown }) override def manifest(obj: AnyRef): String = obj match { - case _: Contacts ⇒ ContactsManifest - case GetContacts ⇒ GetContactsManifest - case Heartbeat ⇒ HeartbeatManifest - case HeartbeatRsp ⇒ HeartbeatRspManifest - case ReceptionistShutdown ⇒ ReceptionistShutdownManifest - case _ ⇒ + case _: Contacts => ContactsManifest + case GetContacts => GetContactsManifest + case Heartbeat => HeartbeatManifest + case HeartbeatRsp => HeartbeatRspManifest + case ReceptionistShutdown => ReceptionistShutdownManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: Contacts ⇒ contactsToProto(m).toByteArray - case GetContacts ⇒ emptyByteArray - case Heartbeat ⇒ emptyByteArray - case HeartbeatRsp ⇒ emptyByteArray - case ReceptionistShutdown ⇒ emptyByteArray - case _ ⇒ + case m: Contacts => contactsToProto(m).toByteArray + case GetContacts => emptyByteArray + case Heartbeat => emptyByteArray + case HeartbeatRsp => emptyByteArray + case ReceptionistShutdown => emptyByteArray + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = fromBinaryMap.get(manifest) match { - case Some(f) ⇒ f(bytes) - case None ⇒ throw new NotSerializableException( + case Some(f) => f(bytes) + case None => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } diff --git a/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/DistributedPubSubMediator.scala b/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/DistributedPubSubMediator.scala index f765d81d05..2278d7ee93 100644 --- a/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/DistributedPubSubMediator.scala +++ b/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/DistributedPubSubMediator.scala @@ -47,11 +47,11 @@ object DistributedPubSubSettings { new DistributedPubSubSettings( role = roleOption(config.getString("role")), routingLogic = config.getString("routing-logic") match { - case "random" ⇒ RandomRoutingLogic() - case "round-robin" ⇒ RoundRobinRoutingLogic() - case "consistent-hashing" ⇒ throw new IllegalArgumentException(s"'consistent-hashing' routing logic can't be used by the pub-sub mediator") - case "broadcast" ⇒ BroadcastRoutingLogic() - case other ⇒ throw new IllegalArgumentException(s"Unknown 'routing-logic': [$other]") + case "random" => RandomRoutingLogic() + case "round-robin" => RoundRobinRoutingLogic() + case "consistent-hashing" => throw new IllegalArgumentException(s"'consistent-hashing' routing logic can't be used by the pub-sub mediator") + case "broadcast" => BroadcastRoutingLogic() + case other => throw new IllegalArgumentException(s"Unknown 'routing-logic': [$other]") }, gossipInterval = config.getDuration("gossip-interval", MILLISECONDS).millis, removedTimeToLive = config.getDuration("removed-time-to-live", MILLISECONDS).millis, @@ -321,30 +321,30 @@ object DistributedPubSubMediator { } def defaultReceive: Receive = { - case msg @ Subscribe(_, _, ref) ⇒ + case msg @ Subscribe(_, _, ref) => context watch ref subscribers += ref pruneDeadline = None context.parent ! Subscribed(SubscribeAck(msg), sender()) - case msg @ Unsubscribe(_, _, ref) ⇒ + case msg @ Unsubscribe(_, _, ref) => context unwatch ref remove(ref) context.parent ! Unsubscribed(UnsubscribeAck(msg), sender()) - case Terminated(ref) ⇒ + case Terminated(ref) => remove(ref) - case Prune ⇒ - for (d ← pruneDeadline if d.isOverdue) { + case Prune => + for (d <- pruneDeadline if d.isOverdue) { pruneDeadline = None context.parent ! NoMoreSubscribers } - case TerminateRequest ⇒ + case TerminateRequest => if (subscribers.isEmpty && context.children.isEmpty) context stop self else context.parent ! NewSubscriberArrived - case Count ⇒ + case Count => sender() ! subscribers.size - case msg ⇒ + case msg => subscribers foreach { _ forward msg } } @@ -362,35 +362,35 @@ object DistributedPubSubMediator { class Topic(val emptyTimeToLive: FiniteDuration, routingLogic: RoutingLogic) extends TopicLike with PerGroupingBuffer { def business = { - case msg @ Subscribe(_, Some(group), _) ⇒ + case msg @ Subscribe(_, Some(group), _) => val encGroup = encName(group) bufferOr(mkKey(self.path / encGroup), msg, sender()) { context.child(encGroup) match { - case Some(g) ⇒ g forward msg - case None ⇒ newGroupActor(encGroup) forward msg + case Some(g) => g forward msg + case None => newGroupActor(encGroup) forward msg } } pruneDeadline = None - case msg @ Unsubscribe(_, Some(group), _) ⇒ + case msg @ Unsubscribe(_, Some(group), _) => val encGroup = encName(group) bufferOr(mkKey(self.path / encGroup), msg, sender()) { context.child(encGroup) match { - case Some(g) ⇒ g forward msg - case None ⇒ // no such group here + case Some(g) => g forward msg + case None => // no such group here } } - case msg: Subscribed ⇒ + case msg: Subscribed => context.parent forward msg - case msg: Unsubscribed ⇒ + case msg: Unsubscribed => context.parent forward msg - case NoMoreSubscribers ⇒ + case NoMoreSubscribers => val key = mkKey(sender()) initializeGrouping(key) sender() ! TerminateRequest - case NewSubscriberArrived ⇒ + case NewSubscriberArrived => val key = mkKey(sender()) forwardMessages(key, sender()) - case Terminated(ref) ⇒ + case Terminated(ref) => val key = mkKey(ref) recreateAndForwardMessagesIfNeeded(key, newGroupActor(ref.path.name)) remove(ref) @@ -406,7 +406,7 @@ object DistributedPubSubMediator { class Group(val emptyTimeToLive: FiniteDuration, routingLogic: RoutingLogic) extends TopicLike { def business = { - case SendToOneSubscriber(msg) ⇒ + case SendToOneSubscriber(msg) => if (subscribers.nonEmpty) Router(routingLogic, (subscribers map ActorRefRoutee).toVector).route(wrapIfNeeded(msg), sender()) } @@ -421,10 +421,10 @@ object DistributedPubSubMediator { * [[MediatorRouterEnvelope]] which will be unwrapped by the [[akka.routing.Router]] leaving original * user message. */ - def wrapIfNeeded: Any ⇒ Any = { - case msg: RouterEnvelope ⇒ MediatorRouterEnvelope(msg) - case null ⇒ throw InvalidMessageException("Message must not be null") - case msg: Any ⇒ msg + def wrapIfNeeded: Any => Any = { + case msg: RouterEnvelope => MediatorRouterEnvelope(msg) + case null => throw InvalidMessageException("Message must not be null") + case msg: Any => msg } } } @@ -529,14 +529,14 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act val pruneInterval: FiniteDuration = removedTimeToLive / 2 val pruneTask = context.system.scheduler.schedule(pruneInterval, pruneInterval, self, Prune) - var registry: Map[Address, Bucket] = Map.empty.withDefault(a ⇒ Bucket(a, 0L, TreeMap.empty)) + var registry: Map[Address, Bucket] = Map.empty.withDefault(a => Bucket(a, 0L, TreeMap.empty)) var nodes: Set[Address] = Set.empty var deltaCount = 0L // the version is a timestamp because it is also used when pruning removed entries val nextVersion = { var version = 0L - () ⇒ { + () => { val current = System.currentTimeMillis version = if (current > version) current else version + 1 version @@ -560,33 +560,33 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act def receive = { - case Send(path, msg, localAffinity) ⇒ + case Send(path, msg, localAffinity) => val routees = registry(selfAddress).content.get(path) match { - case Some(valueHolder) if localAffinity ⇒ + case Some(valueHolder) if localAffinity => (for { - routee ← valueHolder.routee + routee <- valueHolder.routee } yield routee).toVector - case _ ⇒ + case _ => (for { - (_, bucket) ← registry - valueHolder ← bucket.content.get(path).toSeq - routee ← valueHolder.routee.toSeq + (_, bucket) <- registry + valueHolder <- bucket.content.get(path).toSeq + routee <- valueHolder.routee.toSeq } yield routee).toVector } if (routees.isEmpty) ignoreOrSendToDeadLetters(msg) else Router(routingLogic, routees).route(wrapIfNeeded(msg), sender()) - case SendToAll(path, msg, skipSenderNode) ⇒ + case SendToAll(path, msg, skipSenderNode) => publish(path, msg, skipSenderNode) - case Publish(topic, msg, sendOneMessageToEachGroup) ⇒ + case Publish(topic, msg, sendOneMessageToEachGroup) => if (sendOneMessageToEachGroup) publishToEachGroup(mkKey(self.path / encName(topic)), msg) else publish(mkKey(self.path / encName(topic)), msg) - case Put(ref: ActorRef) ⇒ + case Put(ref: ActorRef) => if (ref.path.address.hasGlobalScope) log.warning("Registered actor must be local: [{}]", ref) else { @@ -594,57 +594,57 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act context.watch(ref) } - case Remove(key) ⇒ + case Remove(key) => registry(selfAddress).content.get(key) match { - case Some(ValueHolder(_, Some(ref))) ⇒ + case Some(ValueHolder(_, Some(ref))) => context.unwatch(ref) put(key, None) - case _ ⇒ + case _ => } - case msg @ Subscribe(topic, _, _) ⇒ + case msg @ Subscribe(topic, _, _) => // each topic is managed by a child actor with the same name as the topic val encTopic = encName(topic) bufferOr(mkKey(self.path / encTopic), msg, sender()) { context.child(encTopic) match { - case Some(t) ⇒ t forward msg - case None ⇒ newTopicActor(encTopic) forward msg + case Some(t) => t forward msg + case None => newTopicActor(encTopic) forward msg } } - case msg @ RegisterTopic(t) ⇒ + case msg @ RegisterTopic(t) => registerTopic(t) - case NoMoreSubscribers ⇒ + case NoMoreSubscribers => val key = mkKey(sender()) initializeGrouping(key) sender() ! TerminateRequest - case NewSubscriberArrived ⇒ + case NewSubscriberArrived => val key = mkKey(sender()) forwardMessages(key, sender()) - case GetTopics ⇒ + case GetTopics => sender ! CurrentTopics(getCurrentTopics()) - case msg @ Subscribed(ack, ref) ⇒ + case msg @ Subscribed(ack, ref) => ref ! ack - case msg @ Unsubscribe(topic, _, _) ⇒ + case msg @ Unsubscribe(topic, _, _) => val encTopic = encName(topic) bufferOr(mkKey(self.path / encTopic), msg, sender()) { context.child(encTopic) match { - case Some(t) ⇒ t forward msg - case None ⇒ // no such topic here + case Some(t) => t forward msg + case None => // no such topic here } } - case msg @ Unsubscribed(ack, ref) ⇒ + case msg @ Unsubscribed(ack, ref) => ref ! ack - case Status(otherVersions, isReplyToStatus) ⇒ + case Status(otherVersions, isReplyToStatus) => // only accept status from known nodes, otherwise old cluster with same address may interact // also accept from local for testing purposes if (nodes(sender().path.address) || sender().path.address.hasLocalScope) { @@ -656,7 +656,7 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act sender() ! Status(versions = myVersions, isReplyToStatus = true) // it will reply with Delta } - case Delta(buckets) ⇒ + case Delta(buckets) => deltaCount += 1 // reply from Status message in the gossip chat @@ -664,56 +664,56 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act // only accept deltas/buckets from known nodes, otherwise there is a risk of // adding back entries when nodes are removed if (nodes(sender().path.address)) { - buckets foreach { b ⇒ + buckets foreach { b => if (nodes(b.owner)) { val myBucket = registry(b.owner) if (b.version > myBucket.version) { - registry += (b.owner → myBucket.copy(version = b.version, content = myBucket.content ++ b.content)) + registry += (b.owner -> myBucket.copy(version = b.version, content = myBucket.content ++ b.content)) } } } } - case GossipTick ⇒ gossip() + case GossipTick => gossip() - case Prune ⇒ prune() + case Prune => prune() - case Terminated(a) ⇒ + case Terminated(a) => val key = mkKey(a) registry(selfAddress).content.get(key) match { - case Some(ValueHolder(_, Some(`a`))) ⇒ + case Some(ValueHolder(_, Some(`a`))) => // remove put(key, None) - case _ ⇒ + case _ => } recreateAndForwardMessagesIfNeeded(key, newTopicActor(a.path.name)) - case state: CurrentClusterState ⇒ + case state: CurrentClusterState => nodes = state.members.collect { - case m if m.status != MemberStatus.Joining && matchingRole(m) ⇒ m.address + case m if m.status != MemberStatus.Joining && matchingRole(m) => m.address } - case MemberUp(m) ⇒ + case MemberUp(m) => if (matchingRole(m)) nodes += m.address - case MemberWeaklyUp(m) ⇒ + case MemberWeaklyUp(m) => if (matchingRole(m)) nodes += m.address - case MemberLeft(m) ⇒ + case MemberLeft(m) => if (matchingRole(m)) { nodes -= m.address registry -= m.address } - case MemberDowned(m) ⇒ + case MemberDowned(m) => if (matchingRole(m)) { nodes -= m.address registry -= m.address } - case MemberRemoved(m, _) ⇒ + case MemberRemoved(m, _) => if (m.address == selfAddress) context stop self else if (matchingRole(m)) { @@ -721,25 +721,25 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act registry -= m.address } - case _: MemberEvent ⇒ // not of interest + case _: MemberEvent => // not of interest - case Count ⇒ + case Count => val count = registry.map { - case (owner, bucket) ⇒ bucket.content.count { - case (_, valueHolder) ⇒ valueHolder.ref.isDefined + case (owner, bucket) => bucket.content.count { + case (_, valueHolder) => valueHolder.ref.isDefined } }.sum sender() ! count - case DeltaCount ⇒ + case DeltaCount => sender() ! deltaCount - case msg @ CountSubscribers(topic) ⇒ + case msg @ CountSubscribers(topic) => val encTopic = encName(topic) bufferOr(mkKey(self.path / encTopic), msg, sender()) { context.child(encTopic) match { - case Some(ref) ⇒ ref.tell(Count, sender()) - case None ⇒ sender() ! 0 + case Some(ref) => ref.tell(Count, sender()) + case None => sender() ! 0 } } } @@ -749,10 +749,10 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act def publish(path: String, msg: Any, allButSelf: Boolean = false): Unit = { val refs = for { - (address, bucket) ← registry + (address, bucket) <- registry if !(allButSelf && address == selfAddress) // if we should skip sender() node and current address == self address => skip - valueHolder ← bucket.content.get(path).toSeq - ref ← valueHolder.ref.toSeq + valueHolder <- bucket.content.get(path).toSeq + ref <- valueHolder.ref.toSeq } yield ref if (refs.isEmpty) ignoreOrSendToDeadLetters(msg) else refs.foreach(_.forward(msg)) @@ -762,10 +762,10 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act val prefix = path + '/' val lastKey = path + '0' // '0' is the next char of '/' val groups = (for { - (_, bucket) ← registry.toSeq - key ← bucket.content.range(prefix, lastKey).keys - valueHolder ← bucket.content.get(key) - ref ← valueHolder.routee + (_, bucket) <- registry.toSeq + key <- bucket.content.range(prefix, lastKey).keys + valueHolder <- bucket.content.get(key) + ref <- valueHolder.routee } yield (key, ref)).groupBy(_._1).values if (groups.isEmpty) { @@ -773,7 +773,7 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act } else { val wrappedMsg = SendToOneSubscriber(msg) groups foreach { - group ⇒ + group => val routees = group.map(_._2).toVector if (routees.nonEmpty) Router(routingLogic, routees).route(wrappedMsg, sender()) @@ -784,16 +784,16 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act def put(key: String, valueOption: Option[ActorRef]): Unit = { val bucket = registry(selfAddress) val v = nextVersion() - registry += (selfAddress → bucket.copy( + registry += (selfAddress -> bucket.copy( version = v, - content = bucket.content + (key → ValueHolder(v, valueOption)))) + content = bucket.content + (key -> ValueHolder(v, valueOption)))) } def getCurrentTopics(): Set[String] = { val topicPrefix = self.path.toStringWithoutAddress (for { - (_, bucket) ← registry - (key, value) ← bucket.content.toSeq + (_, bucket) <- registry + (key, value) <- bucket.content.toSeq if key.startsWith(topicPrefix) topic = key.substring(topicPrefix.length + 1) if !topic.contains('/') // exclude group topics @@ -809,17 +809,17 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act def mkKey(path: ActorPath): String = Internal.mkKey(path) - def myVersions: Map[Address, Long] = registry.map { case (owner, bucket) ⇒ (owner → bucket.version) } + def myVersions: Map[Address, Long] = registry.map { case (owner, bucket) => (owner -> bucket.version) } def collectDelta(otherVersions: Map[Address, Long]): immutable.Iterable[Bucket] = { // missing entries are represented by version 0 - val filledOtherVersions = myVersions.map { case (k, _) ⇒ k → 0L } ++ otherVersions + val filledOtherVersions = myVersions.map { case (k, _) => k -> 0L } ++ otherVersions var count = 0 filledOtherVersions.collect { - case (owner, v) if registry(owner).version > v && count < maxDeltaElements ⇒ + case (owner, v) if registry(owner).version > v && count < maxDeltaElements => val bucket = registry(owner) val deltaContent = bucket.content.filter { - case (_, value) ⇒ value.version > v + case (_, value) => value.version > v } count += deltaContent.size if (count <= maxDeltaElements) @@ -835,7 +835,7 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act def otherHasNewerVersions(otherVersions: Map[Address, Long]): Boolean = otherVersions.exists { - case (owner, v) ⇒ v > registry(owner).version + case (owner, v) => v > registry(owner).version } /** @@ -853,12 +853,12 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) extends Act def prune(): Unit = { registry foreach { - case (owner, bucket) ⇒ + case (owner, bucket) => val oldRemoved = bucket.content.collect { - case (key, ValueHolder(version, None)) if (bucket.version - version > removedTimeToLiveMillis) ⇒ key + case (key, ValueHolder(version, None)) if (bucket.version - version > removedTimeToLiveMillis) => key } if (oldRemoved.nonEmpty) - registry += owner → bucket.copy(content = bucket.content -- oldRemoved) + registry += owner -> bucket.copy(content = bucket.content -- oldRemoved) } } @@ -902,8 +902,8 @@ class DistributedPubSub(system: ExtendedActorSystem) extends Extension { else { val name = system.settings.config.getString("akka.cluster.pub-sub.name") val dispatcher = system.settings.config.getString("akka.cluster.pub-sub.use-dispatcher") match { - case "" ⇒ Dispatchers.DefaultDispatcherId - case id ⇒ id + case "" => Dispatchers.DefaultDispatcherId + case id => id } system.systemActorOf(DistributedPubSubMediator.props(settings).withDispatcher(dispatcher), name) } diff --git a/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/PerGroupingBuffer.scala b/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/PerGroupingBuffer.scala index 3ede986b79..825936f21f 100644 --- a/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/PerGroupingBuffer.scala +++ b/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/PerGroupingBuffer.scala @@ -11,12 +11,12 @@ private[pubsub] trait PerGroupingBuffer { private val buffers: MessageBufferMap[String] = new MessageBufferMap() - def bufferOr(grouping: String, message: Any, originalSender: ActorRef)(action: ⇒ Unit): Unit = { + def bufferOr(grouping: String, message: Any, originalSender: ActorRef)(action: => Unit): Unit = { if (!buffers.contains(grouping)) action else buffers.append(grouping, message, originalSender) } - def recreateAndForwardMessagesIfNeeded(grouping: String, recipient: ⇒ ActorRef): Unit = { + def recreateAndForwardMessagesIfNeeded(grouping: String, recipient: => ActorRef): Unit = { val buffer = buffers.getOrEmpty(grouping) if (buffer.nonEmpty) { forwardMessages(buffer, recipient) @@ -31,7 +31,7 @@ private[pubsub] trait PerGroupingBuffer { private def forwardMessages(messages: MessageBuffer, recipient: ActorRef): Unit = { messages.foreach { - case (message, originalSender) ⇒ recipient.tell(message, originalSender) + case (message, originalSender) => recipient.tell(message, originalSender) } } diff --git a/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/protobuf/DistributedPubSubMessageSerializer.scala b/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/protobuf/DistributedPubSubMessageSerializer.scala index 17257248fc..911d4d0083 100644 --- a/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/protobuf/DistributedPubSubMessageSerializer.scala +++ b/akka-cluster-tools/src/main/scala/akka/cluster/pubsub/protobuf/DistributedPubSubMessageSerializer.scala @@ -11,7 +11,7 @@ import akka.protobuf.{ ByteString, MessageLite } import java.util.zip.GZIPOutputStream import java.util.zip.GZIPInputStream import scala.annotation.tailrec -import akka.cluster.pubsub.protobuf.msg.{ DistributedPubSubMessages ⇒ dm } +import akka.cluster.pubsub.protobuf.msg.{ DistributedPubSubMessages => dm } import scala.collection.JavaConverters._ import akka.cluster.pubsub.DistributedPubSubMediator._ import akka.cluster.pubsub.DistributedPubSubMediator.Internal._ @@ -37,40 +37,40 @@ private[akka] class DistributedPubSubMessageSerializer(val system: ExtendedActor private val PublishManifest = "E" private val SendToOneSubscriberManifest = "F" - private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] ⇒ AnyRef]( - StatusManifest → statusFromBinary, - DeltaManifest → deltaFromBinary, - SendManifest → sendFromBinary, - SendToAllManifest → sendToAllFromBinary, - PublishManifest → publishFromBinary, - SendToOneSubscriberManifest → sendToOneSubscriberFromBinary) + private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] => AnyRef]( + StatusManifest -> statusFromBinary, + DeltaManifest -> deltaFromBinary, + SendManifest -> sendFromBinary, + SendToAllManifest -> sendToAllFromBinary, + PublishManifest -> publishFromBinary, + SendToOneSubscriberManifest -> sendToOneSubscriberFromBinary) override def manifest(obj: AnyRef): String = obj match { - case _: Status ⇒ StatusManifest - case _: Delta ⇒ DeltaManifest - case _: Send ⇒ SendManifest - case _: SendToAll ⇒ SendToAllManifest - case _: Publish ⇒ PublishManifest - case _: SendToOneSubscriber ⇒ SendToOneSubscriberManifest - case _ ⇒ + case _: Status => StatusManifest + case _: Delta => DeltaManifest + case _: Send => SendManifest + case _: SendToAll => SendToAllManifest + case _: Publish => PublishManifest + case _: SendToOneSubscriber => SendToOneSubscriberManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: Status ⇒ compress(statusToProto(m)) - case m: Delta ⇒ compress(deltaToProto(m)) - case m: Send ⇒ sendToProto(m).toByteArray - case m: SendToAll ⇒ sendToAllToProto(m).toByteArray - case m: Publish ⇒ publishToProto(m).toByteArray - case m: SendToOneSubscriber ⇒ sendToOneSubscriberToProto(m).toByteArray - case _ ⇒ + case m: Status => compress(statusToProto(m)) + case m: Delta => compress(deltaToProto(m)) + case m: Send => sendToProto(m).toByteArray + case m: SendToAll => sendToAllToProto(m).toByteArray + case m: Publish => publishToProto(m).toByteArray + case m: SendToOneSubscriber => sendToOneSubscriberToProto(m).toByteArray + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = fromBinaryMap.get(manifest) match { - case Some(f) ⇒ f(bytes) - case None ⇒ throw new NotSerializableException( + case Some(f) => f(bytes) + case None => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } @@ -88,8 +88,8 @@ private[akka] class DistributedPubSubMessageSerializer(val system: ExtendedActor val buffer = new Array[Byte](BufferSize) @tailrec def readChunk(): Unit = in.read(buffer) match { - case -1 ⇒ () - case n ⇒ + case -1 => () + case n => out.write(buffer, 0, n) readChunk() } @@ -100,9 +100,9 @@ private[akka] class DistributedPubSubMessageSerializer(val system: ExtendedActor } private def addressToProto(address: Address): dm.Address.Builder = address match { - case Address(protocol, system, Some(host), Some(port)) ⇒ + case Address(protocol, system, Some(host), Some(port)) => dm.Address.newBuilder().setSystem(system).setHostname(host).setPort(port).setProtocol(protocol) - case _ ⇒ throw new IllegalArgumentException(s"Address [${address}] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [${address}] could not be serialized: host or port missing.") } private def addressFromProto(address: dm.Address): Address = @@ -110,7 +110,7 @@ private[akka] class DistributedPubSubMessageSerializer(val system: ExtendedActor private def statusToProto(status: Status): dm.Status = { val versions = status.versions.map { - case (a, v) ⇒ + case (a, v) => dm.Status.Version.newBuilder(). setAddress(addressToProto(a)). setTimestamp(v). @@ -127,16 +127,16 @@ private[akka] class DistributedPubSubMessageSerializer(val system: ExtendedActor private def statusFromProto(status: dm.Status): Status = { val isReplyToStatus = if (status.hasReplyToStatus) status.getReplyToStatus else false - Status(status.getVersionsList.asScala.iterator.map(v ⇒ - addressFromProto(v.getAddress) → v.getTimestamp).toMap, isReplyToStatus) + Status(status.getVersionsList.asScala.iterator.map(v => + addressFromProto(v.getAddress) -> v.getTimestamp).toMap, isReplyToStatus) } private def deltaToProto(delta: Delta): dm.Delta = { - val buckets = delta.buckets.map { b ⇒ + val buckets = delta.buckets.map { b => val entries = b.content.map { - case (key, value) ⇒ + case (key, value) => val b = dm.Delta.Entry.newBuilder().setKey(key).setVersion(value.version) - value.ref.foreach(r ⇒ b.setRef(Serialization.serializedActorPath(r))) + value.ref.foreach(r => b.setRef(Serialization.serializedActorPath(r))) b.build() }.toVector.asJava @@ -153,9 +153,9 @@ private[akka] class DistributedPubSubMessageSerializer(val system: ExtendedActor deltaFromProto(dm.Delta.parseFrom(decompress(bytes))) private def deltaFromProto(delta: dm.Delta): Delta = - Delta(delta.getBucketsList.asScala.toVector.map { b ⇒ - val content: TreeMap[String, ValueHolder] = scala.collection.immutable.TreeMap.from(b.getContentList.asScala.iterator.map { entry ⇒ - entry.getKey → ValueHolder(entry.getVersion, if (entry.hasRef) Some(resolveActorRef(entry.getRef)) else None) + Delta(delta.getBucketsList.asScala.toVector.map { b => + val content: TreeMap[String, ValueHolder] = scala.collection.immutable.TreeMap.from(b.getContentList.asScala.iterator.map { entry => + entry.getKey -> ValueHolder(entry.getVersion, if (entry.hasRef) Some(resolveActorRef(entry.getRef)) else None) }) Bucket(addressFromProto(b.getOwner), b.getVersion, content) }) diff --git a/akka-cluster-tools/src/main/scala/akka/cluster/singleton/ClusterSingletonManager.scala b/akka-cluster-tools/src/main/scala/akka/cluster/singleton/ClusterSingletonManager.scala index c52000d55e..234e0f0624 100644 --- a/akka-cluster-tools/src/main/scala/akka/cluster/singleton/ClusterSingletonManager.scala +++ b/akka-cluster-tools/src/main/scala/akka/cluster/singleton/ClusterSingletonManager.scala @@ -256,7 +256,7 @@ object ClusterSingletonManager { // Using PhaseClusterExiting in the singleton because the graceful shutdown of sharding region // should preferably complete before stopping the singleton sharding coordinator on same node. val coordShutdown = CoordinatedShutdown(context.system) - coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExiting, "singleton-exiting-1") { () ⇒ + coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExiting, "singleton-exiting-1") { () => if (cluster.isTerminated || cluster.selfMember.status == MemberStatus.Down) { Future.successful(Done) } else { @@ -272,7 +272,7 @@ object ClusterSingletonManager { def matchingRole(member: Member): Boolean = member.hasRole(selfDc) && role.forall(member.hasRole) - def trackChange(block: () ⇒ Unit): Unit = { + def trackChange(block: () => Unit): Unit = { val before = membersByAge.headOption block() val after = membersByAge.headOption @@ -281,13 +281,13 @@ object ClusterSingletonManager { } def handleInitial(state: CurrentClusterState): Unit = { - membersByAge = immutable.SortedSet.empty(ageOrdering) union state.members.filter(m ⇒ + membersByAge = immutable.SortedSet.empty(ageOrdering) union state.members.filter(m => m.status == MemberStatus.Up && matchingRole(m)) // If there is some removal in progress of an older node it's not safe to immediately become oldest, // removal of younger nodes doesn't matter. Note that it can also be started via restart after // ClusterSingletonManagerIsStuck. - val selfUpNumber = state.members.collectFirst { case m if m.uniqueAddress == cluster.selfUniqueAddress ⇒ m.upNumber }.getOrElse(Int.MaxValue) - val safeToBeOldest = !state.members.exists { m ⇒ + val selfUpNumber = state.members.collectFirst { case m if m.uniqueAddress == cluster.selfUniqueAddress => m.upNumber }.getOrElse(Int.MaxValue) + val safeToBeOldest = !state.members.exists { m => m.upNumber <= selfUpNumber && matchingRole(m) && (m.status == MemberStatus.Down || m.status == MemberStatus.Exiting || m.status == MemberStatus.Leaving) } val initial = InitialOldestState(membersByAge.headOption.map(_.uniqueAddress), safeToBeOldest) @@ -296,7 +296,7 @@ object ClusterSingletonManager { def add(m: Member): Unit = { if (matchingRole(m)) - trackChange { () ⇒ + trackChange { () => // replace, it's possible that the upNumber is changed membersByAge = membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) membersByAge += m @@ -305,7 +305,7 @@ object ClusterSingletonManager { def remove(m: Member): Unit = { if (matchingRole(m)) - trackChange { () ⇒ + trackChange { () => membersByAge = membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) } } @@ -320,36 +320,36 @@ object ClusterSingletonManager { } def receive = { - case state: CurrentClusterState ⇒ handleInitial(state) - case MemberUp(m) ⇒ add(m) - case MemberRemoved(m, _) ⇒ remove(m) - case MemberExited(m) if m.uniqueAddress != cluster.selfUniqueAddress ⇒ + case state: CurrentClusterState => handleInitial(state) + case MemberUp(m) => add(m) + case MemberRemoved(m, _) => remove(m) + case MemberExited(m) if m.uniqueAddress != cluster.selfUniqueAddress => remove(m) - case SelfExiting ⇒ + case SelfExiting => remove(cluster.readView.self) sender() ! Done // reply to ask - case GetNext if changes.isEmpty ⇒ + case GetNext if changes.isEmpty => context.become(deliverNext, discardOld = false) - case GetNext ⇒ + case GetNext => sendFirstChange() } // the buffer was empty when GetNext was received, deliver next event immediately def deliverNext: Actor.Receive = { - case state: CurrentClusterState ⇒ + case state: CurrentClusterState => handleInitial(state) sendFirstChange() context.unbecome() - case MemberUp(m) ⇒ + case MemberUp(m) => add(m) deliverChanges() - case MemberRemoved(m, _) ⇒ + case MemberRemoved(m, _) => remove(m) deliverChanges() - case MemberExited(m) if m.uniqueAddress != cluster.selfUniqueAddress ⇒ + case MemberExited(m) if m.uniqueAddress != cluster.selfUniqueAddress => remove(m) deliverChanges() - case SelfExiting ⇒ + case SelfExiting => remove(cluster.readView.self) deliverChanges() sender() ! Done // reply to ask @@ -364,8 +364,8 @@ object ClusterSingletonManager { override def unhandled(msg: Any): Unit = { msg match { - case _: MemberEvent ⇒ // ok, silence - case _ ⇒ super.unhandled(msg) + case _: MemberEvent => // ok, silence + case _ => super.unhandled(msg) } } } @@ -437,7 +437,7 @@ class ClusterSingletonManager( import ClusterSingletonManager.Internal._ import ClusterSingletonManager.Internal.OldestChangedBuffer._ import settings._ - import FSM.`→` + import FSM.`->` val cluster = Cluster(context.system) val selfUniqueAddressOption = Some(cluster.selfUniqueAddress) @@ -473,22 +473,22 @@ class ClusterSingletonManager( var removed = Map.empty[UniqueAddress, Deadline] def addRemoved(node: UniqueAddress): Unit = - removed += node → (Deadline.now + 15.minutes) + removed += node -> (Deadline.now + 15.minutes) def cleanupOverdueNotMemberAnyMore(): Unit = { - removed = removed filter { case (_, deadline) ⇒ deadline.hasTimeLeft } + removed = removed filter { case (_, deadline) => deadline.hasTimeLeft } } // for CoordinatedShutdown val coordShutdown = CoordinatedShutdown(context.system) val memberExitingProgress = Promise[Done]() - coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExiting, "wait-singleton-exiting") { () ⇒ + coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExiting, "wait-singleton-exiting") { () => if (cluster.isTerminated || cluster.selfMember.status == MemberStatus.Down) Future.successful(Done) else memberExitingProgress.future } - coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExiting, "singleton-exiting-2") { () ⇒ + coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExiting, "singleton-exiting-2") { () => if (cluster.isTerminated || cluster.selfMember.status == MemberStatus.Down) { Future.successful(Done) } else { @@ -538,13 +538,13 @@ class ClusterSingletonManager( startWith(Start, Uninitialized) when(Start) { - case Event(StartOldestChangedBuffer, _) ⇒ + case Event(StartOldestChangedBuffer, _) => oldestChangedBuffer = context.actorOf(Props(classOf[OldestChangedBuffer], role). withDispatcher(context.props.dispatcher)) getNextOldestChanged() stay - case Event(InitialOldestState(oldestOption, safeToBeOldest), _) ⇒ + case Event(InitialOldestState(oldestOption, safeToBeOldest), _) => oldestChangedReceived = true if (oldestOption == selfUniqueAddressOption && safeToBeOldest) // oldest immediately @@ -556,14 +556,14 @@ class ClusterSingletonManager( } when(Younger) { - case Event(OldestChanged(oldestOption), YoungerData(previousOldestOption)) ⇒ + case Event(OldestChanged(oldestOption), YoungerData(previousOldestOption)) => oldestChangedReceived = true if (oldestOption == selfUniqueAddressOption) { logInfo("Younger observed OldestChanged: [{} -> myself]", previousOldestOption.map(_.address)) previousOldestOption match { - case None ⇒ gotoOldest() - case Some(prev) if removed.contains(prev) ⇒ gotoOldest() - case Some(prev) ⇒ + case None => gotoOldest() + case Some(prev) if removed.contains(prev) => gotoOldest() + case Some(prev) => peer(prev.address) ! HandOverToMe goto(BecomingOldest) using BecomingOldestData(previousOldestOption) } @@ -573,25 +573,25 @@ class ClusterSingletonManager( stay using YoungerData(oldestOption) } - case Event(MemberDowned(m), _) if m.uniqueAddress == cluster.selfUniqueAddress ⇒ + case Event(MemberDowned(m), _) if m.uniqueAddress == cluster.selfUniqueAddress => logInfo("Self downed, stopping ClusterSingletonManager") stop() - case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress ⇒ + case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress => logInfo("Self removed, stopping ClusterSingletonManager") stop() - case Event(MemberRemoved(m, _), _) ⇒ + case Event(MemberRemoved(m, _), _) => scheduleDelayedMemberRemoved(m) stay - case Event(DelayedMemberRemoved(m), YoungerData(Some(previousOldest))) if m.uniqueAddress == previousOldest ⇒ + case Event(DelayedMemberRemoved(m), YoungerData(Some(previousOldest))) if m.uniqueAddress == previousOldest => logInfo("Previous oldest removed [{}]", m.address) addRemoved(m.uniqueAddress) // transition when OldestChanged stay using YoungerData(None) - case Event(HandOverToMe, _) ⇒ + case Event(HandOverToMe, _) => // this node was probably quickly restarted with same hostname:port, // confirm that the old singleton instance has been stopped sender() ! HandOverDone @@ -600,13 +600,13 @@ class ClusterSingletonManager( when(BecomingOldest) { - case Event(HandOverInProgress, _) ⇒ + case Event(HandOverInProgress, _) => // confirmation that the hand-over process has started logInfo("Hand-over in progress at [{}]", sender().path.address) cancelTimer(HandOverRetryTimer) stay - case Event(HandOverDone, BecomingOldestData(Some(previousOldest))) ⇒ + case Event(HandOverDone, BecomingOldestData(Some(previousOldest))) => if (sender().path.address == previousOldest.address) gotoOldest() else { @@ -616,51 +616,51 @@ class ClusterSingletonManager( stay } - case Event(MemberDowned(m), _) if m.uniqueAddress == cluster.selfUniqueAddress ⇒ + case Event(MemberDowned(m), _) if m.uniqueAddress == cluster.selfUniqueAddress => logInfo("Self downed, stopping ClusterSingletonManager") stop() - case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress ⇒ + case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress => logInfo("Self removed, stopping ClusterSingletonManager") stop() - case Event(MemberRemoved(m, _), _) ⇒ + case Event(MemberRemoved(m, _), _) => scheduleDelayedMemberRemoved(m) stay - case Event(DelayedMemberRemoved(m), BecomingOldestData(Some(previousOldest))) if m.uniqueAddress == previousOldest ⇒ + case Event(DelayedMemberRemoved(m), BecomingOldestData(Some(previousOldest))) if m.uniqueAddress == previousOldest => logInfo("Previous oldest [{}] removed", previousOldest.address) addRemoved(m.uniqueAddress) gotoOldest() - case Event(TakeOverFromMe, BecomingOldestData(previousOldestOption)) ⇒ + case Event(TakeOverFromMe, BecomingOldestData(previousOldestOption)) => val senderAddress = sender().path.address // it would have been better to include the UniqueAddress in the TakeOverFromMe message, // but can't change due to backwards compatibility - cluster.state.members.collectFirst { case m if m.address == senderAddress ⇒ m.uniqueAddress } match { - case None ⇒ + cluster.state.members.collectFirst { case m if m.address == senderAddress => m.uniqueAddress } match { + case None => // from unknown node, ignore logInfo( "Ignoring TakeOver request from unknown node in BecomingOldest from [{}].", senderAddress) stay - case Some(senderUniqueAddress) ⇒ + case Some(senderUniqueAddress) => previousOldestOption match { - case Some(previousOldest) ⇒ + case Some(previousOldest) => if (previousOldest == senderUniqueAddress) sender() ! HandOverToMe else logInfo( "Ignoring TakeOver request in BecomingOldest from [{}]. Expected previous oldest [{}]", sender().path.address, previousOldest.address) stay - case None ⇒ + case None => sender() ! HandOverToMe stay using BecomingOldestData(Some(senderUniqueAddress)) } } - case Event(HandOverRetry(count), BecomingOldestData(previousOldestOption)) ⇒ + case Event(HandOverRetry(count), BecomingOldestData(previousOldestOption)) => if (count <= maxHandOverRetries) { logInfo("Retry [{}], sending HandOverToMe to [{}]", count, previousOldestOption.map(_.address)) - previousOldestOption.foreach(node ⇒ peer(node.address) ! HandOverToMe) + previousOldestOption.foreach(node => peer(node.address) ! HandOverToMe) setTimer(HandOverRetryTimer, HandOverRetry(count + 1), handOverRetryInterval, repeat = false) stay() } else if (previousOldestOption forall removed.contains) { @@ -690,48 +690,48 @@ class ClusterSingletonManager( } when(Oldest) { - case Event(OldestChanged(oldestOption), OldestData(singleton, singletonTerminated)) ⇒ + case Event(OldestChanged(oldestOption), OldestData(singleton, singletonTerminated)) => oldestChangedReceived = true logInfo("Oldest observed OldestChanged: [{} -> {}]", cluster.selfAddress, oldestOption.map(_.address)) oldestOption match { - case Some(a) if a == cluster.selfUniqueAddress ⇒ + case Some(a) if a == cluster.selfUniqueAddress => // already oldest stay - case Some(a) if !selfExited && removed.contains(a) ⇒ + case Some(a) if !selfExited && removed.contains(a) => // The member removal was not completed and the old removed node is considered // oldest again. Safest is to terminate the singleton instance and goto Younger. // This node will become oldest again when the other is removed again. gotoHandingOver(singleton, singletonTerminated, None) - case Some(a) ⇒ + case Some(a) => // send TakeOver request in case the new oldest doesn't know previous oldest peer(a.address) ! TakeOverFromMe setTimer(TakeOverRetryTimer, TakeOverRetry(1), handOverRetryInterval, repeat = false) goto(WasOldest) using WasOldestData(singleton, singletonTerminated, newOldestOption = Some(a)) - case None ⇒ + case None => // new oldest will initiate the hand-over setTimer(TakeOverRetryTimer, TakeOverRetry(1), handOverRetryInterval, repeat = false) goto(WasOldest) using WasOldestData(singleton, singletonTerminated, newOldestOption = None) } - case Event(HandOverToMe, OldestData(singleton, singletonTerminated)) ⇒ + case Event(HandOverToMe, OldestData(singleton, singletonTerminated)) => gotoHandingOver(singleton, singletonTerminated, Some(sender())) - case Event(TakeOverFromMe, _) ⇒ + case Event(TakeOverFromMe, _) => // already oldest, so confirm and continue like that sender() ! HandOverToMe stay - case Event(Terminated(ref), d @ OldestData(singleton, _)) if ref == singleton ⇒ + case Event(Terminated(ref), d @ OldestData(singleton, _)) if ref == singleton => logInfo("Singleton actor [{}] was terminated", singleton.path) stay using d.copy(singletonTerminated = true) - case Event(SelfExiting, _) ⇒ + case Event(SelfExiting, _) => selfMemberExited() // complete memberExitingProgress when handOverDone sender() ! Done // reply to ask stay - case Event(MemberDowned(m), OldestData(singleton, singletonTerminated)) if m.uniqueAddress == cluster.selfUniqueAddress ⇒ + case Event(MemberDowned(m), OldestData(singleton, singletonTerminated)) if m.uniqueAddress == cluster.selfUniqueAddress => if (singletonTerminated) { logInfo("Self downed, stopping ClusterSingletonManager") stop() @@ -742,7 +742,7 @@ class ClusterSingletonManager( } when(WasOldest) { - case Event(TakeOverRetry(count), WasOldestData(singleton, singletonTerminated, newOldestOption)) ⇒ + case Event(TakeOverRetry(count), WasOldestData(singleton, singletonTerminated, newOldestOption)) => if ((cluster.isTerminated || selfExited) && (newOldestOption.isEmpty || count > maxTakeOverRetries)) { if (singletonTerminated) stop() else gotoStopping(singleton) @@ -751,34 +751,34 @@ class ClusterSingletonManager( logInfo("Retry [{}], sending TakeOverFromMe to [{}]", count, newOldestOption.map(_.address)) else log.debug("Retry [{}], sending TakeOverFromMe to [{}]", count, newOldestOption.map(_.address)) - newOldestOption.foreach(node ⇒ peer(node.address) ! TakeOverFromMe) + newOldestOption.foreach(node => peer(node.address) ! TakeOverFromMe) setTimer(TakeOverRetryTimer, TakeOverRetry(count + 1), handOverRetryInterval, repeat = false) stay } else throw new ClusterSingletonManagerIsStuck(s"Expected hand-over to [$newOldestOption] never occurred") - case Event(HandOverToMe, WasOldestData(singleton, singletonTerminated, _)) ⇒ + case Event(HandOverToMe, WasOldestData(singleton, singletonTerminated, _)) => gotoHandingOver(singleton, singletonTerminated, Some(sender())) - case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress && !selfExited ⇒ + case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress && !selfExited => logInfo("Self removed, stopping ClusterSingletonManager") stop() - case Event(MemberRemoved(m, _), WasOldestData(singleton, singletonTerminated, Some(newOldest))) if !selfExited && m.uniqueAddress == newOldest ⇒ + case Event(MemberRemoved(m, _), WasOldestData(singleton, singletonTerminated, Some(newOldest))) if !selfExited && m.uniqueAddress == newOldest => addRemoved(m.uniqueAddress) gotoHandingOver(singleton, singletonTerminated, None) - case Event(Terminated(ref), d @ WasOldestData(singleton, _, _)) if ref == singleton ⇒ + case Event(Terminated(ref), d @ WasOldestData(singleton, _, _)) if ref == singleton => logInfo("Singleton actor [{}] was terminated", singleton.path) stay using d.copy(singletonTerminated = true) - case Event(SelfExiting, _) ⇒ + case Event(SelfExiting, _) => selfMemberExited() // complete memberExitingProgress when handOverDone sender() ! Done // reply to ask stay - case Event(MemberDowned(m), OldestData(singleton, singletonTerminated)) if m.uniqueAddress == cluster.selfUniqueAddress ⇒ + case Event(MemberDowned(m), OldestData(singleton, singletonTerminated)) if m.uniqueAddress == cluster.selfUniqueAddress => if (singletonTerminated) { logInfo("Self downed, stopping ClusterSingletonManager") stop() @@ -801,15 +801,15 @@ class ClusterSingletonManager( } when(HandingOver) { - case (Event(Terminated(ref), HandingOverData(singleton, handOverTo))) if ref == singleton ⇒ + case (Event(Terminated(ref), HandingOverData(singleton, handOverTo))) if ref == singleton => handOverDone(handOverTo) - case Event(HandOverToMe, HandingOverData(singleton, handOverTo)) if handOverTo == Some(sender()) ⇒ + case Event(HandOverToMe, HandingOverData(singleton, handOverTo)) if handOverTo == Some(sender()) => // retry sender() ! HandOverInProgress stay - case Event(SelfExiting, _) ⇒ + case Event(SelfExiting, _) => selfMemberExited() // complete memberExitingProgress when handOverDone sender() ! Done // reply to ask @@ -837,16 +837,16 @@ class ClusterSingletonManager( } when(Stopping) { - case (Event(Terminated(ref), StoppingData(singleton))) if ref == singleton ⇒ + case (Event(Terminated(ref), StoppingData(singleton))) if ref == singleton => logInfo("Singleton actor [{}] was terminated", singleton.path) stop() } when(End) { - case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress ⇒ + case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress => logInfo("Self removed, stopping ClusterSingletonManager") stop() - case Event(_: OldestChanged, _) ⇒ + case Event(_: OldestChanged, _) => // not interested anymore - waiting for removal stay } @@ -857,53 +857,53 @@ class ClusterSingletonManager( } whenUnhandled { - case Event(SelfExiting, _) ⇒ + case Event(SelfExiting, _) => selfMemberExited() memberExitingProgress.trySuccess(Done) sender() ! Done // reply to ask stay - case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress && !selfExited ⇒ + case Event(MemberRemoved(m, _), _) if m.uniqueAddress == cluster.selfUniqueAddress && !selfExited => logInfo("Self removed, stopping ClusterSingletonManager") stop() - case Event(MemberRemoved(m, _), _) ⇒ + case Event(MemberRemoved(m, _), _) => if (!selfExited) logInfo("Member removed [{}]", m.address) addRemoved(m.uniqueAddress) stay - case Event(DelayedMemberRemoved(m), _) ⇒ + case Event(DelayedMemberRemoved(m), _) => if (!selfExited) logInfo("Member removed [{}]", m.address) addRemoved(m.uniqueAddress) stay - case Event(TakeOverFromMe, _) ⇒ + case Event(TakeOverFromMe, _) => log.debug("Ignoring TakeOver request in [{}] from [{}].", stateName, sender().path.address) stay - case Event(Cleanup, _) ⇒ + case Event(Cleanup, _) => cleanupOverdueNotMemberAnyMore() stay - case Event(MemberDowned(m), _) ⇒ + case Event(MemberDowned(m), _) => if (m.uniqueAddress == cluster.selfUniqueAddress) logInfo("Self downed, waiting for removal") stay } onTransition { - case from → to ⇒ logInfo("ClusterSingletonManager state change [{} -> {}]", from, to) + case from -> to => logInfo("ClusterSingletonManager state change [{} -> {}]", from, to) } onTransition { - case _ → BecomingOldest ⇒ setTimer(HandOverRetryTimer, HandOverRetry(1), handOverRetryInterval, repeat = false) + case _ -> BecomingOldest => setTimer(HandOverRetryTimer, HandOverRetry(1), handOverRetryInterval, repeat = false) } onTransition { - case BecomingOldest → _ ⇒ cancelTimer(HandOverRetryTimer) - case WasOldest → _ ⇒ cancelTimer(TakeOverRetryTimer) + case BecomingOldest -> _ => cancelTimer(HandOverRetryTimer) + case WasOldest -> _ => cancelTimer(TakeOverRetryTimer) } onTransition { - case _ → (Younger | Oldest) ⇒ getNextOldestChanged() + case _ -> (Younger | Oldest) => getNextOldestChanged() } onTransition { - case _ → (Younger | End) if removed.contains(cluster.selfUniqueAddress) ⇒ + case _ -> (Younger | End) if removed.contains(cluster.selfUniqueAddress) => logInfo("Self removed, stopping ClusterSingletonManager") // note that FSM.stop() can't be used in onTransition context.stop(self) diff --git a/akka-cluster-tools/src/main/scala/akka/cluster/singleton/ClusterSingletonProxy.scala b/akka-cluster-tools/src/main/scala/akka/cluster/singleton/ClusterSingletonProxy.scala index ec7a254bcb..69b1f64a6f 100644 --- a/akka-cluster-tools/src/main/scala/akka/cluster/singleton/ClusterSingletonProxy.scala +++ b/akka-cluster-tools/src/main/scala/akka/cluster/singleton/ClusterSingletonProxy.scala @@ -180,8 +180,8 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste } private val targetDcRole = settings.dataCenter match { - case Some(t) ⇒ ClusterSettings.DcRolePrefix + t - case None ⇒ ClusterSettings.DcRolePrefix + cluster.settings.SelfDataCenter + case Some(t) => ClusterSettings.DcRolePrefix + t + case None => ClusterSettings.DcRolePrefix + cluster.settings.SelfDataCenter } def matchingRole(member: Member): Boolean = @@ -189,9 +189,9 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste def handleInitial(state: CurrentClusterState): Unit = { trackChange { - () ⇒ + () => membersByAge = immutable.SortedSet.empty(ageOrdering) union state.members.collect { - case m if m.status == MemberStatus.Up && matchingRole(m) ⇒ m + case m if m.status == MemberStatus.Up && matchingRole(m) => m } } } @@ -209,7 +209,7 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste identifyTimer = Some(context.system.scheduler.schedule(0 milliseconds, singletonIdentificationInterval, self, ClusterSingletonProxy.TryToIdentifySingleton)) } - def trackChange(block: () ⇒ Unit): Unit = { + def trackChange(block: () => Unit): Unit = { val before = membersByAge.headOption block() val after = membersByAge.headOption @@ -223,7 +223,7 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste */ def add(m: Member): Unit = { if (matchingRole(m)) - trackChange { () ⇒ + trackChange { () => // replace, it's possible that the upNumber is changed membersByAge = membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) membersByAge += m @@ -236,7 +236,7 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste */ def remove(m: Member): Unit = { if (matchingRole(m)) - trackChange { () ⇒ + trackChange { () => // filter, it's possible that the upNumber is changed membersByAge = membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) } @@ -244,52 +244,52 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste def receive = { // cluster logic - case state: CurrentClusterState ⇒ handleInitial(state) - case MemberUp(m) ⇒ add(m) - case MemberExited(m) ⇒ remove(m) - case MemberRemoved(m, _) ⇒ + case state: CurrentClusterState => handleInitial(state) + case MemberUp(m) => add(m) + case MemberExited(m) => remove(m) + case MemberRemoved(m, _) => if (m.uniqueAddress == cluster.selfUniqueAddress) context.stop(self) else remove(m) - case _: MemberEvent ⇒ // do nothing + case _: MemberEvent => // do nothing // singleton identification logic - case ActorIdentity(identifyId, Some(s)) ⇒ + case ActorIdentity(identifyId, Some(s)) => // if the new singleton is defined, deliver all buffered messages log.info("Singleton identified at [{}]", s.path) singleton = Some(s) context.watch(s) cancelTimer() sendBuffered() - case _: ActorIdentity ⇒ // do nothing - case ClusterSingletonProxy.TryToIdentifySingleton ⇒ + case _: ActorIdentity => // do nothing + case ClusterSingletonProxy.TryToIdentifySingleton => identifyTimer match { - case Some(_) ⇒ - membersByAge.headOption foreach { oldest ⇒ + case Some(_) => + membersByAge.headOption foreach { oldest => val singletonAddress = RootActorPath(oldest.address) / singletonPath log.debug("Trying to identify singleton at [{}]", singletonAddress) context.actorSelection(singletonAddress) ! Identify(identifyId) } - case _ ⇒ + case _ => // ignore, if the timer is not present it means we have successfully identified } - case Terminated(ref) ⇒ + case Terminated(ref) => if (singleton.contains(ref)) { // buffering mode, identification of new will start when old node is removed singleton = None } // forwarding/stashing logic - case msg: Any ⇒ + case msg: Any => singleton match { - case Some(s) ⇒ + case Some(s) => if (log.isDebugEnabled) log.debug( "Forwarding message of type [{}] to current singleton instance at [{}]", Logging.simpleName(msg.getClass), s.path) s forward msg - case None ⇒ + case None => buffer(msg) } } @@ -310,7 +310,7 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste def sendBuffered(): Unit = { log.debug("Sending buffered messages to current singleton instance") val target = singleton.get - buffer.foreach((msg, snd) ⇒ target.tell(msg, snd)) + buffer.foreach((msg, snd) => target.tell(msg, snd)) buffer = MessageBuffer.empty } } diff --git a/akka-cluster-tools/src/main/scala/akka/cluster/singleton/protobuf/ClusterSingletonMessageSerializer.scala b/akka-cluster-tools/src/main/scala/akka/cluster/singleton/protobuf/ClusterSingletonMessageSerializer.scala index 25180288de..33ac1038a1 100644 --- a/akka-cluster-tools/src/main/scala/akka/cluster/singleton/protobuf/ClusterSingletonMessageSerializer.scala +++ b/akka-cluster-tools/src/main/scala/akka/cluster/singleton/protobuf/ClusterSingletonMessageSerializer.scala @@ -31,34 +31,34 @@ private[akka] class ClusterSingletonMessageSerializer(val system: ExtendedActorS private val emptyByteArray = Array.empty[Byte] - private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] ⇒ AnyRef]( - HandOverToMeManifest → { _ ⇒ HandOverToMe }, - HandOverInProgressManifest → { _ ⇒ HandOverInProgress }, - HandOverDoneManifest → { _ ⇒ HandOverDone }, - TakeOverFromMeManifest → { _ ⇒ TakeOverFromMe }) + private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] => AnyRef]( + HandOverToMeManifest -> { _ => HandOverToMe }, + HandOverInProgressManifest -> { _ => HandOverInProgress }, + HandOverDoneManifest -> { _ => HandOverDone }, + TakeOverFromMeManifest -> { _ => TakeOverFromMe }) override def manifest(obj: AnyRef): String = obj match { - case HandOverToMe ⇒ HandOverToMeManifest - case HandOverInProgress ⇒ HandOverInProgressManifest - case HandOverDone ⇒ HandOverDoneManifest - case TakeOverFromMe ⇒ TakeOverFromMeManifest - case _ ⇒ + case HandOverToMe => HandOverToMeManifest + case HandOverInProgress => HandOverInProgressManifest + case HandOverDone => HandOverDoneManifest + case TakeOverFromMe => TakeOverFromMeManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case HandOverToMe ⇒ emptyByteArray - case HandOverInProgress ⇒ emptyByteArray - case HandOverDone ⇒ emptyByteArray - case TakeOverFromMe ⇒ emptyByteArray - case _ ⇒ + case HandOverToMe => emptyByteArray + case HandOverInProgress => emptyByteArray + case HandOverDone => emptyByteArray + case TakeOverFromMe => emptyByteArray + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = fromBinaryMap.get(manifest) match { - case Some(f) ⇒ f(bytes) - case None ⇒ throw new NotSerializableException( + case Some(f) => f(bytes) + case None => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientHandoverSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientHandoverSpec.scala index 4503e56a2f..76cb2418d8 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientHandoverSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientHandoverSpec.scala @@ -50,7 +50,7 @@ class ClusterClientHandoverSpec extends MultiNodeSpec(ClusterClientHandoverSpec) enterBarrier(from.name + "-joined") } - def initialContacts: Set[ActorPath] = Set(first, second).map { r ⇒ + def initialContacts: Set[ActorPath] = Set(first, second).map { r => node(r) / "system" / "receptionist" } diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientSpec.scala index ddfeae0603..1277499c91 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientSpec.scala @@ -51,9 +51,9 @@ object ClusterClientSpec extends MultiNodeConfig { class TestService(testActor: ActorRef) extends Actor { def receive = { - case "shutdown" ⇒ + case "shutdown" => context.system.terminate() - case msg ⇒ + case msg => testActor forward msg sender() ! Reply(msg + "-ack", Cluster(context.system).selfAddress) } @@ -61,7 +61,7 @@ object ClusterClientSpec extends MultiNodeConfig { class Service extends Actor { def receive = { - case msg ⇒ sender() ! msg + case msg => sender() ! msg } } @@ -74,13 +74,13 @@ object ClusterClientSpec extends MultiNodeConfig { receiveWithContactPoints(Set.empty) def receiveWithContactPoints(contactPoints: Set[ActorPath]): Receive = { - case ContactPoints(cps) ⇒ + case ContactPoints(cps) => context.become(receiveWithContactPoints(cps)) // Now do something with the up-to-date "cps" - case ContactPointAdded(cp) ⇒ + case ContactPointAdded(cp) => context.become(receiveWithContactPoints(contactPoints + cp)) // Now do something with an up-to-date "contactPoints + cp" - case ContactPointRemoved(cp) ⇒ + case ContactPointRemoved(cp) => context.become(receiveWithContactPoints(contactPoints - cp)) // Now do something with an up-to-date "contactPoints - cp" } @@ -97,9 +97,9 @@ object ClusterClientSpec extends MultiNodeConfig { import TestClientListener._ override def receiveWithContactPoints(contactPoints: Set[ActorPath]): Receive = { - case GetLatestContactPoints ⇒ + case GetLatestContactPoints => sender() ! LatestContactPoints(contactPoints) - case msg: Any ⇒ + case msg: Any => super.receiveWithContactPoints(contactPoints)(msg) } } @@ -113,13 +113,13 @@ object ClusterClientSpec extends MultiNodeConfig { receiveWithClusterClients(Set.empty) def receiveWithClusterClients(clusterClients: Set[ActorRef]): Receive = { - case ClusterClients(cs) ⇒ + case ClusterClients(cs) => context.become(receiveWithClusterClients(cs)) // Now do something with the up-to-date "c" - case ClusterClientUp(c) ⇒ + case ClusterClientUp(c) => context.become(receiveWithClusterClients(clusterClients + c)) // Now do something with an up-to-date "clusterClients + c" - case ClusterClientUnreachable(c) ⇒ + case ClusterClientUnreachable(c) => context.become(receiveWithClusterClients(clusterClients - c)) // Now do something with an up-to-date "clusterClients - c" } @@ -136,9 +136,9 @@ object ClusterClientSpec extends MultiNodeConfig { import TestReceptionistListener._ override def receiveWithClusterClients(clusterClients: Set[ActorRef]): Receive = { - case GetLatestClusterClients ⇒ + case GetLatestClusterClients => sender() ! LatestClusterClients(clusterClients) - case msg: Any ⇒ + case msg: Any => super.receiveWithClusterClients(clusterClients)(msg) } } @@ -176,7 +176,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod def roleName(addr: Address): Option[RoleName] = remainingServerRoleNames.find(node(_).address == addr) - def initialContacts = (remainingServerRoleNames - first - fourth).map { r ⇒ + def initialContacts = (remainingServerRoleNames - first - fourth).map { r => node(r) / "system" / "receptionist" } @@ -329,7 +329,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod // We need to slow down things otherwise our receptionists can sometimes tell us // that our unreachableContact is unreachable before we get a chance to // subscribe to events. - expectedRoles.foreach { role ⇒ + expectedRoles.foreach { role => testConductor.blackhole(client, role, Direction.Both).await } @@ -339,13 +339,13 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod val probe = TestProbe() c.tell(SubscribeContactPoints, probe.ref) - expectedRoles.foreach { role ⇒ + expectedRoles.foreach { role => testConductor.passThrough(client, role, Direction.Both).await } probe.fishForMessage(10.seconds, "removal") { - case ContactPointRemoved(`unreachableContact`) ⇒ true - case _ ⇒ false + case ContactPointRemoved(`unreachableContact`) => true + case _ => false } } enterBarrier("after-7") @@ -367,8 +367,8 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod val reply = expectMsgType[Reply] reply.msg should be("bonjour-ack") val receptionistRoleName = roleName(reply.node) match { - case Some(r) ⇒ r - case None ⇒ fail("unexpected missing roleName: " + reply.node) + case Some(r) => r + case None => fail("unexpected missing roleName: " + reply.node) } testConductor.exit(receptionistRoleName, 0).await remainingServerRoleNames -= receptionistRoleName @@ -380,8 +380,8 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod } enterBarrier("verifed-3") receiveWhile(2 seconds) { - case "hi again" ⇒ - case other ⇒ fail("unexpected message: " + other) + case "hi again" => + case other => fail("unexpected message: " + other) } enterBarrier("verifed-4") runOn(client) { @@ -406,11 +406,11 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod val reply = expectMsgType[Reply] reply.msg should be("bonjour2-ack") val receptionistRoleName = roleName(reply.node) match { - case Some(r) ⇒ r - case None ⇒ fail("unexpected missing roleName: " + reply.node) + case Some(r) => r + case None => fail("unexpected missing roleName: " + reply.node) } // shutdown all but the one that the client is connected to - remainingServerRoleNames.foreach { r ⇒ + remainingServerRoleNames.foreach { r => if (r != receptionistRoleName) testConductor.exit(r, 0).await } @@ -441,7 +441,7 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod "re-establish connection to receptionist after server restart" in within(30 seconds) { runOn(client) { remainingServerRoleNames.size should ===(1) - val remainingContacts = remainingServerRoleNames.map { r ⇒ + val remainingContacts = remainingServerRoleNames.map { r => node(r) / "system" / "receptionist" } val c = system.actorOf(ClusterClient.props( diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientStopSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientStopSpec.scala index e9fd523ef9..b22e01819c 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientStopSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/client/ClusterClientStopSpec.scala @@ -34,7 +34,7 @@ object ClusterClientStopSpec extends MultiNodeConfig { class Service extends Actor { def receive = { - case msg ⇒ sender() ! msg + case msg => sender() ! msg } } } @@ -64,7 +64,7 @@ class ClusterClientStopSpec extends MultiNodeSpec(ClusterClientStopSpec) with ST } } - def initialContacts = Set(first, second).map { r ⇒ + def initialContacts = Set(first, second).map { r => node(r) / "system" / "receptionist" } diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/pubsub/DistributedPubSubMediatorSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/pubsub/DistributedPubSubMediatorSpec.scala index 1ebb966740..2855b2c739 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/pubsub/DistributedPubSubMediatorSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/pubsub/DistributedPubSubMediatorSpec.scala @@ -50,14 +50,14 @@ object DistributedPubSubMediatorSpec extends MultiNodeConfig { import DistributedPubSubMediator._ def receive = { - case Whisper(path, msg) ⇒ mediator ! Send(path, msg, localAffinity = true) - case Talk(path, msg) ⇒ mediator ! SendToAll(path, msg) - case TalkToOthers(path, msg) ⇒ mediator ! SendToAll(path, msg, allButSelf = true) - case Shout(topic, msg) ⇒ mediator ! Publish(topic, msg) - case ShoutToGroups(topic, msg) ⇒ mediator ! Publish(topic, msg, true) - case JoinGroup(topic, group) ⇒ mediator ! Subscribe(topic, Some(group), self) - case ExitGroup(topic, group) ⇒ mediator ! Unsubscribe(topic, Some(group), self) - case msg ⇒ testActor ! msg + case Whisper(path, msg) => mediator ! Send(path, msg, localAffinity = true) + case Talk(path, msg) => mediator ! SendToAll(path, msg) + case TalkToOthers(path, msg) => mediator ! SendToAll(path, msg, allButSelf = true) + case Shout(topic, msg) => mediator ! Publish(topic, msg) + case ShoutToGroups(topic, msg) => mediator ! Publish(topic, msg, true) + case JoinGroup(topic, group) => mediator ! Subscribe(topic, Some(group), self) + case ExitGroup(topic, group) => mediator ! Unsubscribe(topic, Some(group), self) + case msg => testActor ! msg } } @@ -68,7 +68,7 @@ object DistributedPubSubMediatorSpec extends MultiNodeConfig { val mediator = DistributedPubSub(context.system).mediator def receive = { - case in: String ⇒ + case in: String => val out = in.toUpperCase mediator ! Publish("content", out) } @@ -83,9 +83,9 @@ object DistributedPubSubMediatorSpec extends MultiNodeConfig { mediator ! Subscribe("content", self) def receive = { - case s: String ⇒ + case s: String => log.info("Got {}", s) - case SubscribeAck(Subscribe("content", None, `self`)) ⇒ + case SubscribeAck(Subscribe("content", None, `self`)) => log.info("subscribing") } } @@ -98,7 +98,7 @@ object DistributedPubSubMediatorSpec extends MultiNodeConfig { val mediator = DistributedPubSub(context.system).mediator def receive = { - case in: String ⇒ + case in: String => val out = in.toUpperCase mediator ! Send(path = "/user/destination", msg = out, localAffinity = true) } @@ -113,7 +113,7 @@ object DistributedPubSubMediatorSpec extends MultiNodeConfig { mediator ! Put(self) def receive = { - case s: String ⇒ + case s: String => log.info("Got {}", s) } } @@ -147,7 +147,7 @@ class DistributedPubSubMediatorSpec extends MultiNodeSpec(DistributedPubSubMedia def createChatUser(name: String): ActorRef = { var a = system.actorOf(Props(classOf[TestChatUser], mediator, testActor), name) - chatUsers += (name → a) + chatUsers += (name -> a) a } @@ -319,7 +319,7 @@ class DistributedPubSubMediatorSpec extends MultiNodeSpec(DistributedPubSubMedia runOn(first) { val names = receiveWhile(messages = 2) { - case "hello all" ⇒ lastSender.path.name + case "hello all" => lastSender.path.name } names.toSet should ===(Set("u8", "u9")) } @@ -474,18 +474,18 @@ class DistributedPubSubMediatorSpec extends MultiNodeSpec(DistributedPubSubMedia // this test is configured with max-delta-elements = 500 val many = 1010 runOn(first) { - for (i ← 0 until many) + for (i <- 0 until many) mediator ! Put(createChatUser("u" + (1000 + i))) mediator ! Status(versions = Map.empty, isReplyToStatus = false) val deltaBuckets1 = expectMsgType[Delta].buckets deltaBuckets1.map(_.content.size).sum should ===(500) - mediator ! Status(versions = deltaBuckets1.map(b ⇒ b.owner → b.version).toMap, isReplyToStatus = false) + mediator ! Status(versions = deltaBuckets1.map(b => b.owner -> b.version).toMap, isReplyToStatus = false) val deltaBuckets2 = expectMsgType[Delta].buckets deltaBuckets1.map(_.content.size).sum should ===(500) - mediator ! Status(versions = deltaBuckets2.map(b ⇒ b.owner → b.version).toMap, isReplyToStatus = false) + mediator ! Status(versions = deltaBuckets2.map(b => b.owner -> b.version).toMap, isReplyToStatus = false) val deltaBuckets3 = expectMsgType[Delta].buckets deltaBuckets3.map(_.content.size).sum should ===(10 + 9 + 2 + many - 500 - 500) @@ -559,7 +559,7 @@ class DistributedPubSubMediatorSpec extends MultiNodeSpec(DistributedPubSubMedia mediator ! GetTopics expectMsgPF() { case CurrentTopics(topics) if topics.contains("topic_a1") - && topics.contains("topic_a2") ⇒ true + && topics.contains("topic_a2") => true } } diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/pubsub/DistributedPubSubRestartSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/pubsub/DistributedPubSubRestartSpec.scala index 19889a1bed..3e951e2f88 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/pubsub/DistributedPubSubRestartSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/pubsub/DistributedPubSubRestartSpec.scala @@ -40,7 +40,7 @@ object DistributedPubSubRestartSpec extends MultiNodeConfig { class Shutdown extends Actor { def receive = { - case "shutdown" ⇒ context.system.terminate() + case "shutdown" => context.system.terminate() } } diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerChaosSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerChaosSpec.scala index 64f21a64fa..44d0cbe4a8 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerChaosSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerChaosSpec.scala @@ -46,7 +46,7 @@ object ClusterSingletonManagerChaosSpec extends MultiNodeConfig { testActor ! EchoStarted def receive = { - case _ ⇒ sender() ! self + case _ => sender() ! self } } } @@ -82,7 +82,7 @@ class ClusterSingletonManagerChaosSpec extends MultiNodeSpec(ClusterSingletonMan def crash(roles: RoleName*): Unit = { runOn(controller) { - roles foreach { r ⇒ + roles foreach { r => log.info("Shutdown [{}]", node(r).address) testConductor.exit(r, 0).await } @@ -97,7 +97,7 @@ class ClusterSingletonManagerChaosSpec extends MultiNodeSpec(ClusterSingletonMan memberProbe.expectMsgType[MemberUp](15.seconds).member.address should ===(node(nodes.head).address) } runOn(nodes.head) { - memberProbe.receiveN(nodes.size, 15.seconds).collect { case MemberUp(m) ⇒ m.address }.toSet should ===( + memberProbe.receiveN(nodes.size, 15.seconds).collect { case MemberUp(m) => m.address }.toSet should ===( nodes.map(node(_).address).toSet) } enterBarrier(nodes.head.name + "-up") diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerDownedSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerDownedSpec.scala index 656e2dac6f..5568d4aa57 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerDownedSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerDownedSpec.scala @@ -46,7 +46,7 @@ object ClusterSingletonManagerDownedSpec extends MultiNodeConfig { } def receive = { - case _ ⇒ sender() ! self + case _ => sender() ! self } } } diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerLeaveSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerLeaveSpec.scala index a8d3fef2f9..e642d77d29 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerLeaveSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerLeaveSpec.scala @@ -42,10 +42,10 @@ object ClusterSingletonManagerLeaveSpec extends MultiNodeConfig { } def receive = { - case "stop" ⇒ + case "stop" => testActor ! "stop" context.stop(self) - case _ ⇒ + case _ => sender() ! self } } @@ -105,14 +105,14 @@ class ClusterSingletonManagerLeaveSpec extends MultiNodeSpec(ClusterSingletonMan join(second, first) runOn(first, second) { within(10.seconds) { - awaitAssert(cluster.state.members.count(m ⇒ m.status == MemberStatus.Up) should be(2)) + awaitAssert(cluster.state.members.count(m => m.status == MemberStatus.Up) should be(2)) } } enterBarrier("second-up") join(third, first) within(10.seconds) { - awaitAssert(cluster.state.members.count(m ⇒ m.status == MemberStatus.Up) should be(3)) + awaitAssert(cluster.state.members.count(m => m.status == MemberStatus.Up) should be(3)) } enterBarrier("all-up") diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerSpec.scala index efac73f350..8d329766cf 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerSpec.scala @@ -72,35 +72,35 @@ object ClusterSingletonManagerSpec extends MultiNodeConfig { def receive = idle def idle: Receive = { - case RegisterConsumer ⇒ + case RegisterConsumer => log.info("RegisterConsumer: [{}]", sender().path) sender() ! RegistrationOk context.become(active(sender())) - case UnregisterConsumer ⇒ + case UnregisterConsumer => log.info("UnexpectedUnregistration: [{}]", sender().path) sender() ! UnexpectedUnregistration context stop self - case Reset ⇒ sender() ! ResetOk - case msg ⇒ // no consumer, drop + case Reset => sender() ! ResetOk + case msg => // no consumer, drop } def active(consumer: ActorRef): Receive = { - case UnregisterConsumer if sender() == consumer ⇒ + case UnregisterConsumer if sender() == consumer => log.info("UnregistrationOk: [{}]", sender().path) sender() ! UnregistrationOk context.become(idle) - case UnregisterConsumer ⇒ + case UnregisterConsumer => log.info("UnexpectedUnregistration: [{}], expected [{}]", sender().path, consumer.path) sender() ! UnexpectedUnregistration context stop self - case RegisterConsumer ⇒ + case RegisterConsumer => log.info("Unexpected RegisterConsumer [{}], active consumer [{}]", sender().path, consumer.path) sender() ! UnexpectedRegistration context stop self - case Reset ⇒ + case Reset => context.become(idle) sender() ! ResetOk - case msg ⇒ consumer ! msg + case msg => consumer ! msg } } @@ -132,22 +132,22 @@ object ClusterSingletonManagerSpec extends MultiNodeConfig { } def receive = { - case n: Int if n <= current ⇒ + case n: Int if n <= current => context.stop(self) - case n: Int ⇒ + case n: Int => current = n delegateTo ! n - case message @ (RegistrationOk | UnexpectedRegistration) ⇒ + case message @ (RegistrationOk | UnexpectedRegistration) => delegateTo ! message - case GetCurrent ⇒ + case GetCurrent => sender() ! current //#consumer-end - case End ⇒ + case End => queue ! UnregisterConsumer - case UnregistrationOk ⇒ + case UnregistrationOk => stoppedBeforeUnregistration = false context stop self - case Ping ⇒ + case Ping => sender() ! Pong //#consumer-end } @@ -204,7 +204,7 @@ class ClusterSingletonManagerSpec extends MultiNodeSpec(ClusterSingletonManagerS memberProbe.expectMsgType[MemberUp](15.seconds).member.address should ===(node(nodes.head).address) } runOn(nodes.head) { - memberProbe.receiveN(nodes.size, 15.seconds).collect { case MemberUp(m) ⇒ m.address }.toSet should ===( + memberProbe.receiveN(nodes.size, 15.seconds).collect { case MemberUp(m) => m.address }.toSet should ===( nodes.map(node(_).address).toSet) } enterBarrier(nodes.head.name + "-up") @@ -303,7 +303,7 @@ class ClusterSingletonManagerSpec extends MultiNodeSpec(ClusterSingletonManagerS runOn(oldest) { expectMsg(5.seconds, msg) } - runOn(roles.filterNot(r ⇒ r == oldest || r == controller || r == observer): _*) { + runOn(roles.filterNot(r => r == oldest || r == controller || r == observer): _*) { expectNoMsg(1 second) } enterBarrier("after-" + msg + "-verified") @@ -313,7 +313,7 @@ class ClusterSingletonManagerSpec extends MultiNodeSpec(ClusterSingletonManagerS runOn(controller) { queue ! Reset expectMsg(ResetOk) - roles foreach { r ⇒ + roles foreach { r => log.info("Shutdown [{}]", node(r).address) testConductor.exit(r, 0).await } @@ -400,8 +400,8 @@ class ClusterSingletonManagerSpec extends MultiNodeSpec(ClusterSingletonManagerS runOn(leaveRole) { system.actorSelection("/user/consumer").tell(Identify("singleton"), identifyProbe.ref) identifyProbe.expectMsgPF() { - case ActorIdentity("singleton", None) ⇒ // already terminated - case ActorIdentity("singleton", Some(singleton)) ⇒ + case ActorIdentity("singleton", None) => // already terminated + case ActorIdentity("singleton", Some(singleton)) => watch(singleton) expectTerminated(singleton) } diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerStartupSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerStartupSpec.scala index 4d046da9f1..b6de14cbf1 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerStartupSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/ClusterSingletonManagerStartupSpec.scala @@ -36,7 +36,7 @@ object ClusterSingletonManagerStartupSpec extends MultiNodeConfig { */ class Echo(testActor: ActorRef) extends Actor { def receive = { - case _ ⇒ + case _ => sender() ! self } } diff --git a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/MultiDcSingletonManagerSpec.scala b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/MultiDcSingletonManagerSpec.scala index 69ab1778c3..4f5b1566ba 100644 --- a/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/MultiDcSingletonManagerSpec.scala +++ b/akka-cluster-tools/src/multi-jvm/scala/akka/cluster/singleton/MultiDcSingletonManagerSpec.scala @@ -55,7 +55,7 @@ class MultiDcSingleton extends Actor with ActorLogging { val cluster = Cluster(context.system) override def receive: Receive = { - case Ping ⇒ + case Ping => sender() ! Pong(cluster.settings.SelfDataCenter, cluster.selfAddress, cluster.selfRoles) } } diff --git a/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/DistributedPubSubMediatorDeadLettersSpec.scala b/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/DistributedPubSubMediatorDeadLettersSpec.scala index 514071e87f..a03357fb8c 100644 --- a/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/DistributedPubSubMediatorDeadLettersSpec.scala +++ b/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/DistributedPubSubMediatorDeadLettersSpec.scala @@ -21,7 +21,7 @@ object DistributedPubSubMediatorDeadLettersSpec { """ } -trait DeadLettersProbe { this: TestKitBase ⇒ +trait DeadLettersProbe { this: TestKitBase => val deadLettersProbe = TestProbe() system.eventStream.subscribe(deadLettersProbe.ref, classOf[DeadLetter]) diff --git a/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/DistributedPubSubMediatorRouterSpec.scala b/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/DistributedPubSubMediatorRouterSpec.scala index 2aa422c9ff..c6fe3d1093 100644 --- a/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/DistributedPubSubMediatorRouterSpec.scala +++ b/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/DistributedPubSubMediatorRouterSpec.scala @@ -28,7 +28,7 @@ object DistributedPubSubMediatorRouterSpec { """ } -trait DistributedPubSubMediatorRouterSpec { this: WordSpecLike with TestKit with ImplicitSender ⇒ +trait DistributedPubSubMediatorRouterSpec { this: WordSpecLike with TestKit with ImplicitSender => def nonUnwrappingPubSub(mediator: ActorRef, testActor: ActorRef, msg: Any): Unit = { val path = testActor.path.toStringWithoutAddress diff --git a/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/protobuf/DistributedPubSubMessageSerializerSpec.scala b/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/protobuf/DistributedPubSubMessageSerializerSpec.scala index e7ff4a85fa..a821810907 100644 --- a/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/protobuf/DistributedPubSubMessageSerializerSpec.scala +++ b/akka-cluster-tools/src/test/scala/akka/cluster/pubsub/protobuf/DistributedPubSubMessageSerializerSpec.scala @@ -31,11 +31,11 @@ class DistributedPubSubMessageSerializerSpec extends AkkaSpec { val u2 = system.actorOf(Props.empty, "u2") val u3 = system.actorOf(Props.empty, "u3") val u4 = system.actorOf(Props.empty, "u4") - checkSerialization(Status(Map(address1 → 3, address2 → 17, address3 → 5), isReplyToStatus = true)) + checkSerialization(Status(Map(address1 -> 3, address2 -> 17, address3 -> 5), isReplyToStatus = true)) checkSerialization(Delta(List( - Bucket(address1, 3, TreeMap("/user/u1" → ValueHolder(2, Some(u1)), "/user/u2" → ValueHolder(3, Some(u2)))), - Bucket(address2, 17, TreeMap("/user/u3" → ValueHolder(17, Some(u3)))), - Bucket(address3, 5, TreeMap("/user/u4" → ValueHolder(4, Some(u4)), "/user/u5" → ValueHolder(5, None)))))) + Bucket(address1, 3, TreeMap("/user/u1" -> ValueHolder(2, Some(u1)), "/user/u2" -> ValueHolder(3, Some(u2)))), + Bucket(address2, 17, TreeMap("/user/u3" -> ValueHolder(17, Some(u3)))), + Bucket(address3, 5, TreeMap("/user/u4" -> ValueHolder(4, Some(u4)), "/user/u5" -> ValueHolder(5, None)))))) checkSerialization(Send("/user/u3", "hello", localAffinity = true)) checkSerialization(SendToAll("/user/u3", "hello", allButSelf = true)) checkSerialization(Publish("mytopic", "hello")) diff --git a/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonLeavingSpeedSpec.scala b/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonLeavingSpeedSpec.scala index da25391de1..ab45001640 100644 --- a/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonLeavingSpeedSpec.scala +++ b/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonLeavingSpeedSpec.scala @@ -34,7 +34,7 @@ object ClusterSingletonLeavingSpeedSpec { } override def receive: Receive = { - case msg ⇒ sender() ! msg + case msg => sender() ! msg } } } @@ -61,7 +61,7 @@ class ClusterSingletonLeavingSpeedSpec extends AkkaSpec(""" } """) { - private val systems = (1 to 3).map { n ⇒ + private val systems = (1 to 3).map { n => val roleConfig = ConfigFactory.parseString(s"""akka.cluster.roles=[role-${n % 3}]""") ActorSystem(system.name, roleConfig.withFallback(system.settings.config)) } @@ -90,7 +90,7 @@ class ClusterSingletonLeavingSpeedSpec extends AkkaSpec(""" "ClusterSingleton that is leaving" must { "join cluster" in { - systems.indices.foreach { i ⇒ + systems.indices.foreach { i => join(systems(i), systems.head, probes(i).ref) } // leader is most likely on system, lowest port @@ -101,7 +101,7 @@ class ClusterSingletonLeavingSpeedSpec extends AkkaSpec(""" "quickly hand-over to next oldest" in { - val durations = systems.indices.take(1).map { i ⇒ + val durations = systems.indices.take(1).map { i => val t0 = System.nanoTime() val leaveAddress = Cluster(systems(i)).selfAddress CoordinatedShutdown(systems(i)).run(CoordinatedShutdown.ClusterLeavingReason) @@ -115,7 +115,7 @@ class ClusterSingletonLeavingSpeedSpec extends AkkaSpec(""" awaitAssert { Cluster(systems(i)).isTerminated should ===(true) Cluster(system).state.members.map(_.address) should not contain leaveAddress - systems.foreach { sys ⇒ + systems.foreach { sys => if (!Cluster(sys).isTerminated) Cluster(sys).state.members.map(_.address) should not contain leaveAddress } @@ -129,7 +129,7 @@ class ClusterSingletonLeavingSpeedSpec extends AkkaSpec(""" } durations.zipWithIndex.foreach { - case ((stoppedDuration, startedDuration), i) ⇒ + case ((stoppedDuration, startedDuration), i) => println(s"Singleton $i stopped in ${stoppedDuration.toMillis} ms, started in ${startedDuration.toMillis} ms, " + s"diff ${(startedDuration - stoppedDuration).toMillis} ms") } diff --git a/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonProxySpec.scala b/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonProxySpec.scala index 05b61e4748..46995df172 100644 --- a/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonProxySpec.scala +++ b/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonProxySpec.scala @@ -18,7 +18,7 @@ class ClusterSingletonProxySpec extends WordSpecLike with Matchers with BeforeAn val seed = new ActorSys() val testSystems = { - val joiners = (0 until 4).map(n ⇒ new ActorSys(joinTo = Some(seed.cluster.selfAddress))) + val joiners = (0 until 4).map(n => new ActorSys(joinTo = Some(seed.cluster.selfAddress))) joiners :+ seed } @@ -29,7 +29,7 @@ class ClusterSingletonProxySpec extends WordSpecLike with Matchers with BeforeAn } } - override def afterAll(): Unit = testSystems.foreach { sys ⇒ + override def afterAll(): Unit = testSystems.foreach { sys => TestKit.shutdownActorSystem(sys.system) } } @@ -87,7 +87,7 @@ object ClusterSingletonProxySpec { log.info("Singleton created on {}", Cluster(context.system).selfAddress) def receive: Actor.Receive = { - case msg ⇒ + case msg => log.info(s"Got $msg") sender() ! "Got " + msg } diff --git a/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonRestart2Spec.scala b/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonRestart2Spec.scala index f08de017fc..81478bc822 100644 --- a/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonRestart2Spec.scala +++ b/akka-cluster-tools/src/test/scala/akka/cluster/singleton/ClusterSingletonRestart2Spec.scala @@ -22,7 +22,7 @@ object ClusterSingletonRestart2Spec { class Singleton extends Actor { def receive = { - case _ ⇒ sender() ! Cluster(context.system).selfUniqueAddress + case _ => sender() ! Cluster(context.system).selfUniqueAddress } } } diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/internal/ReplicatorBehavior.scala b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/internal/ReplicatorBehavior.scala index b9f9aa5a2f..52a4b5c03b 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/internal/ReplicatorBehavior.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/internal/ReplicatorBehavior.scala @@ -8,7 +8,7 @@ import scala.compat.java8.OptionConverters._ import scala.concurrent.duration._ import akka.annotation.InternalApi -import akka.cluster.{ ddata ⇒ dd } +import akka.cluster.{ ddata => dd } import akka.pattern.ask import akka.actor.typed.ActorRef import akka.actor.typed.Behavior @@ -23,8 +23,8 @@ import akka.actor.typed.Terminated * INTERNAL API */ @InternalApi private[akka] object ReplicatorBehavior { - import akka.cluster.ddata.typed.javadsl.{ Replicator ⇒ JReplicator } - import akka.cluster.ddata.typed.scaladsl.{ Replicator ⇒ SReplicator } + import akka.cluster.ddata.typed.javadsl.{ Replicator => JReplicator } + import akka.cluster.ddata.typed.scaladsl.{ Replicator => SReplicator } private case class InternalChanged[A <: ReplicatedData](chg: dd.Replicator.Changed[A], subscriber: ActorRef[JReplicator.Changed[A]]) extends JReplicator.Command @@ -34,10 +34,10 @@ import akka.actor.typed.Terminated def behavior(settings: dd.ReplicatorSettings, underlyingReplicator: Option[akka.actor.ActorRef]): Behavior[SReplicator.Command] = { - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => val untypedReplicator = underlyingReplicator match { - case Some(ref) ⇒ ref - case None ⇒ + case Some(ref) => ref + case None => // FIXME perhaps add supervisor for restarting val untypedReplicatorProps = dd.Replicator.props(settings) ctx.actorOf(untypedReplicatorProps, name = "underlying") @@ -48,79 +48,79 @@ import akka.actor.typed.Terminated def stopSubscribeAdapter(subscriber: ActorRef[JReplicator.Changed[ReplicatedData]]): Behavior[SReplicator.Command] = { subscribeAdapters.get(subscriber) match { - case Some(adapter) ⇒ + case Some(adapter) => // will be unsubscribed from untypedReplicator via Terminated ctx.stop(adapter) withState(subscribeAdapters - subscriber) - case None ⇒ // already unsubscribed or terminated + case None => // already unsubscribed or terminated Behaviors.same } } - Behaviors.receive[SReplicator.Command] { (ctx, msg) ⇒ + Behaviors.receive[SReplicator.Command] { (ctx, msg) => msg match { - case cmd: SReplicator.Get[_] ⇒ + case cmd: SReplicator.Get[_] => untypedReplicator.tell( dd.Replicator.Get(cmd.key, cmd.consistency, cmd.request), sender = cmd.replyTo.toUntyped) Behaviors.same - case cmd: JReplicator.Get[d] ⇒ + case cmd: JReplicator.Get[d] => implicit val timeout = Timeout(cmd.consistency.timeout match { - case java.time.Duration.ZERO ⇒ localAskTimeout - case t ⇒ t.asScala + additionalAskTimeout + case java.time.Duration.ZERO => localAskTimeout + case t => t.asScala + additionalAskTimeout }) import ctx.executionContext val reply = (untypedReplicator ? dd.Replicator.Get(cmd.key, cmd.consistency.toUntyped, cmd.request.asScala)) .mapTo[dd.Replicator.GetResponse[d]].map { - case rsp: dd.Replicator.GetSuccess[d] ⇒ JReplicator.GetSuccess(rsp.key, rsp.request.asJava)(rsp.dataValue) - case rsp: dd.Replicator.NotFound[d] ⇒ JReplicator.NotFound(rsp.key, rsp.request.asJava) - case rsp: dd.Replicator.GetFailure[d] ⇒ JReplicator.GetFailure(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.GetSuccess[d] => JReplicator.GetSuccess(rsp.key, rsp.request.asJava)(rsp.dataValue) + case rsp: dd.Replicator.NotFound[d] => JReplicator.NotFound(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.GetFailure[d] => JReplicator.GetFailure(rsp.key, rsp.request.asJava) }.recover { - case _ ⇒ JReplicator.GetFailure(cmd.key, cmd.request) + case _ => JReplicator.GetFailure(cmd.key, cmd.request) } reply.foreach { cmd.replyTo ! _ } Behaviors.same - case cmd: SReplicator.Update[_] ⇒ + case cmd: SReplicator.Update[_] => untypedReplicator.tell( dd.Replicator.Update(cmd.key, cmd.writeConsistency, cmd.request)(cmd.modify), sender = cmd.replyTo.toUntyped) Behaviors.same - case cmd: JReplicator.Update[d] ⇒ + case cmd: JReplicator.Update[d] => implicit val timeout = Timeout(cmd.writeConsistency.timeout match { - case java.time.Duration.ZERO ⇒ localAskTimeout - case t ⇒ t.asScala + additionalAskTimeout + case java.time.Duration.ZERO => localAskTimeout + case t => t.asScala + additionalAskTimeout }) import ctx.executionContext val reply = (untypedReplicator ? dd.Replicator.Update(cmd.key, cmd.writeConsistency.toUntyped, cmd.request.asScala)(cmd.modify)) .mapTo[dd.Replicator.UpdateResponse[d]].map { - case rsp: dd.Replicator.UpdateSuccess[d] ⇒ JReplicator.UpdateSuccess(rsp.key, rsp.request.asJava) - case rsp: dd.Replicator.UpdateTimeout[d] ⇒ JReplicator.UpdateTimeout(rsp.key, rsp.request.asJava) - case rsp: dd.Replicator.ModifyFailure[d] ⇒ JReplicator.ModifyFailure(rsp.key, rsp.errorMessage, rsp.cause, rsp.request.asJava) - case rsp: dd.Replicator.StoreFailure[d] ⇒ JReplicator.StoreFailure(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.UpdateSuccess[d] => JReplicator.UpdateSuccess(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.UpdateTimeout[d] => JReplicator.UpdateTimeout(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.ModifyFailure[d] => JReplicator.ModifyFailure(rsp.key, rsp.errorMessage, rsp.cause, rsp.request.asJava) + case rsp: dd.Replicator.StoreFailure[d] => JReplicator.StoreFailure(rsp.key, rsp.request.asJava) }.recover { - case _ ⇒ JReplicator.UpdateTimeout(cmd.key, cmd.request) + case _ => JReplicator.UpdateTimeout(cmd.key, cmd.request) } reply.foreach { cmd.replyTo ! _ } Behaviors.same - case cmd: SReplicator.Subscribe[_] ⇒ + case cmd: SReplicator.Subscribe[_] => // For the Scala API the Changed messages can be sent directly to the subscriber untypedReplicator.tell( dd.Replicator.Subscribe(cmd.key, cmd.subscriber.toUntyped), sender = cmd.subscriber.toUntyped) Behaviors.same - case cmd: JReplicator.Subscribe[ReplicatedData] @unchecked ⇒ + case cmd: JReplicator.Subscribe[ReplicatedData] @unchecked => // For the Java API the Changed messages must be mapped to the JReplicator.Changed class. // That is done with an adapter, and we have to keep track of the lifecycle of the original // subscriber and stop the adapter when the original subscriber is stopped. val adapter: ActorRef[dd.Replicator.Changed[ReplicatedData]] = ctx.spawnMessageAdapter { - chg ⇒ InternalChanged(chg, cmd.subscriber) + chg => InternalChanged(chg, cmd.subscriber) } untypedReplicator.tell( @@ -131,59 +131,59 @@ import akka.actor.typed.Terminated withState(subscribeAdapters.updated(cmd.subscriber, adapter)) - case InternalChanged(chg, subscriber) ⇒ + case InternalChanged(chg, subscriber) => subscriber ! JReplicator.Changed(chg.key)(chg.dataValue) Behaviors.same - case cmd: JReplicator.Unsubscribe[ReplicatedData] @unchecked ⇒ + case cmd: JReplicator.Unsubscribe[ReplicatedData] @unchecked => stopSubscribeAdapter(cmd.subscriber) - case cmd: SReplicator.Delete[_] ⇒ + case cmd: SReplicator.Delete[_] => untypedReplicator.tell( dd.Replicator.Delete(cmd.key, cmd.consistency, cmd.request), sender = cmd.replyTo.toUntyped) Behaviors.same - case cmd: JReplicator.Delete[d] ⇒ + case cmd: JReplicator.Delete[d] => implicit val timeout = Timeout(cmd.consistency.timeout match { - case java.time.Duration.ZERO ⇒ localAskTimeout - case t ⇒ t.asScala + additionalAskTimeout + case java.time.Duration.ZERO => localAskTimeout + case t => t.asScala + additionalAskTimeout }) import ctx.executionContext val reply = (untypedReplicator ? dd.Replicator.Delete(cmd.key, cmd.consistency.toUntyped, cmd.request.asScala)) .mapTo[dd.Replicator.DeleteResponse[d]].map { - case rsp: dd.Replicator.DeleteSuccess[d] ⇒ JReplicator.DeleteSuccess(rsp.key, rsp.request.asJava) - case rsp: dd.Replicator.ReplicationDeleteFailure[d] ⇒ JReplicator.ReplicationDeleteFailure(rsp.key, rsp.request.asJava) - case rsp: dd.Replicator.DataDeleted[d] ⇒ JReplicator.DataDeleted(rsp.key, rsp.request.asJava) - case rsp: dd.Replicator.StoreFailure[d] ⇒ JReplicator.StoreFailure(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.DeleteSuccess[d] => JReplicator.DeleteSuccess(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.ReplicationDeleteFailure[d] => JReplicator.ReplicationDeleteFailure(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.DataDeleted[d] => JReplicator.DataDeleted(rsp.key, rsp.request.asJava) + case rsp: dd.Replicator.StoreFailure[d] => JReplicator.StoreFailure(rsp.key, rsp.request.asJava) }.recover { - case _ ⇒ JReplicator.ReplicationDeleteFailure(cmd.key, cmd.request) + case _ => JReplicator.ReplicationDeleteFailure(cmd.key, cmd.request) } reply.foreach { cmd.replyTo ! _ } Behaviors.same - case SReplicator.GetReplicaCount(replyTo) ⇒ + case SReplicator.GetReplicaCount(replyTo) => untypedReplicator.tell(dd.Replicator.GetReplicaCount, sender = replyTo.toUntyped) Behaviors.same - case JReplicator.GetReplicaCount(replyTo) ⇒ + case JReplicator.GetReplicaCount(replyTo) => implicit val timeout = Timeout(localAskTimeout) import ctx.executionContext val reply = (untypedReplicator ? dd.Replicator.GetReplicaCount) - .mapTo[dd.Replicator.ReplicaCount].map(rsp ⇒ JReplicator.ReplicaCount(rsp.n)) + .mapTo[dd.Replicator.ReplicaCount].map(rsp => JReplicator.ReplicaCount(rsp.n)) reply.foreach { replyTo ! _ } Behaviors.same - case SReplicator.FlushChanges | JReplicator.FlushChanges ⇒ + case SReplicator.FlushChanges | JReplicator.FlushChanges => untypedReplicator.tell(dd.Replicator.FlushChanges, sender = akka.actor.ActorRef.noSender) Behaviors.same } } .receiveSignal { - case (_, Terminated(ref: ActorRef[JReplicator.Changed[ReplicatedData]] @unchecked)) ⇒ + case (_, Terminated(ref: ActorRef[JReplicator.Changed[ReplicatedData]] @unchecked)) => stopSubscribeAdapter(ref) } } diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/DistributedData.scala b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/DistributedData.scala index 61804dd3e1..2f72fb51d9 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/DistributedData.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/DistributedData.scala @@ -57,7 +57,7 @@ abstract class DistributedData extends Extension { } object DistributedDataSetup { - def apply[T <: Extension](createExtension: ActorSystem[_] ⇒ DistributedData): DistributedDataSetup = + def apply[T <: Extension](createExtension: ActorSystem[_] => DistributedData): DistributedDataSetup = new DistributedDataSetup(new java.util.function.Function[ActorSystem[_], DistributedData] { override def apply(sys: ActorSystem[_]): DistributedData = createExtension(sys) }) // TODO can be simplified when compiled only with Scala >= 2.12 diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/Replicator.scala b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/Replicator.scala index 3d3beff128..3bc7a326ae 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/Replicator.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/Replicator.scala @@ -6,7 +6,7 @@ package akka.cluster.ddata.typed.javadsl import java.time.Duration import java.util.Optional -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import scala.util.control.NoStackTrace @@ -19,7 +19,7 @@ import akka.annotation.InternalApi import akka.cluster.ddata.Key import akka.cluster.ddata.ReplicatedData import akka.cluster.ddata.typed.internal.ReplicatorBehavior -import akka.cluster.{ ddata ⇒ dd } +import akka.cluster.{ ddata => dd } import akka.util.JavaDurationConverters._ /** @@ -161,9 +161,9 @@ object Replicator { object Update { - private def modifyWithInitial[A <: ReplicatedData](initial: A, modify: A ⇒ A): Option[A] ⇒ A = { - case Some(data) ⇒ modify(data) - case None ⇒ modify(initial) + private def modifyWithInitial[A <: ReplicatedData](initial: A, modify: A => A): Option[A] => A = { + case Some(data) => modify(data) + case None => modify(initial) } } /** @@ -180,7 +180,7 @@ object Replicator { * for example not access `sender()` reference of an enclosing actor. */ final case class Update[A <: ReplicatedData] private (key: Key[A], writeConsistency: WriteConsistency, - replyTo: ActorRef[UpdateResponse[A]], request: Optional[Any])(val modify: Option[A] ⇒ A) + replyTo: ActorRef[UpdateResponse[A]], request: Optional[Any])(val modify: Option[A] => A) extends Command with NoSerializationVerificationNeeded { /** @@ -193,7 +193,7 @@ object Replicator { def this( key: Key[A], initial: A, writeConsistency: WriteConsistency, replyTo: ActorRef[UpdateResponse[A]], modify: JFunction[A, A]) = this(key, writeConsistency, replyTo, Optional.empty[Any])( - Update.modifyWithInitial(initial, data ⇒ modify.apply(data))) + Update.modifyWithInitial(initial, data => modify.apply(data))) /** * Modify value of local `Replicator` and replicate with given `writeConsistency`. @@ -209,7 +209,7 @@ object Replicator { def this( key: Key[A], initial: A, writeConsistency: WriteConsistency, replyTo: ActorRef[UpdateResponse[A]], request: Optional[Any], modify: JFunction[A, A]) = - this(key, writeConsistency, replyTo, request)(Update.modifyWithInitial(initial, data ⇒ modify.apply(data))) + this(key, writeConsistency, replyTo, request)(Update.modifyWithInitial(initial, data => modify.apply(data))) } diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/ReplicatorSettings.scala b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/ReplicatorSettings.scala index 2ed55b1d30..4239949fd1 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/ReplicatorSettings.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/javadsl/ReplicatorSettings.scala @@ -4,7 +4,7 @@ package akka.cluster.ddata.typed.javadsl -import akka.cluster.{ ddata ⇒ dd } +import akka.cluster.{ ddata => dd } import akka.actor.typed.ActorSystem import akka.actor.typed.scaladsl.adapter._ import com.typesafe.config.Config diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/DistributedData.scala b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/DistributedData.scala index c47bcc5224..ae56b80f03 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/DistributedData.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/DistributedData.scala @@ -10,7 +10,7 @@ import akka.actor.typed.ExtensionId import akka.actor.typed.ActorRef import akka.actor.ExtendedActorSystem import akka.actor.typed.Props -import akka.cluster.{ ddata ⇒ dd } +import akka.cluster.{ ddata => dd } import akka.cluster.ddata.SelfUniqueAddress object DistributedData extends ExtensionId[DistributedData] { diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/Replicator.scala b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/Replicator.scala index 727e20a2f8..13b4d61298 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/Replicator.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/Replicator.scala @@ -6,7 +6,7 @@ package akka.cluster.ddata.typed.scaladsl import akka.actor.NoSerializationVerificationNeeded -import akka.cluster.{ ddata ⇒ dd } +import akka.cluster.{ ddata => dd } import akka.cluster.ddata.Key import akka.cluster.ddata.ReplicatedData import akka.actor.typed.ActorRef @@ -49,8 +49,8 @@ object Replicator { /** * Convenience for `ask`. */ - def apply[A <: ReplicatedData](key: Key[A], consistency: ReadConsistency): ActorRef[GetResponse[A]] ⇒ Get[A] = - replyTo ⇒ Get(key, consistency, replyTo, None) + def apply[A <: ReplicatedData](key: Key[A], consistency: ReadConsistency): ActorRef[GetResponse[A]] => Get[A] = + replyTo => Get(key, consistency, replyTo, None) } /** @@ -94,19 +94,19 @@ object Replicator { */ def apply[A <: ReplicatedData]( key: Key[A], initial: A, writeConsistency: WriteConsistency, replyTo: ActorRef[UpdateResponse[A]], - request: Option[Any] = None)(modify: A ⇒ A): Update[A] = + request: Option[Any] = None)(modify: A => A): Update[A] = Update(key, writeConsistency, replyTo, request)(modifyWithInitial(initial, modify)) /** * Convenience for `ask`. */ def apply[A <: ReplicatedData](key: Key[A], initial: A, - writeConsistency: WriteConsistency)(modify: A ⇒ A): ActorRef[UpdateResponse[A]] ⇒ Update[A] = - (replyTo ⇒ Update(key, writeConsistency, replyTo, None)(modifyWithInitial(initial, modify))) + writeConsistency: WriteConsistency)(modify: A => A): ActorRef[UpdateResponse[A]] => Update[A] = + (replyTo => Update(key, writeConsistency, replyTo, None)(modifyWithInitial(initial, modify))) - private def modifyWithInitial[A <: ReplicatedData](initial: A, modify: A ⇒ A): Option[A] ⇒ A = { - case Some(data) ⇒ modify(data) - case None ⇒ modify(initial) + private def modifyWithInitial[A <: ReplicatedData](initial: A, modify: A => A): Option[A] => A = { + case Some(data) => modify(data) + case None => modify(initial) } } @@ -128,7 +128,7 @@ object Replicator { */ final case class Update[A <: ReplicatedData](key: Key[A], writeConsistency: WriteConsistency, replyTo: ActorRef[UpdateResponse[A]], - request: Option[Any])(val modify: Option[A] ⇒ A) + request: Option[Any])(val modify: Option[A] => A) extends Command with NoSerializationVerificationNeeded { } @@ -201,8 +201,8 @@ object Replicator { /** * Convenience for `ask`. */ - def apply[A <: ReplicatedData](key: Key[A], consistency: WriteConsistency): ActorRef[DeleteResponse[A]] ⇒ Delete[A] = - (replyTo ⇒ Delete(key, consistency, replyTo, None)) + def apply[A <: ReplicatedData](key: Key[A], consistency: WriteConsistency): ActorRef[DeleteResponse[A]] => Delete[A] = + (replyTo => Delete(key, consistency, replyTo, None)) } /** * Send this message to the local `Replicator` to delete a data value for the @@ -225,8 +225,8 @@ object Replicator { /** * Convenience for `ask`. */ - def apply(): ActorRef[ReplicaCount] ⇒ GetReplicaCount = - (replyTo ⇒ GetReplicaCount(replyTo)) + def apply(): ActorRef[ReplicaCount] => GetReplicaCount = + (replyTo => GetReplicaCount(replyTo)) } /** diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/ReplicatorSettings.scala b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/ReplicatorSettings.scala index 43ee70a7ae..231c96c36f 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/ReplicatorSettings.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/ReplicatorSettings.scala @@ -4,7 +4,7 @@ package akka.cluster.ddata.typed.scaladsl -import akka.cluster.{ ddata ⇒ dd } +import akka.cluster.{ ddata => dd } import akka.actor.typed.ActorSystem import akka.actor.typed.scaladsl.adapter._ import akka.annotation.InternalApi diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/package.scala b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/package.scala index 7773c97c2f..72104d5889 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/package.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/ddata/typed/scaladsl/package.scala @@ -4,7 +4,7 @@ package akka.cluster.ddata.typed -import akka.cluster.{ ddata ⇒ dd } +import akka.cluster.{ ddata => dd } package object scaladsl { /** diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/typed/Cluster.scala b/akka-cluster-typed/src/main/scala/akka/cluster/typed/Cluster.scala index 8ec08e719b..e356e06baa 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/typed/Cluster.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/typed/Cluster.scala @@ -188,7 +188,7 @@ abstract class Cluster extends Extension { } object ClusterSetup { - def apply[T <: Extension](createExtension: ActorSystem[_] ⇒ Cluster): ClusterSetup = + def apply[T <: Extension](createExtension: ActorSystem[_] => Cluster): ClusterSetup = new ClusterSetup(new java.util.function.Function[ActorSystem[_], Cluster] { override def apply(sys: ActorSystem[_]): Cluster = createExtension(sys) }) // TODO can be simplified when compiled only with Scala >= 2.12 diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/typed/ClusterSingleton.scala b/akka-cluster-typed/src/main/scala/akka/cluster/typed/ClusterSingleton.scala index bb20f04131..ece31d0e5b 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/typed/ClusterSingleton.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/typed/ClusterSingleton.scala @@ -7,7 +7,7 @@ package akka.cluster.typed import akka.actor.NoSerializationVerificationNeeded import akka.annotation.{ DoNotInherit, InternalApi } import akka.cluster.ClusterSettings.DataCenter -import akka.cluster.singleton.{ ClusterSingletonProxySettings, ClusterSingletonManagerSettings ⇒ UntypedClusterSingletonManagerSettings } +import akka.cluster.singleton.{ ClusterSingletonProxySettings, ClusterSingletonManagerSettings => UntypedClusterSingletonManagerSettings } import akka.cluster.typed.internal.AdaptedClusterSingletonImpl import akka.actor.typed.{ ActorRef, ActorSystem, Behavior, Extension, ExtensionId, Props } import akka.util.JavaDurationConverters._ @@ -286,7 +286,7 @@ final class ClusterSingletonManagerSettings( } object ClusterSingletonSetup { - def apply[T <: Extension](createExtension: ActorSystem[_] ⇒ ClusterSingleton): ClusterSingletonSetup = + def apply[T <: Extension](createExtension: ActorSystem[_] => ClusterSingleton): ClusterSingletonSetup = new ClusterSingletonSetup(new java.util.function.Function[ActorSystem[_], ClusterSingleton] { override def apply(sys: ActorSystem[_]): ClusterSingleton = createExtension(sys) }) // TODO can be simplified when compiled only with Scala >= 2.12 diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AdaptedClusterImpl.scala b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AdaptedClusterImpl.scala index a3be936d6f..4ace983941 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AdaptedClusterImpl.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AdaptedClusterImpl.scala @@ -25,7 +25,7 @@ private[akka] object AdapterClusterImpl { private case object Up extends SeenState private case class Removed(previousStatus: MemberStatus) extends SeenState - private def subscriptionsBehavior(adaptedCluster: akka.cluster.Cluster) = Behaviors.setup[ClusterStateSubscription] { ctx ⇒ + private def subscriptionsBehavior(adaptedCluster: akka.cluster.Cluster) = Behaviors.setup[ClusterStateSubscription] { ctx => var seenState: SeenState = BeforeUp var upSubscribers: List[ActorRef[SelfUp]] = Nil var removedSubscribers: List[ActorRef[SelfRemoved]] = Nil @@ -36,67 +36,67 @@ private[akka] object AdapterClusterImpl { lazy val cluster = Cluster(ctx.system) def onSelfMemberEvent(event: MemberEvent): Unit = { event match { - case ClusterEvent.MemberUp(_) ⇒ + case ClusterEvent.MemberUp(_) => seenState = Up val upMessage = SelfUp(cluster.state) upSubscribers.foreach(_ ! upMessage) upSubscribers = Nil - case ClusterEvent.MemberRemoved(_, previousStatus) ⇒ + case ClusterEvent.MemberRemoved(_, previousStatus) => seenState = Removed(previousStatus) val removedMessage = SelfRemoved(previousStatus) removedSubscribers.foreach(_ ! removedMessage) removedSubscribers = Nil - case _ ⇒ // This is fine. + case _ => // This is fine. } } - Behaviors.receive[AnyRef] { (ctx, msg) ⇒ + Behaviors.receive[AnyRef] { (ctx, msg) => msg match { - case Subscribe(subscriber: ActorRef[SelfUp] @unchecked, clazz) if clazz == classOf[SelfUp] ⇒ + case Subscribe(subscriber: ActorRef[SelfUp] @unchecked, clazz) if clazz == classOf[SelfUp] => seenState match { - case Up ⇒ subscriber ! SelfUp(adaptedCluster.state) - case BeforeUp ⇒ + case Up => subscriber ! SelfUp(adaptedCluster.state) + case BeforeUp => ctx.watch(subscriber) upSubscribers = subscriber :: upSubscribers - case _: Removed ⇒ + case _: Removed => // self did join, but is now no longer up, we want to avoid subscribing // to not get a memory leak, but also not signal anything } Behaviors.same - case Subscribe(subscriber: ActorRef[SelfRemoved] @unchecked, clazz) if clazz == classOf[SelfRemoved] ⇒ + case Subscribe(subscriber: ActorRef[SelfRemoved] @unchecked, clazz) if clazz == classOf[SelfRemoved] => seenState match { - case BeforeUp | Up ⇒ removedSubscribers = subscriber :: removedSubscribers - case Removed(s) ⇒ subscriber ! SelfRemoved(s) + case BeforeUp | Up => removedSubscribers = subscriber :: removedSubscribers + case Removed(s) => subscriber ! SelfRemoved(s) } Behaviors.same - case Subscribe(subscriber, eventClass) ⇒ + case Subscribe(subscriber, eventClass) => adaptedCluster.subscribe(subscriber.toUntyped, initialStateMode = ClusterEvent.initialStateAsEvents, eventClass) Behaviors.same - case Unsubscribe(subscriber) ⇒ + case Unsubscribe(subscriber) => adaptedCluster.unsubscribe(subscriber.toUntyped) Behaviors.same - case GetCurrentState(sender) ⇒ + case GetCurrentState(sender) => adaptedCluster.sendCurrentClusterState(sender.toUntyped) Behaviors.same - case evt: MemberEvent if evt.member.uniqueAddress == cluster.selfMember.uniqueAddress ⇒ + case evt: MemberEvent if evt.member.uniqueAddress == cluster.selfMember.uniqueAddress => onSelfMemberEvent(evt) Behaviors.same - case _: MemberEvent ⇒ + case _: MemberEvent => Behaviors.same } }.receiveSignal { - case (_, Terminated(ref)) ⇒ + case (_, Terminated(ref)) => upSubscribers = upSubscribers.filterNot(_ == ref) removedSubscribers = removedSubscribers.filterNot(_ == ref) Behaviors.same @@ -104,21 +104,21 @@ private[akka] object AdapterClusterImpl { }.narrow[ClusterStateSubscription] } - private def managerBehavior(adaptedCluster: akka.cluster.Cluster) = Behaviors.receive[ClusterCommand]((_, msg) ⇒ + private def managerBehavior(adaptedCluster: akka.cluster.Cluster) = Behaviors.receive[ClusterCommand]((_, msg) => msg match { - case Join(address) ⇒ + case Join(address) => adaptedCluster.join(address) Behaviors.same - case Leave(address) ⇒ + case Leave(address) => adaptedCluster.leave(address) Behaviors.same - case Down(address) ⇒ + case Down(address) => adaptedCluster.down(address) Behaviors.same - case JoinSeedNodes(addresses) ⇒ + case JoinSeedNodes(addresses) => adaptedCluster.joinSeedNodes(addresses) Behaviors.same diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AdaptedClusterSingletonImpl.scala b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AdaptedClusterSingletonImpl.scala index 6050e71b33..3d372542b7 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AdaptedClusterSingletonImpl.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AdaptedClusterSingletonImpl.scala @@ -5,12 +5,12 @@ package akka.cluster.typed.internal import java.util.concurrent.ConcurrentHashMap -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import akka.actor.typed.internal.{ PoisonPill, PoisonPillInterceptor } import akka.actor.{ ExtendedActorSystem, InvalidActorNameException } import akka.annotation.InternalApi -import akka.cluster.singleton.{ ClusterSingletonProxy, ClusterSingletonManager ⇒ OldSingletonManager } +import akka.cluster.singleton.{ ClusterSingletonProxy, ClusterSingletonManager => OldSingletonManager } import akka.cluster.typed.{ Cluster, ClusterSingleton, ClusterSingletonImpl, ClusterSingletonSettings } import akka.actor.typed.internal.adapter.ActorSystemAdapter import akka.actor.typed.scaladsl.Behaviors @@ -35,13 +35,13 @@ private[akka] final class AdaptedClusterSingletonImpl(system: ActorSystem[_]) ex override def init[M](singleton: typed.SingletonActor[M]): ActorRef[M] = { val settings = singleton.settings match { - case None ⇒ ClusterSingletonSettings(system) - case Some(s) ⇒ s + case None => ClusterSingletonSettings(system) + case Some(s) => s } def poisonPillInterceptor(behv: Behavior[M]): Behavior[M] = { singleton.stopMessage match { - case Some(_) ⇒ behv - case None ⇒ Behaviors.intercept(new PoisonPillInterceptor[M])(behv) + case Some(_) => behv + case None => Behaviors.intercept(new PoisonPillInterceptor[M])(behv) } } @@ -54,7 +54,7 @@ private[akka] final class AdaptedClusterSingletonImpl(system: ActorSystem[_]) ex OldSingletonManager.props(untypedProps, singleton.stopMessage.getOrElse(PoisonPill), settings.toManagerSettings(singleton.name)), managerName) } catch { - case ex: InvalidActorNameException if ex.getMessage.endsWith("is not unique!") ⇒ + case ex: InvalidActorNameException if ex.getMessage.endsWith("is not unique!") => // This is fine. We just wanted to make sure it is running and it already is } } diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AkkaClusterTypedSerializer.scala b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AkkaClusterTypedSerializer.scala index ef369a3478..8ecaf47530 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AkkaClusterTypedSerializer.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/AkkaClusterTypedSerializer.scala @@ -26,20 +26,20 @@ private[akka] final class AkkaClusterTypedSerializer(override val system: Extend private val ReceptionistEntryManifest = "a" override def manifest(o: AnyRef): String = o match { - case _: Entry ⇒ ReceptionistEntryManifest - case _ ⇒ + case _: Entry => ReceptionistEntryManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass} in [${getClass.getName}]") } override def toBinary(o: AnyRef): Array[Byte] = o match { - case e: Entry ⇒ receptionistEntryToBinary(e) - case _ ⇒ + case e: Entry => receptionistEntryToBinary(e) + case _ => throw new IllegalArgumentException(s"Cannot serialize object of type [${o.getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case ReceptionistEntryManifest ⇒ receptionistEntryFromBinary(bytes) - case _ ⇒ + case ReceptionistEntryManifest => receptionistEntryFromBinary(bytes) + case _ => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionist.scala b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionist.scala index 41f6831092..1b4bbe08af 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionist.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionist.scala @@ -13,7 +13,7 @@ import akka.actor.typed.{ ActorRef, Behavior, Terminated } import akka.annotation.InternalApi import akka.cluster.ClusterEvent.MemberRemoved import akka.cluster.ddata.typed.scaladsl.DistributedData -import akka.cluster.{ ddata ⇒ dd } +import akka.cluster.{ ddata => dd } import akka.cluster.ddata.{ ORMultiMap, ORMultiMapKey, Replicator } import akka.cluster.{ Cluster, ClusterEvent, UniqueAddress } import akka.remote.AddressUidExtension @@ -62,8 +62,8 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { val replicator = dd.DistributedData(untypedSystem).replicator val selfSystemUid = AddressUidExtension(untypedSystem).longAddressUid lazy val keepTombstonesFor = cluster.settings.PruneGossipTombstonesAfter match { - case f: FiniteDuration ⇒ f - case _ ⇒ throw new IllegalStateException("Cannot actually happen") + case f: FiniteDuration => f + case _ => throw new IllegalStateException("Cannot actually happen") } val cluster = Cluster(untypedSystem) implicit val selfNodeAddress = DistributedData(ctx.system).selfUniqueAddress @@ -72,9 +72,9 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { } override def behavior: Behavior[Command] = - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => ctx.setLoggerClass(classOf[ClusterReceptionist]) - Behaviors.withTimers { timers ⇒ + Behaviors.withTimers { timers => val setup = new Setup(ctx) val registry = ShardedServiceRegistry(setup.settings.distributedKeyCount) @@ -82,19 +82,19 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { // subscribe to changes from other nodes val replicatorMessageAdapter: ActorRef[Replicator.ReplicatorMessage] = ctx.messageAdapter[Replicator.ReplicatorMessage] { - case changed: Replicator.Changed[_] @unchecked ⇒ + case changed: Replicator.Changed[_] @unchecked => ChangeFromReplicator( changed.key.asInstanceOf[DDataKey], changed.dataValue.asInstanceOf[ORMultiMap[ServiceKey[_], Entry]]) } - registry.allDdataKeys.foreach(key ⇒ + registry.allDdataKeys.foreach(key => setup.replicator ! Replicator.Subscribe(key, replicatorMessageAdapter.toUntyped) ) // remove entries when members are removed val clusterEventMessageAdapter: ActorRef[MemberRemoved] = - ctx.messageAdapter[MemberRemoved] { case MemberRemoved(member, _) ⇒ NodeRemoved(member.uniqueAddress) } + ctx.messageAdapter[MemberRemoved] { case MemberRemoved(member, _) => NodeRemoved(member.uniqueAddress) } setup.cluster.subscribe(clusterEventMessageAdapter.toUntyped, ClusterEvent.InitialStateAsEvents, classOf[MemberRemoved]) // also periodic cleanup in case removal from ORMultiMap is skipped due to concurrent update, @@ -121,7 +121,7 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { setup: Setup, registry: ShardedServiceRegistry, subscriptions: SubscriptionRegistry): Behavior[Command] = - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => import setup._ // Helper to create new behavior @@ -135,11 +135,11 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { * FIXME: replace by simple map in our state */ def watchWith(ctx: ActorContext[Command], target: ActorRef[_], msg: InternalCommand): Unit = - ctx.spawnAnonymous[Nothing](Behaviors.setup[Nothing] { innerCtx ⇒ + ctx.spawnAnonymous[Nothing](Behaviors.setup[Nothing] { innerCtx => innerCtx.watch(target) - Behaviors.receive[Nothing]((_, _) ⇒ Behaviors.same) + Behaviors.receive[Nothing]((_, _) => Behaviors.same) .receiveSignal { - case (_, Terminated(`target`)) ⇒ + case (_, Terminated(`target`)) => ctx.self ! msg Behaviors.stopped } @@ -163,7 +163,7 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { val removals = { registry.allServices.foldLeft(Map.empty[AbstractServiceKey, Set[Entry]]) { - case (acc, (key, entries)) ⇒ + case (acc, (key, entries)) => val removedEntries = entries.filter(isOnRemovedNode) if (removedEntries.isEmpty) acc // no change else acc + (key -> removedEntries) @@ -176,15 +176,15 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { "Node(s) [{}] removed, updating registry removing: [{}]", addresses.mkString(","), removals.map { - case (key, entries) ⇒ key.asServiceKey.id -> entries.mkString("[", ", ", "]") + case (key, entries) => key.asServiceKey.id -> entries.mkString("[", ", ", "]") }.mkString(",")) // shard changes over the ddata keys they belong to val removalsPerDdataKey = registry.entriesPerDdataKey(removals) removalsPerDdataKey.foreach { - case (ddataKey, removalForKey) ⇒ - replicator ! Replicator.Update(ddataKey, EmptyORMultiMap, settings.writeConsistency) { registry ⇒ + case (ddataKey, removalForKey) => + replicator ! Replicator.Update(ddataKey, EmptyORMultiMap, settings.writeConsistency) { registry => ServiceRegistry(registry).removeAll(removalForKey).toORMultiMap } } @@ -196,25 +196,25 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { } def onCommand(cmd: Command): Behavior[Command] = cmd match { - case ReceptionistMessages.Register(key, serviceInstance, maybeReplyTo) ⇒ + case ReceptionistMessages.Register(key, serviceInstance, maybeReplyTo) => val entry = Entry(serviceInstance, setup.selfSystemUid) ctx.log.debug("Actor was registered: [{}] [{}]", key, entry) watchWith(ctx, serviceInstance, RegisteredActorTerminated(key, serviceInstance)) maybeReplyTo match { - case Some(replyTo) ⇒ replyTo ! ReceptionistMessages.Registered(key, serviceInstance) - case None ⇒ + case Some(replyTo) => replyTo ! ReceptionistMessages.Registered(key, serviceInstance) + case None => } val ddataKey = registry.ddataKeyFor(key) - replicator ! Replicator.Update(ddataKey, EmptyORMultiMap, settings.writeConsistency) { registry ⇒ + replicator ! Replicator.Update(ddataKey, EmptyORMultiMap, settings.writeConsistency) { registry => ServiceRegistry(registry).addBinding(key, entry).toORMultiMap } Behaviors.same - case ReceptionistMessages.Find(key, replyTo) ⇒ + case ReceptionistMessages.Find(key, replyTo) => replyTo ! ReceptionistMessages.Listing(key.asServiceKey, registry.actorRefsFor(key)) Behaviors.same - case ReceptionistMessages.Subscribe(key, subscriber) ⇒ + case ReceptionistMessages.Subscribe(key, subscriber) => watchWith(ctx, subscriber, SubscriberTerminated(key, subscriber)) // immediately reply with initial listings to the new subscriber @@ -225,21 +225,21 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { def onInternalCommand(cmd: InternalCommand): Behavior[Command] = cmd match { - case SubscriberTerminated(key, subscriber) ⇒ + case SubscriberTerminated(key, subscriber) => next(newSubscriptions = subscriptions.removed(key)(subscriber)) - case RegisteredActorTerminated(key, serviceInstance) ⇒ + case RegisteredActorTerminated(key, serviceInstance) => val entry = Entry(serviceInstance, setup.selfSystemUid) ctx.log.debug("Registered actor terminated: [{}] [{}]", key.asServiceKey.id, entry) val ddataKey = registry.ddataKeyFor(key) - replicator ! Replicator.Update(ddataKey, EmptyORMultiMap, settings.writeConsistency) { registry ⇒ + replicator ! Replicator.Update(ddataKey, EmptyORMultiMap, settings.writeConsistency) { registry => ServiceRegistry(registry).removeBinding(key, entry).toORMultiMap } // tombstone removals so they are not re-added by merging with other concurrent // registrations for the same key next(newState = registry.addTombstone(serviceInstance, setup.newTombstoneDeadline())) - case ChangeFromReplicator(ddataKey, value) ⇒ + case ChangeFromReplicator(ddataKey, value) => // every change will come back this way - this is where the local notifications happens val newState = ServiceRegistry(value) val changedKeys = registry.collectChangedKeys(ddataKey, newState) @@ -249,13 +249,13 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { ctx.log.debug( "Change from replicator: [{}], changes: [{}], tombstones [{}]", newState.entries.entries, - changedKeys.map(key ⇒ + changedKeys.map(key => key.asServiceKey.id -> newState.entriesFor(key).mkString("[", ", ", "]") ).mkString(", "), registry.tombstones.mkString(", ") ) } - changedKeys.foreach { changedKey ⇒ + changedKeys.foreach { changedKey => notifySubscribersFor(changedKey, newState) // because of how ORMultiMap/ORset works, we could have a case where an actor we removed @@ -263,9 +263,9 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { val serviceKey = changedKey.asServiceKey val tombstonedButReAdded = newRegistry.actorRefsFor(serviceKey).filter(newRegistry.hasTombstone) - tombstonedButReAdded.foreach { actorRef ⇒ + tombstonedButReAdded.foreach { actorRef => ctx.log.debug("Saw actorref that was tomstoned {}, re-removing.", actorRef) - replicator ! Replicator.Update(ddataKey, EmptyORMultiMap, settings.writeConsistency) { registry ⇒ + replicator ! Replicator.Update(ddataKey, EmptyORMultiMap, settings.writeConsistency) { registry => ServiceRegistry(registry).removeBinding(serviceKey, Entry(actorRef, setup.selfSystemUid)).toORMultiMap } } @@ -276,14 +276,14 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { Behaviors.same } - case NodeRemoved(uniqueAddress) ⇒ + case NodeRemoved(uniqueAddress) => // ok to update from several nodes but more efficient to try to do it from one node if (cluster.state.leader.contains(cluster.selfAddress)) { ctx.log.debug(s"Leader node observed removed address [{}]", uniqueAddress) nodesRemoved(Set(uniqueAddress)) } else Behaviors.same - case RemoveTick ⇒ + case RemoveTick => // ok to update from several nodes but more efficient to try to do it from one node if (cluster.state.leader.contains(cluster.selfAddress)) { val allAddressesInState: Set[UniqueAddress] = registry.allUniqueAddressesInState(setup.selfUniqueAddress) @@ -299,7 +299,7 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { } else Behavior.same - case PruneTombstonesTick ⇒ + case PruneTombstonesTick => val prunedRegistry = registry.pruneTombstones() if (prunedRegistry eq registry) Behaviors.same else { @@ -308,12 +308,12 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { } } - Behaviors.receive[Command] { (_, msg) ⇒ + Behaviors.receive[Command] { (_, msg) => msg match { // support two heterogenous types of messages without union types - case cmd: InternalCommand ⇒ onInternalCommand(cmd) - case cmd: Command ⇒ onCommand(cmd) - case _ ⇒ Behaviors.unhandled + case cmd: InternalCommand => onInternalCommand(cmd) + case cmd: Command => onCommand(cmd) + case _ => Behaviors.unhandled } } } diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionistSettings.scala b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionistSettings.scala index d0b3f1830e..7cc5995039 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionistSettings.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionistSettings.scala @@ -27,10 +27,10 @@ private[akka] object ClusterReceptionistSettings { val writeConsistency = { val key = "write-consistency" toRootLowerCase(config.getString(key)) match { - case "local" ⇒ Replicator.WriteLocal - case "majority" ⇒ Replicator.WriteMajority(writeTimeout) - case "all" ⇒ Replicator.WriteAll(writeTimeout) - case _ ⇒ Replicator.WriteTo(config.getInt(key), writeTimeout) + case "local" => Replicator.WriteLocal + case "majority" => Replicator.WriteMajority(writeTimeout) + case "all" => Replicator.WriteAll(writeTimeout) + case _ => Replicator.WriteTo(config.getInt(key), writeTimeout) } } ClusterReceptionistSettings( diff --git a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/Registry.scala b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/Registry.scala index 399f8f32e2..48d07b57a2 100644 --- a/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/Registry.scala +++ b/akka-cluster-typed/src/main/scala/akka/cluster/typed/internal/receptionist/Registry.scala @@ -19,7 +19,7 @@ import scala.concurrent.duration.Deadline */ @InternalApi private[akka] object ShardedServiceRegistry { def apply(numberOfKeys: Int): ShardedServiceRegistry = { - val emptyRegistries = (0 until numberOfKeys).map { n ⇒ + val emptyRegistries = (0 until numberOfKeys).map { n => val key = ORMultiMapKey[ServiceKey[_], Entry](s"ReceptionistKey_$n") key -> new ServiceRegistry(EmptyORMultiMap) }.toMap @@ -66,7 +66,7 @@ import scala.concurrent.duration.Deadline def allUniqueAddressesInState(selfUniqueAddress: UniqueAddress): Set[UniqueAddress] = allEntries.collect { // we don't care about local (empty host:port addresses) - case entry if entry.ref.path.address.hasGlobalScope ⇒ + case entry if entry.ref.path.address.hasGlobalScope => entry.uniqueAddress(selfUniqueAddress) }.toSet @@ -77,7 +77,7 @@ import scala.concurrent.duration.Deadline def entriesPerDdataKey(entries: Map[AbstractServiceKey, Set[Entry]]): Map[DDataKey, Map[AbstractServiceKey, Set[Entry]]] = entries.foldLeft(Map.empty[DDataKey, Map[AbstractServiceKey, Set[Entry]]]) { - case (acc, (key, entries)) ⇒ + case (acc, (key, entries)) => val ddataKey = ddataKeyFor(key.asServiceKey) val updated = acc.getOrElse(ddataKey, Map.empty) + (key -> entries) acc + (ddataKey -> updated) @@ -91,7 +91,7 @@ import scala.concurrent.duration.Deadline def pruneTombstones(): ShardedServiceRegistry = { copy(tombstones = tombstones.filter { - case (_, deadline) ⇒ deadline.hasTimeLeft + case (_, deadline) => deadline.hasTimeLeft }) } @@ -117,9 +117,9 @@ import scala.concurrent.duration.Deadline def removeAll(entries: Map[AbstractServiceKey, Set[Entry]])(implicit node: SelfUniqueAddress): ServiceRegistry = { entries.foldLeft(this) { - case (acc, (key, entries)) ⇒ + case (acc, (key, entries)) => entries.foldLeft(acc) { - case (innerAcc, entry) ⇒ + case (innerAcc, entry) => innerAcc.removeBinding[key.Protocol](key.asServiceKey, entry) } } @@ -137,7 +137,7 @@ import scala.concurrent.duration.Deadline def collectChangedKeys(previousRegistry: ServiceRegistry, newRegistry: ServiceRegistry): Set[AbstractServiceKey] = { val allKeys = previousRegistry.toORMultiMap.entries.keySet ++ newRegistry.toORMultiMap.entries.keySet - allKeys.foldLeft(Set.empty[AbstractServiceKey]) { (acc, key) ⇒ + allKeys.foldLeft(Set.empty[AbstractServiceKey]) { (acc, key) => val oldValues = previousRegistry.entriesFor(key) val newValues = newRegistry.entriesFor(key) if (oldValues != newValues) acc + key diff --git a/akka-cluster-typed/src/multi-jvm/scala/akka/cluster/typed/MultiDcClusterActors.scala b/akka-cluster-typed/src/multi-jvm/scala/akka/cluster/typed/MultiDcClusterActors.scala index b3d4ece377..77041aa12b 100644 --- a/akka-cluster-typed/src/multi-jvm/scala/akka/cluster/typed/MultiDcClusterActors.scala +++ b/akka-cluster-typed/src/multi-jvm/scala/akka/cluster/typed/MultiDcClusterActors.scala @@ -13,13 +13,13 @@ object MultiDcClusterActors { case class Ping(ref: ActorRef[Pong]) extends PingProtocol case object NoMore extends PingProtocol - val multiDcPinger = Behaviors.setup[PingProtocol] { ctx ⇒ + val multiDcPinger = Behaviors.setup[PingProtocol] { ctx => val cluster = Cluster(ctx.system) Behaviors.receiveMessage[PingProtocol] { - case Ping(ref) ⇒ + case Ping(ref) => ref ! Pong(cluster.selfMember.dataCenter) Behaviors.same - case NoMore ⇒ + case NoMore => Behaviors.stopped } } diff --git a/akka-cluster-typed/src/multi-jvm/scala/akka/cluster/typed/MultiNodeTypedClusterSpec.scala b/akka-cluster-typed/src/multi-jvm/scala/akka/cluster/typed/MultiNodeTypedClusterSpec.scala index 250c299e56..8192151a69 100644 --- a/akka-cluster-typed/src/multi-jvm/scala/akka/cluster/typed/MultiNodeTypedClusterSpec.scala +++ b/akka-cluster-typed/src/multi-jvm/scala/akka/cluster/typed/MultiNodeTypedClusterSpec.scala @@ -19,7 +19,7 @@ import scala.concurrent.duration._ import scala.language.implicitConversions trait MultiNodeTypedClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoroner with FlightRecordingSupport with Matchers { - self: MultiNodeSpec ⇒ + self: MultiNodeSpec => override def initialParticipants: Int = roles.size @@ -46,27 +46,27 @@ trait MultiNodeTypedClusterSpec extends Suite with STMultiNodeSpec with WatchedB */ implicit def address(role: RoleName): Address = { cachedAddresses.get(role) match { - case null ⇒ + case null => val address = node(role).address cachedAddresses.put(role, address) address - case address ⇒ address + case address => address } } def formCluster(first: RoleName, rest: RoleName*): Unit = { runOn(first) { cluster.manager ! Join(cluster.selfMember.address) - awaitAssert(cluster.state.members.exists { m ⇒ + awaitAssert(cluster.state.members.exists { m => m.uniqueAddress == cluster.selfMember.uniqueAddress && m.status == MemberStatus.Up } should be(true)) } enterBarrier(first.name + "-joined") - rest foreach { node ⇒ + rest foreach { node => runOn(node) { cluster.manager ! Join(address(first)) - awaitAssert(cluster.state.members.exists { m ⇒ + awaitAssert(cluster.state.members.exists { m => m.uniqueAddress == cluster.selfMember.uniqueAddress && m.status == MemberStatus.Up } should be(true)) } diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/ddata/typed/scaladsl/ReplicatorSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/ddata/typed/scaladsl/ReplicatorSpec.scala index b5ed505a4b..6bc62410d0 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/ddata/typed/scaladsl/ReplicatorSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/ddata/typed/scaladsl/ReplicatorSpec.scala @@ -48,7 +48,7 @@ object ReplicatorSpec { val Key = GCounterKey("counter") def client(replicator: ActorRef[Replicator.Command])(implicit node: SelfUniqueAddress): Behavior[ClientCommand] = - Behaviors.setup[ClientCommand] { ctx ⇒ + Behaviors.setup[ClientCommand] { ctx => val updateResponseAdapter: ActorRef[Replicator.UpdateResponse[GCounter]] = ctx.messageAdapter(InternalUpdateResponse.apply) @@ -62,32 +62,32 @@ object ReplicatorSpec { replicator ! Replicator.Subscribe(Key, changedAdapter) def behavior(cachedValue: Int): Behavior[ClientCommand] = { - Behaviors.receive[ClientCommand] { (ctx, msg) ⇒ + Behaviors.receive[ClientCommand] { (ctx, msg) => msg match { - case Increment ⇒ + case Increment => replicator ! Replicator.Update(Key, GCounter.empty, Replicator.WriteLocal, updateResponseAdapter)(_ :+ 1) Behaviors.same - case GetValue(replyTo) ⇒ + case GetValue(replyTo) => replicator ! Replicator.Get(Key, Replicator.ReadLocal, getResponseAdapter, Some(replyTo)) Behaviors.same - case GetCachedValue(replyTo) ⇒ + case GetCachedValue(replyTo) => replicator ! Replicator.Get(Key, Replicator.ReadLocal, getResponseAdapter, Some(replyTo)) Behaviors.same - case internal: InternalMsg ⇒ internal match { - case InternalUpdateResponse(_) ⇒ Behaviors.same // ok + case internal: InternalMsg => internal match { + case InternalUpdateResponse(_) => Behaviors.same // ok - case InternalGetResponse(rsp @ Replicator.GetSuccess(Key, Some(replyTo: ActorRef[Int] @unchecked))) ⇒ + case InternalGetResponse(rsp @ Replicator.GetSuccess(Key, Some(replyTo: ActorRef[Int] @unchecked))) => val value = rsp.get(Key).value.toInt replyTo ! value Behaviors.same - case InternalGetResponse(rsp) ⇒ + case InternalGetResponse(rsp) => Behaviors.unhandled // not dealing with failures - case InternalChanged(chg @ Replicator.Changed(Key)) ⇒ + case InternalChanged(chg @ Replicator.Changed(Key)) => val value = chg.get(Key).value.intValue behavior(value) } diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/ActorSystemSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/ActorSystemSpec.scala index 709cdbeb63..48ba6e4234 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/ActorSystemSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/ActorSystemSpec.scala @@ -29,13 +29,13 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll case class Probe(msg: String, replyTo: ActorRef[String]) - def withSystem[T](name: String, behavior: Behavior[T], doTerminate: Boolean = true)(block: ActorSystem[T] ⇒ Unit): Terminated = { + def withSystem[T](name: String, behavior: Behavior[T], doTerminate: Boolean = true)(block: ActorSystem[T] => Unit): Terminated = { val sys = system(behavior, s"$suite-$name") try { block(sys) if (doTerminate) sys.terminate().futureValue else sys.whenTerminated.futureValue } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => sys.terminate() throw ex } @@ -45,7 +45,7 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll "start the guardian actor and terminate when it terminates" in { val t = withSystem( "a", - Behaviors.receive[Probe] { case (_, p) ⇒ p.replyTo ! p.msg; Behaviors.stopped }, doTerminate = false) { sys ⇒ + Behaviors.receive[Probe] { case (_, p) => p.replyTo ! p.msg; Behaviors.stopped }, doTerminate = false) { sys => val inbox = TestInbox[String]("a") sys ! Probe("hello", inbox.ref) eventually { @@ -61,7 +61,7 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll // see issue #24172 "shutdown if guardian shuts down immediately" in { pending - withSystem("shutdown", Behaviors.stopped[String], doTerminate = false) { sys: ActorSystem[String] ⇒ + withSystem("shutdown", Behaviors.stopped[String], doTerminate = false) { sys: ActorSystem[String] => sys.whenTerminated.futureValue } } @@ -70,9 +70,9 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll val inbox = TestInbox[String]("terminate") val sys = system( Behaviors.receive[Probe] { - case (_, _) ⇒ Behaviors.unhandled + case (_, _) => Behaviors.unhandled } receiveSignal { - case (_, PostStop) ⇒ + case (_, PostStop) => inbox.ref ! "done" Behaviors.same }, @@ -86,13 +86,13 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll } "have a name" in { - withSystem("name", Behaviors.empty[String]) { sys ⇒ + withSystem("name", Behaviors.empty[String]) { sys => sys.name should ===(suite + "-name") } } "report its uptime" in { - withSystem("uptime", Behaviors.empty[String]) { sys ⇒ + withSystem("uptime", Behaviors.empty[String]) { sys => sys.uptime should be < 1L Thread.sleep(2000) sys.uptime should be >= 1L @@ -100,7 +100,7 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll } "have a working thread factory" in { - withSystem("thread", Behaviors.empty[String]) { sys ⇒ + withSystem("thread", Behaviors.empty[String]) { sys => val p = Promise[Int] sys.threadFactory.newThread(new Runnable { def run(): Unit = p.success(42) @@ -110,14 +110,14 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll } "be able to run Futures" in { - withSystem("futures", Behaviors.empty[String]) { sys ⇒ + withSystem("futures", Behaviors.empty[String]) { sys => val f = Future(42)(sys.executionContext) f.futureValue should ===(42) } } "not allow null messages" in { - withSystem("null-messages", Behaviors.empty[String]) { sys ⇒ + withSystem("null-messages", Behaviors.empty[String]) { sys => intercept[InvalidMessageException] { sys ! null } diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonApiSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonApiSpec.scala index 3f3ee17757..2da4cf31db 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonApiSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonApiSpec.scala @@ -50,14 +50,14 @@ object ClusterSingletonApiSpec { case object Perish extends PingProtocol - val pingPong = Behaviors.receive[PingProtocol] { (_, msg) ⇒ + val pingPong = Behaviors.receive[PingProtocol] { (_, msg) => msg match { - case Ping(respondTo) ⇒ + case Ping(respondTo) => respondTo ! Pong Behaviors.same - case Perish ⇒ + case Perish => Behaviors.stopped } @@ -69,21 +69,21 @@ object ClusterSingletonApiSpec { def identifier: Int = 47 def manifest(o: AnyRef): String = o match { - case _: Ping ⇒ "a" - case Pong ⇒ "b" - case Perish ⇒ "c" + case _: Ping => "a" + case Pong => "b" + case Perish => "c" } def toBinary(o: AnyRef): Array[Byte] = o match { - case p: Ping ⇒ actorRefResolver.toSerializationFormat(p.respondTo).getBytes(StandardCharsets.UTF_8) - case Pong ⇒ Array.emptyByteArray - case Perish ⇒ Array.emptyByteArray + case p: Ping => actorRefResolver.toSerializationFormat(p.respondTo).getBytes(StandardCharsets.UTF_8) + case Pong => Array.emptyByteArray + case Perish => Array.emptyByteArray } def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case "a" ⇒ Ping(actorRefResolver.resolveActorRef(new String(bytes, StandardCharsets.UTF_8))) - case "b" ⇒ Pong - case "c" ⇒ Perish + case "a" => Ping(actorRefResolver.resolveActorRef(new String(bytes, StandardCharsets.UTF_8))) + case "b" => Pong + case "c" => Perish } } } diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonPersistenceSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonPersistenceSpec.scala index e973b8a9f4..320fa43a7e 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonPersistenceSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonPersistenceSpec.scala @@ -39,14 +39,14 @@ object ClusterSingletonPersistenceSpec { EventSourcedBehavior[Command, String, String]( persistenceId = PersistenceId("TheSingleton"), emptyState = "", - commandHandler = (state, cmd) ⇒ cmd match { - case Add(s) ⇒ Effect.persist(s) - case Get(replyTo) ⇒ + commandHandler = (state, cmd) => cmd match { + case Add(s) => Effect.persist(s) + case Get(replyTo) => replyTo ! state Effect.none - case StopPlz ⇒ Effect.stop() + case StopPlz => Effect.stop() }, - eventHandler = (state, evt) ⇒ if (state.isEmpty) evt else state + "|" + evt) + eventHandler = (state, evt) => if (state.isEmpty) evt else state + "|" + evt) } diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonPoisonPillSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonPoisonPillSpec.scala index 7c0f931524..0d348f919a 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonPoisonPillSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/ClusterSingletonPoisonPillSpec.scala @@ -19,7 +19,7 @@ object ClusterSingletonPoisonPillSpec { final case class GetSelf(replyTo: ActorRef[ActorRef[Any]]) val sneakyBehavior: Behavior[GetSelf] = Behaviors.receive { - case (ctx, GetSelf(replyTo)) ⇒ + case (ctx, GetSelf(replyTo)) => replyTo ! ctx.self.unsafeUpcast[Any] Behaviors.same } diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteContextAskSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteContextAskSpec.scala index 6d18518ef1..0bb7ed55cc 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteContextAskSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteContextAskSpec.scala @@ -25,20 +25,20 @@ import org.scalatest.WordSpecLike class RemoteContextAskSpecSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest { override def identifier = 41 override def manifest(o: AnyRef) = o match { - case _: RemoteContextAskSpec.Ping ⇒ "a" - case RemoteContextAskSpec.Pong ⇒ "b" + case _: RemoteContextAskSpec.Ping => "a" + case RemoteContextAskSpec.Pong => "b" } override def toBinary(o: AnyRef) = o match { - case RemoteContextAskSpec.Ping(who) ⇒ + case RemoteContextAskSpec.Ping(who) => ActorRefResolver(system.toTyped).toSerializationFormat(who).getBytes(StandardCharsets.UTF_8) - case RemoteContextAskSpec.Pong ⇒ Array.emptyByteArray + case RemoteContextAskSpec.Pong => Array.emptyByteArray } override def fromBinary(bytes: Array[Byte], manifest: String) = manifest match { - case "a" ⇒ + case "a" => val str = new String(bytes, StandardCharsets.UTF_8) val ref = ActorRefResolver(system.toTyped).resolveActorRef[RemoteContextAskSpec.Pong.type](str) RemoteContextAskSpec.Ping(ref) - case "b" ⇒ RemoteContextAskSpec.Pong + case "b" => RemoteContextAskSpec.Pong } } @@ -73,9 +73,9 @@ object RemoteContextAskSpec { case object Pong case class Ping(respondTo: ActorRef[Pong.type]) - def pingPong = Behaviors.receive[Ping] { (_, msg) ⇒ + def pingPong = Behaviors.receive[Ping] { (_, msg) => msg match { - case Ping(sender) ⇒ + case Ping(sender) => sender ! Pong Behaviors.same } @@ -110,15 +110,15 @@ class RemoteContextAskSpec extends ScalaTestWithActorTestKit(RemoteContextAskSpe // wait until the service is seen on the first node val remoteRef = node1Probe.expectMessageType[Receptionist.Listing].serviceInstances(pingPongKey).head - spawn(Behaviors.setup[AnyRef] { ctx ⇒ + spawn(Behaviors.setup[AnyRef] { ctx => implicit val timeout: Timeout = 3.seconds ctx.ask(remoteRef)(Ping) { - case Success(pong) ⇒ pong - case Failure(ex) ⇒ ex + case Success(pong) => pong + case Failure(ex) => ex } - Behaviors.receiveMessage { msg ⇒ + Behaviors.receiveMessage { msg => node1Probe.ref ! msg Behaviors.same } diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteDeployNotAllowedSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteDeployNotAllowedSpec.scala index 283af4b59e..fb4028c9e3 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteDeployNotAllowedSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteDeployNotAllowedSpec.scala @@ -58,26 +58,26 @@ class RemoteDeployNotAllowedSpec extends ScalaTestWithActorTestKit(RemoteDeployN case class SpawnChild(name: String) extends GuardianProtocol case object SpawnAnonymous extends GuardianProtocol - val guardianBehavior = Behaviors.receive[GuardianProtocol] { (ctx, msg) ⇒ + val guardianBehavior = Behaviors.receive[GuardianProtocol] { (ctx, msg) => msg match { - case SpawnChild(name) ⇒ + case SpawnChild(name) => // this should throw try { ctx.spawn( - Behaviors.setup[AnyRef] { ctx ⇒ Behaviors.empty }, + Behaviors.setup[AnyRef] { ctx => Behaviors.empty }, name) } catch { - case ex: Exception ⇒ probe.ref ! ex + case ex: Exception => probe.ref ! ex } Behaviors.same - case SpawnAnonymous ⇒ + case SpawnAnonymous => // this should throw try { - ctx.spawnAnonymous(Behaviors.setup[AnyRef] { ctx ⇒ Behaviors.empty }) + ctx.spawnAnonymous(Behaviors.setup[AnyRef] { ctx => Behaviors.empty }) } catch { - case ex: Exception ⇒ probe.ref ! ex + case ex: Exception => probe.ref ! ex } Behaviors.same } diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteMessageSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteMessageSpec.scala index 44c077b4e7..bee93b2791 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteMessageSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/RemoteMessageSpec.scala @@ -10,7 +10,7 @@ import akka.Done import akka.testkit.AkkaSpec import akka.actor.typed.{ ActorRef, ActorRefResolver } import akka.actor.typed.scaladsl.Behaviors -import akka.actor.{ ExtendedActorSystem, ActorSystem ⇒ UntypedActorSystem } +import akka.actor.{ ExtendedActorSystem, ActorSystem => UntypedActorSystem } import akka.serialization.SerializerWithStringManifest import com.typesafe.config.ConfigFactory @@ -21,7 +21,7 @@ class PingSerializer(system: ExtendedActorSystem) extends SerializerWithStringMa override def identifier = 41 override def manifest(o: AnyRef) = "a" override def toBinary(o: AnyRef) = o match { - case RemoteMessageSpec.Ping(who) ⇒ + case RemoteMessageSpec.Ping(who) => ActorRefResolver(system.toTyped).toSerializationFormat(who).getBytes(StandardCharsets.UTF_8) } override def fromBinary(bytes: Array[Byte], manifest: String) = { @@ -71,9 +71,9 @@ class RemoteMessageSpec extends AkkaSpec(RemoteMessageSpec.config) { "something something" in { val pingPromise = Promise[Done]() - val ponger = Behaviors.receive[Ping]((_, msg) ⇒ + val ponger = Behaviors.receive[Ping]((_, msg) => msg match { - case Ping(sender) ⇒ + case Ping(sender) => pingPromise.success(Done) sender ! "pong" Behaviors.stopped @@ -92,7 +92,7 @@ class RemoteMessageSpec extends AkkaSpec(RemoteMessageSpec.config) { ActorRefResolver(typedSystem2).resolveActorRef[Ping](remoteRefStr) val pongPromise = Promise[Done]() - val recipient = system2.spawn(Behaviors.receive[String] { (_, _) ⇒ + val recipient = system2.spawn(Behaviors.receive[String] { (_, _) => pongPromise.success(Done) Behaviors.stopped }, "recipient") diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/internal/AkkaClusterTypedSerializerSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/internal/AkkaClusterTypedSerializerSpec.scala index 09f2f07bd8..beecbd9328 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/internal/AkkaClusterTypedSerializerSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/internal/AkkaClusterTypedSerializerSpec.scala @@ -21,9 +21,9 @@ class AkkaClusterTypedSerializerSpec extends ScalaTestWithActorTestKit with Word "AkkaClusterTypedSerializer" must { Seq( - "ReceptionistEntry" → ClusterReceptionist.Entry(ref, 666L) + "ReceptionistEntry" -> ClusterReceptionist.Entry(ref, 666L) ).foreach { - case (scenario, item) ⇒ + case (scenario, item) => s"resolve serializer for $scenario" in { val serializer = SerializationExtension(untypedSystem) serializer.serializerFor(item.getClass).getClass should be(classOf[AkkaClusterTypedSerializer]) diff --git a/akka-cluster-typed/src/test/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionistSpec.scala b/akka-cluster-typed/src/test/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionistSpec.scala index 70d9f9c862..88ef3d81eb 100644 --- a/akka-cluster-typed/src/test/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionistSpec.scala +++ b/akka-cluster-typed/src/test/scala/akka/cluster/typed/internal/receptionist/ClusterReceptionistSpec.scala @@ -54,13 +54,13 @@ object ClusterReceptionistSpec { case class Ping(respondTo: ActorRef[Pong.type]) extends PingProtocol case object Perish extends PingProtocol - val pingPongBehavior = Behaviors.receive[PingProtocol] { (_, msg) ⇒ + val pingPongBehavior = Behaviors.receive[PingProtocol] { (_, msg) => msg match { - case Ping(respondTo) ⇒ + case Ping(respondTo) => respondTo ! Pong Behaviors.same - case Perish ⇒ + case Perish => Behaviors.stopped } } @@ -68,21 +68,21 @@ object ClusterReceptionistSpec { class PingSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest { def identifier: Int = 47 def manifest(o: AnyRef): String = o match { - case _: Ping ⇒ "a" - case Pong ⇒ "b" - case Perish ⇒ "c" + case _: Ping => "a" + case Pong => "b" + case Perish => "c" } def toBinary(o: AnyRef): Array[Byte] = o match { - case p: Ping ⇒ ActorRefResolver(system.toTyped).toSerializationFormat(p.respondTo).getBytes(StandardCharsets.UTF_8) - case Pong ⇒ Array.emptyByteArray - case Perish ⇒ Array.emptyByteArray + case p: Ping => ActorRefResolver(system.toTyped).toSerializationFormat(p.respondTo).getBytes(StandardCharsets.UTF_8) + case Pong => Array.emptyByteArray + case Perish => Array.emptyByteArray } def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case "a" ⇒ Ping(ActorRefResolver(system.toTyped).resolveActorRef(new String(bytes, StandardCharsets.UTF_8))) - case "b" ⇒ Pong - case "c" ⇒ Perish + case "a" => Ping(ActorRefResolver(system.toTyped).resolveActorRef(new String(bytes, StandardCharsets.UTF_8))) + case "b" => Pong + case "c" => Perish } } @@ -266,7 +266,7 @@ class ClusterReceptionistSpec extends WordSpec with Matchers { // make sure it joined fine and node1 has upped it regProbe1.awaitAssert { - clusterNode1.state.members.exists(m ⇒ + clusterNode1.state.members.exists(m => m.uniqueAddress == clusterNode3.selfMember.uniqueAddress && m.status == MemberStatus.Up && !clusterNode1.state.unreachable(m) @@ -276,8 +276,8 @@ class ClusterReceptionistSpec extends WordSpec with Matchers { // we should get either empty message and then updated with the new incarnation actor // or just updated with the new service directly val msg = regProbe1.fishForMessage(20.seconds) { - case PingKey.Listing(entries) if entries.size == 1 ⇒ FishingOutcome.Complete - case _: Listing ⇒ FishingOutcome.ContinueAndIgnore + case PingKey.Listing(entries) if entries.size == 1 => FishingOutcome.Complete + case _: Listing => FishingOutcome.ContinueAndIgnore } val PingKey.Listing(entries) = msg.last entries should have size 1 @@ -322,10 +322,10 @@ class ClusterReceptionistSpec extends WordSpec with Matchers { // one actor on each node up front val actor1 = testKit1.spawn(Behaviors.receive[AnyRef] { - case (ctx, "stop") ⇒ + case (ctx, "stop") => ctx.log.info("Stopping") Behaviors.stopped - case _ ⇒ Behaviors.same + case _ => Behaviors.same }, "actor1") val actor2 = testKit2.spawn(Behaviors.empty[AnyRef], "actor2") @@ -338,10 +338,10 @@ class ClusterReceptionistSpec extends WordSpec with Matchers { system2.receptionist ! Subscribe(TheKey, regProbe2.ref) regProbe2.fishForMessage(10.seconds) { - case TheKey.Listing(actors) if actors.nonEmpty ⇒ + case TheKey.Listing(actors) if actors.nonEmpty => println(actors) FishingOutcomes.complete - case _ ⇒ FishingOutcomes.continue + case _ => FishingOutcomes.continue } system1.log.info("Saw actor on both nodes") @@ -354,15 +354,15 @@ class ClusterReceptionistSpec extends WordSpec with Matchers { // we should now, eventually, see the removal on both nodes regProbe1.fishForMessage(10.seconds) { - case TheKey.Listing(actors) if actors.size == 1 ⇒ + case TheKey.Listing(actors) if actors.size == 1 => FishingOutcomes.complete - case _ ⇒ + case _ => FishingOutcomes.continue } regProbe2.fishForMessage(10.seconds) { - case TheKey.Listing(actors) if actors.size == 1 ⇒ + case TheKey.Listing(actors) if actors.size == 1 => FishingOutcomes.complete - case _ ⇒ + case _ => FishingOutcomes.continue } diff --git a/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/PingSerializer.scala b/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/PingSerializer.scala index a210b9484e..5364d2591a 100644 --- a/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/PingSerializer.scala +++ b/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/PingSerializer.scala @@ -22,24 +22,24 @@ class PingSerializer(system: ExtendedActorSystem) extends SerializerWithStringMa override def identifier = 41 override def manifest(msg: AnyRef) = msg match { - case _: Ping ⇒ PingManifest - case Pong ⇒ PongManifest + case _: Ping => PingManifest + case Pong => PongManifest } override def toBinary(msg: AnyRef) = msg match { - case Ping(who) ⇒ + case Ping(who) => actorRefResolver.toSerializationFormat(who).getBytes(StandardCharsets.UTF_8) - case Pong ⇒ + case Pong => Array.emptyByteArray } override def fromBinary(bytes: Array[Byte], manifest: String) = { manifest match { - case PingManifest ⇒ + case PingManifest => val str = new String(bytes, StandardCharsets.UTF_8) val ref = actorRefResolver.resolveActorRef[Pong.type](str) Ping(ref) - case PongManifest ⇒ + case PongManifest => Pong } } diff --git a/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/ReceptionistExampleSpec.scala b/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/ReceptionistExampleSpec.scala index 4803319b4b..2c4d172c46 100644 --- a/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/ReceptionistExampleSpec.scala +++ b/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/ReceptionistExampleSpec.scala @@ -21,11 +21,11 @@ object PingPongExample { final case object Pong val pingService: Behavior[Ping] = - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => ctx.system.receptionist ! Receptionist.Register(PingServiceKey, ctx.self) - Behaviors.receive[Ping] { (_, msg) ⇒ + Behaviors.receive[Ping] { (_, msg) => msg match { - case Ping(replyTo) ⇒ + case Ping(replyTo) => println("Pinged, now stopping") replyTo ! Pong Behaviors.stopped @@ -35,9 +35,9 @@ object PingPongExample { //#ping-service //#pinger - def pinger(pingService: ActorRef[Ping]) = Behaviors.setup[Pong.type] { ctx ⇒ + def pinger(pingService: ActorRef[Ping]) = Behaviors.setup[Pong.type] { ctx => pingService ! Ping(ctx.self) - Behaviors.receive { (_, msg) ⇒ + Behaviors.receive { (_, msg) => println("I was ponged!!" + msg) Behaviors.same } @@ -45,16 +45,16 @@ object PingPongExample { //#pinger //#pinger-guardian - val guardian: Behavior[Nothing] = Behaviors.setup[Listing] { ctx ⇒ + val guardian: Behavior[Nothing] = Behaviors.setup[Listing] { ctx => ctx.system.receptionist ! Receptionist.Subscribe(PingServiceKey, ctx.self) val ps = ctx.spawnAnonymous(pingService) ctx.watch(ps) Behaviors.receiveMessagePartial[Listing] { - case PingServiceKey.Listing(listings) if listings.nonEmpty ⇒ - listings.foreach(ps ⇒ ctx.spawnAnonymous(pinger(ps))) + case PingServiceKey.Listing(listings) if listings.nonEmpty => + listings.foreach(ps => ctx.spawnAnonymous(pinger(ps))) Behaviors.same } receiveSignal { - case (_, Terminated(`ps`)) ⇒ + case (_, Terminated(`ps`)) => println("Ping service has shut down") Behaviors.stopped } diff --git a/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/SingletonCompileOnlySpec.scala b/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/SingletonCompileOnlySpec.scala index 56e939e654..b9085809cd 100644 --- a/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/SingletonCompileOnlySpec.scala +++ b/akka-cluster-typed/src/test/scala/docs/akka/cluster/typed/SingletonCompileOnlySpec.scala @@ -22,12 +22,12 @@ object SingletonCompileOnlySpec { def counter(value: Int): Behavior[CounterCommand] = Behaviors.receiveMessage[CounterCommand] { - case Increment ⇒ + case Increment => counter(value + 1) - case GetValue(replyTo) ⇒ + case GetValue(replyTo) => replyTo ! value Behaviors.same - case GoodByeCounter ⇒ + case GoodByeCounter => // Do async action then stop Behaviors.stopped } diff --git a/akka-cluster/src/main/scala/akka/cluster/AutoDown.scala b/akka-cluster/src/main/scala/akka/cluster/AutoDown.scala index bf50a53f3d..5e04353efb 100644 --- a/akka-cluster/src/main/scala/akka/cluster/AutoDown.scala +++ b/akka-cluster/src/main/scala/akka/cluster/AutoDown.scala @@ -35,8 +35,8 @@ final class AutoDowning(system: ActorSystem) extends DowningProvider { override def downingActorProps: Option[Props] = clusterSettings.AutoDownUnreachableAfter match { - case d: FiniteDuration ⇒ Some(AutoDown.props(d)) - case _ ⇒ + case d: FiniteDuration => Some(AutoDown.props(d)) + case _ => // I don't think this can actually happen throw new ConfigurationException("AutoDowning downing provider selected but 'akka.cluster.auto-down-unreachable-after' not set") } @@ -113,29 +113,29 @@ private[cluster] abstract class AutoDownBase(autoDownUnreachableAfter: FiniteDur } def receive = { - case state: CurrentClusterState ⇒ + case state: CurrentClusterState => leader = state.leader.exists(_ == selfAddress) state.unreachable foreach unreachableMember - case UnreachableMember(m) ⇒ unreachableMember(m) + case UnreachableMember(m) => unreachableMember(m) - case ReachableMember(m) ⇒ remove(m.uniqueAddress) - case MemberRemoved(m, _) ⇒ remove(m.uniqueAddress) + case ReachableMember(m) => remove(m.uniqueAddress) + case MemberRemoved(m, _) => remove(m.uniqueAddress) - case LeaderChanged(leaderOption) ⇒ + case LeaderChanged(leaderOption) => leader = leaderOption.exists(_ == selfAddress) if (leader) { - pendingUnreachable.foreach(node ⇒ down(node.address)) + pendingUnreachable.foreach(node => down(node.address)) pendingUnreachable = Set.empty } - case UnreachableTimeout(node) ⇒ + case UnreachableTimeout(node) => if (scheduledUnreachable contains node) { scheduledUnreachable -= node downOrAddPending(node) } - case _: ClusterDomainEvent ⇒ // not interested in other events + case _: ClusterDomainEvent => // not interested in other events } @@ -148,7 +148,7 @@ private[cluster] abstract class AutoDownBase(autoDownUnreachableAfter: FiniteDur downOrAddPending(node) } else { val task = scheduler.scheduleOnce(autoDownUnreachableAfter, self, UnreachableTimeout(node)) - scheduledUnreachable += (node → task) + scheduledUnreachable += (node -> task) } } diff --git a/akka-cluster/src/main/scala/akka/cluster/Cluster.scala b/akka-cluster/src/main/scala/akka/cluster/Cluster.scala index 319038c72e..d501812dbd 100644 --- a/akka-cluster/src/main/scala/akka/cluster/Cluster.scala +++ b/akka-cluster/src/main/scala/akka/cluster/Cluster.scala @@ -16,7 +16,7 @@ import akka.dispatch.MonitorableThreadFactory import akka.event.{ Logging, LoggingAdapter } import akka.japi.Util import akka.pattern._ -import akka.remote.{ UniqueAddress ⇒ _, _ } +import akka.remote.{ UniqueAddress => _, _ } import com.typesafe.config.{ Config, ConfigFactory } import scala.annotation.varargs import scala.collection.immutable @@ -41,8 +41,8 @@ object Cluster extends ExtensionId[Cluster] with ExtensionIdProvider { */ private[cluster] final val isAssertInvariantsEnabled: Boolean = System.getProperty("akka.cluster.assert", "off").toLowerCase match { - case "on" | "true" ⇒ true - case _ ⇒ false + case "on" | "true" => true + case _ => false } } @@ -70,9 +70,9 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { * incarnations of a member with same hostname and port. */ val selfUniqueAddress: UniqueAddress = system.provider match { - case c: ClusterActorRefProvider ⇒ + case c: ClusterActorRefProvider => UniqueAddress(c.transport.defaultAddress, AddressUidExtension(system).longAddressUid) - case other ⇒ throw new ConfigurationException( + case other => throw new ConfigurationException( s"ActorSystem [${system}] needs to have 'akka.actor.provider' set to 'cluster' in the configuration, currently uses [${other.getClass.getName}]") } @@ -103,14 +103,14 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { logInfo("Starting up, Akka version [{}] ...", system.settings.ConfigVersion) val failureDetector: FailureDetectorRegistry[Address] = { - val createFailureDetector = () ⇒ + val createFailureDetector = () => FailureDetectorLoader.load(settings.FailureDetectorImplementationClass, settings.FailureDetectorConfig, system) new DefaultFailureDetectorRegistry(createFailureDetector) } val crossDcFailureDetector: FailureDetectorRegistry[Address] = { - val createFailureDetector = () ⇒ + val createFailureDetector = () => FailureDetectorLoader.load( settings.MultiDataCenter.CrossDcFailureDetectorSettings.ImplementationClass, settings.MultiDataCenter.CrossDcFailureDetectorSettings.config, system) @@ -140,13 +140,13 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { s"akka.scheduler.tick-duration=${SchedulerTickDuration.toMillis}ms").withFallback( system.settings.config) val threadFactory = system.threadFactory match { - case tf: MonitorableThreadFactory ⇒ tf.withName(tf.name + "-cluster-scheduler") - case tf ⇒ tf + case tf: MonitorableThreadFactory => tf.withName(tf.name + "-cluster-scheduler") + case tf => tf } system.dynamicAccess.createInstanceFor[Scheduler](system.settings.SchedulerClass, immutable.Seq( - classOf[Config] → cfg, - classOf[LoggingAdapter] → log, - classOf[ThreadFactory] → threadFactory)).get + classOf[Config] -> cfg, + classOf[LoggingAdapter] -> log, + classOf[ThreadFactory] -> threadFactory)).get } else { // delegate to system.scheduler, but don't close over system val systemScheduler = system.scheduler @@ -181,7 +181,7 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { try { Await.result((clusterDaemons ? InternalClusterAction.GetClusterCoreRef).mapTo[ActorRef], timeout.duration) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "Failed to startup Cluster. You can try to increase 'akka.actor.creation-timeout'.") shutdown() // don't re-throw, that would cause the extension to be re-recreated @@ -355,7 +355,7 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { * to defer some action, such as starting actors, until the cluster has reached * a certain size. */ - def registerOnMemberUp[T](code: ⇒ T): Unit = + def registerOnMemberUp[T](code: => T): Unit = registerOnMemberUp(new Runnable { def run() = code }) /** @@ -372,7 +372,7 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { * If the cluster has already been shutdown the thunk will run on the caller thread immediately. * Typically used together `cluster.leave(cluster.selfAddress)` and then `system.terminate()`. */ - def registerOnMemberRemoved[T](code: ⇒ T): Unit = + def registerOnMemberRemoved[T](code: => T): Unit = registerOnMemberRemoved(new Runnable { override def run(): Unit = code }) /** @@ -431,8 +431,8 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { } private def closeScheduler(): Unit = scheduler match { - case x: Closeable ⇒ x.close() - case _ ⇒ // ignore, this is fine + case x: Closeable => x.close() + case _ => // ignore, this is fine } /** diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterActorRefProvider.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterActorRefProvider.scala index 9b4af59077..145e029305 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterActorRefProvider.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterActorRefProvider.scala @@ -75,7 +75,7 @@ private[akka] class ClusterDeployer(_settings: ActorSystem.Settings, _pm: Dynami } else config super.parseConfig(path, config2) match { - case d @ Some(deploy) ⇒ + case d @ Some(deploy) => if (deploy.config.getBoolean("cluster.enabled")) { if (deploy.scope != NoScopeGiven) throw new ConfigurationException("Cluster deployment can't be combined with scope [%s]".format(deploy.scope)) @@ -83,17 +83,17 @@ private[akka] class ClusterDeployer(_settings: ActorSystem.Settings, _pm: Dynami throw new ConfigurationException("Cluster deployment can't be combined with [%s]".format(deploy.routerConfig)) deploy.routerConfig match { - case r: Pool ⇒ + case r: Pool => Some(deploy.copy( routerConfig = ClusterRouterPool(r, ClusterRouterPoolSettings.fromConfig(deploy.config)), scope = ClusterScope)) - case r: Group ⇒ + case r: Group => Some(deploy.copy( routerConfig = ClusterRouterGroup(r, ClusterRouterGroupSettings.fromConfig(deploy.config)), scope = ClusterScope)) - case other ⇒ + case other => throw new IllegalArgumentException(s"Cluster aware router can only wrap Pool or Group, got [${other.getClass.getName}]") } } else d - case None ⇒ None + case None => None } } diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterDaemon.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterDaemon.scala index 9e78fe8952..19d2d7efc1 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterDaemon.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterDaemon.scala @@ -192,7 +192,7 @@ private[cluster] final class ClusterDaemon(joinConfigCompatChecker: JoinConfigCo val coordShutdown = CoordinatedShutdown(context.system) coordShutdown.addTask(CoordinatedShutdown.PhaseClusterLeave, "leave") { val sys = context.system - () ⇒ + () => if (Cluster(sys).isTerminated || Cluster(sys).selfMember.status == Down) Future.successful(Done) else { @@ -200,7 +200,7 @@ private[cluster] final class ClusterDaemon(joinConfigCompatChecker: JoinConfigCo self.ask(CoordinatedShutdownLeave.LeaveReq).mapTo[Done] } } - coordShutdown.addTask(CoordinatedShutdown.PhaseClusterShutdown, "wait-shutdown") { () ⇒ + coordShutdown.addTask(CoordinatedShutdown.PhaseClusterShutdown, "wait-shutdown") { () => clusterShutdown.future } @@ -220,15 +220,15 @@ private[cluster] final class ClusterDaemon(joinConfigCompatChecker: JoinConfigCo } def receive = { - case msg: GetClusterCoreRef.type ⇒ + case msg: GetClusterCoreRef.type => if (coreSupervisor.isEmpty) createChildren() coreSupervisor.foreach(_ forward msg) - case AddOnMemberUpListener(code) ⇒ + case AddOnMemberUpListener(code) => context.actorOf(Props(classOf[OnMemberStatusChangedListener], code, Up).withDeploy(Deploy.local)) - case AddOnMemberRemovedListener(code) ⇒ + case AddOnMemberRemovedListener(code) => context.actorOf(Props(classOf[OnMemberStatusChangedListener], code, Removed).withDeploy(Deploy.local)) - case CoordinatedShutdownLeave.LeaveReq ⇒ + case CoordinatedShutdownLeave.LeaveReq => val ref = context.actorOf(CoordinatedShutdownLeave.props().withDispatcher(context.props.dispatcher)) // forward the ask request ref.forward(CoordinatedShutdownLeave.LeaveReq) @@ -262,7 +262,7 @@ private[cluster] final class ClusterCoreSupervisor(joinConfigCompatChecker: Join override val supervisorStrategy = OneForOneStrategy() { - case NonFatal(e) ⇒ + case NonFatal(e) => Cluster(context.system).ClusterLogger.logError( e, "crashed, [{}] - shutting down...", e.getMessage) self ! PoisonPill @@ -272,7 +272,7 @@ private[cluster] final class ClusterCoreSupervisor(joinConfigCompatChecker: Join override def postStop(): Unit = Cluster(context.system).shutdown() def receive = { - case InternalClusterAction.GetClusterCoreRef ⇒ + case InternalClusterAction.GetClusterCoreRef => if (coreDaemon.isEmpty) createChildren() coreDaemon.foreach(sender() ! _) @@ -339,7 +339,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh var exitingTasksInProgress = false val selfExiting = Promise[Done]() val coordShutdown = CoordinatedShutdown(context.system) - coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExiting, "wait-exiting") { () ⇒ + coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExiting, "wait-exiting") { () => if (latestGossip.members.isEmpty) Future.successful(Done) // not joined yet else @@ -347,7 +347,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } coordShutdown.addTask(CoordinatedShutdown.PhaseClusterExitingDone, "exiting-completed") { val sys = context.system - () ⇒ + () => if (Cluster(sys).isTerminated || Cluster(sys).selfMember.status == Down) Future.successful(Done) else { @@ -382,15 +382,15 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh // start periodic publish of current stats val publishStatsTask: Option[Cancellable] = PublishStatsInterval match { - case Duration.Zero | _: Duration.Infinite ⇒ None - case d: FiniteDuration ⇒ + case Duration.Zero | _: Duration.Infinite => None + case d: FiniteDuration => Some(scheduler.schedule(PeriodicTasksInitialDelay.max(d), d, self, PublishStatsTick)) } override def preStart(): Unit = { context.system.eventStream.subscribe(self, classOf[QuarantinedEvent]) - cluster.downingProvider.downingActorProps.foreach { props ⇒ + cluster.downingProvider.downingActorProps.foreach { props => val propsWithDispatcher = if (props.dispatcher == Deploy.NoDispatcherGiven) props.withDispatcher(context.props.dispatcher) else props @@ -427,38 +427,38 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } def uninitialized: Actor.Receive = ({ - case InitJoin ⇒ + case InitJoin => logInfo("Received InitJoin message from [{}], but this node is not initialized yet", sender()) sender() ! InitJoinNack(selfAddress) - case ClusterUserAction.JoinTo(address) ⇒ + case ClusterUserAction.JoinTo(address) => join(address) - case JoinSeedNodes(newSeedNodes) ⇒ + case JoinSeedNodes(newSeedNodes) => resetJoinSeedNodesDeadline() joinSeedNodes(newSeedNodes) - case msg: SubscriptionMessage ⇒ + case msg: SubscriptionMessage => publisher forward msg - case Welcome(from, gossip) ⇒ + case Welcome(from, gossip) => welcome(from.address, from, gossip) - case _: Tick ⇒ + case _: Tick => if (joinSeedNodesDeadline.exists(_.isOverdue)) joinSeedNodesWasUnsuccessful() }: Actor.Receive).orElse(receiveExitingCompleted) def tryingToJoin(joinWith: Address, deadline: Option[Deadline]): Actor.Receive = ({ - case Welcome(from, gossip) ⇒ + case Welcome(from, gossip) => welcome(joinWith, from, gossip) - case InitJoin ⇒ + case InitJoin => logInfo("Received InitJoin message from [{}], but this node is not a member yet", sender()) sender() ! InitJoinNack(selfAddress) - case ClusterUserAction.JoinTo(address) ⇒ + case ClusterUserAction.JoinTo(address) => becomeUninitialized() join(address) - case JoinSeedNodes(newSeedNodes) ⇒ + case JoinSeedNodes(newSeedNodes) => resetJoinSeedNodesDeadline() becomeUninitialized() joinSeedNodes(newSeedNodes) - case msg: SubscriptionMessage ⇒ publisher forward msg - case _: Tick ⇒ + case msg: SubscriptionMessage => publisher forward msg + case _: Tick => if (joinSeedNodesDeadline.exists(_.isOverdue)) joinSeedNodesWasUnsuccessful() else if (deadline.exists(_.isOverdue)) { @@ -471,8 +471,8 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh private def resetJoinSeedNodesDeadline(): Unit = { joinSeedNodesDeadline = ShutdownAfterUnsuccessfulJoinSeedNodes match { - case d: FiniteDuration ⇒ Some(Deadline.now + d) - case _ ⇒ None // off + case d: FiniteDuration => Some(Deadline.now + d) + case _ => None // off } } @@ -507,33 +507,33 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } def initialized: Actor.Receive = ({ - case msg: GossipEnvelope ⇒ receiveGossip(msg) - case msg: GossipStatus ⇒ receiveGossipStatus(msg) - case GossipTick ⇒ gossipTick() - case GossipSpeedupTick ⇒ gossipSpeedupTick() - case ReapUnreachableTick ⇒ reapUnreachableMembers() - case LeaderActionsTick ⇒ leaderActions() - case PublishStatsTick ⇒ publishInternalStats() - case InitJoin(joiningNodeConfig) ⇒ + case msg: GossipEnvelope => receiveGossip(msg) + case msg: GossipStatus => receiveGossipStatus(msg) + case GossipTick => gossipTick() + case GossipSpeedupTick => gossipSpeedupTick() + case ReapUnreachableTick => reapUnreachableMembers() + case LeaderActionsTick => leaderActions() + case PublishStatsTick => publishInternalStats() + case InitJoin(joiningNodeConfig) => logInfo("Received InitJoin message from [{}] to [{}]", sender(), selfAddress) initJoin(joiningNodeConfig) - case Join(node, roles) ⇒ joining(node, roles) - case ClusterUserAction.Down(address) ⇒ downing(address) - case ClusterUserAction.Leave(address) ⇒ leaving(address) - case SendGossipTo(address) ⇒ sendGossipTo(address) - case msg: SubscriptionMessage ⇒ publisher forward msg - case QuarantinedEvent(address, uid) ⇒ quarantined(UniqueAddress(address, uid)) - case ClusterUserAction.JoinTo(address) ⇒ + case Join(node, roles) => joining(node, roles) + case ClusterUserAction.Down(address) => downing(address) + case ClusterUserAction.Leave(address) => leaving(address) + case SendGossipTo(address) => sendGossipTo(address) + case msg: SubscriptionMessage => publisher forward msg + case QuarantinedEvent(address, uid) => quarantined(UniqueAddress(address, uid)) + case ClusterUserAction.JoinTo(address) => logInfo("Trying to join [{}] when already part of a cluster, ignoring", address) - case JoinSeedNodes(nodes) ⇒ + case JoinSeedNodes(nodes) => logInfo( "Trying to join seed nodes [{}] when already part of a cluster, ignoring", nodes.mkString(", ")) - case ExitingConfirmed(address) ⇒ receiveExitingConfirmed(address) + case ExitingConfirmed(address) => receiveExitingConfirmed(address) }: Actor.Receive).orElse(receiveExitingCompleted) def receiveExitingCompleted: Actor.Receive = { - case ExitingCompleted ⇒ + case ExitingCompleted => exitingCompleted() sender() ! Done // reply to ask } @@ -541,11 +541,11 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def receive = uninitialized override def unhandled(message: Any): Unit = message match { - case _: Tick ⇒ - case _: GossipEnvelope ⇒ - case _: GossipStatus ⇒ - case _: ExitingConfirmed ⇒ - case other ⇒ super.unhandled(other) + case _: Tick => + case _: GossipEnvelope => + case _: GossipStatus => + case _: ExitingConfirmed => + case other => super.unhandled(other) } def initJoin(joiningNodeConfig: Config): Unit = { @@ -577,7 +577,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh val configCheckReply = joinConfigCompatChecker.check(joiningNodeConfig, configWithoutSensitiveKeys) match { - case Valid ⇒ + case Valid => if (configCheckUnsupportedByJoiningNode) ConfigCheckUnsupportedByJoiningNode else { @@ -588,7 +588,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh val clusterConfig = JoinConfigCompatChecker.filterWithKeys(nonSensitiveKeys, context.system.settings.config) CompatibleConfig(clusterConfig) } - case Invalid(messages) ⇒ + case Invalid(messages) => // messages are only logged on the cluster side logWarning( "Found incompatible settings when [{}] tried to join: {}. " + @@ -655,8 +655,8 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh joining(selfUniqueAddress, cluster.selfRoles) } else { val joinDeadline = RetryUnsuccessfulJoinAfter match { - case d: FiniteDuration ⇒ Some(Deadline.now + d) - case _ ⇒ None + case d: FiniteDuration => Some(Deadline.now + d) + case _ => None } context.become(tryingToJoin(address, joinDeadline)) clusterCore(address) ! Join(selfUniqueAddress, cluster.selfRoles) @@ -666,11 +666,11 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def stopSeedNodeProcess(): Unit = { seedNodeProcess match { - case Some(s) ⇒ + case Some(s) => // manual join, abort current seedNodeProcess context stop s seedNodeProcess = None - case None ⇒ // no seedNodeProcess in progress + case None => // no seedNodeProcess in progress } } @@ -697,12 +697,12 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh // check by address without uid to make sure that node with same host:port is not allowed // to join until previous node with that host:port has been removed from the cluster localMembers.find(_.address == joiningNode.address) match { - case Some(m) if m.uniqueAddress == joiningNode ⇒ + case Some(m) if m.uniqueAddress == joiningNode => // node retried join attempt, probably due to lost Welcome message logInfo("Existing member [{}] is joining again.", m) if (joiningNode != selfUniqueAddress) sender() ! Welcome(selfUniqueAddress, latestGossip) - case Some(m) ⇒ + case Some(m) => // node restarted, same host:port as existing member, but with different uid // safe to down and later remove existing member // new node will retry join @@ -717,7 +717,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh downing(m.address) } - case None ⇒ + case None => // remove the node from the failure detector failureDetector.remove(joiningNode.address) crossDcFailureDetector.remove(joiningNode.address) @@ -768,8 +768,8 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh */ def leaving(address: Address): Unit = { // only try to update if the node is available (in the member ring) - if (latestGossip.members.exists(m ⇒ m.address == address && (m.status == Joining || m.status == WeaklyUp || m.status == Up))) { - val newMembers = latestGossip.members map { m ⇒ if (m.address == address) m.copy(status = Leaving) else m } // mark node as LEAVING + if (latestGossip.members.exists(m => m.address == address && (m.status == Joining || m.status == WeaklyUp || m.status == Up))) { + val newMembers = latestGossip.members map { m => if (m.address == address) m.copy(status = Leaving) else m } // mark node as LEAVING val newGossip = latestGossip copy (members = newMembers) updateLatestGossip(newGossip) @@ -804,14 +804,14 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh val membersExceptSelf = latestGossip.members.filter(_.uniqueAddress != selfUniqueAddress) membershipState.leaderOf(membersExceptSelf) match { - case Some(node1) ⇒ + case Some(node1) => clusterCore(node1.address) ! ExitingConfirmed(selfUniqueAddress) membershipState.leaderOf(membersExceptSelf.filterNot(_.uniqueAddress == node1)) match { - case Some(node2) ⇒ + case Some(node2) => clusterCore(node2.address) ! ExitingConfirmed(selfUniqueAddress) - case None ⇒ // no more potential leader + case None => // no more potential leader } - case None ⇒ // no leader + case None => // no leader } shutdown() @@ -825,7 +825,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def cleanupExitingConfirmed(): Unit = { // in case the actual removal was performed by another leader node we if (exitingConfirmed.nonEmpty) - exitingConfirmed = exitingConfirmed.filter(n ⇒ latestGossip.members.exists(_.uniqueAddress == n)) + exitingConfirmed = exitingConfirmed.filter(n => latestGossip.members.exists(_.uniqueAddress == n)) } /** @@ -847,7 +847,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh // check if the node to DOWN is in the `members` set localMembers.find(_.address == address) match { - case Some(m) if m.status != Down ⇒ + case Some(m) if m.status != Down => if (localReachability.isReachable(m.uniqueAddress)) logInfo("Marking node [{}] as [{}]", m.address, Down) else @@ -856,8 +856,8 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh val newGossip = localGossip.markAsDown(m) updateLatestGossip(newGossip) publishMembershipState() - case Some(_) ⇒ // already down - case None ⇒ + case Some(_) => // already down + case None => logInfo("Ignoring down of unknown node [{}]", address) } @@ -886,9 +886,9 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh logInfo("Ignoring received gossip status from unreachable [{}] ", from) else { (status.version compareTo latestGossip.version) match { - case VectorClock.Same ⇒ // same version - case VectorClock.After ⇒ gossipStatusTo(from, sender()) // remote is newer - case _ ⇒ gossipTo(from, sender()) // conflicting or local is newer + case VectorClock.Same => // same version + case VectorClock.After => gossipStatusTo(from, sender()) // remote is newer + case _ => gossipTo(from, sender()) // conflicting or local is newer } } } @@ -931,31 +931,31 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh val comparison = remoteGossip.version compareTo localGossip.version val (winningGossip, talkback, gossipType) = comparison match { - case VectorClock.Same ⇒ + case VectorClock.Same => // same version val talkback = !exitingTasksInProgress && !remoteGossip.seenByNode(selfUniqueAddress) (remoteGossip mergeSeen localGossip, talkback, Same) - case VectorClock.Before ⇒ + case VectorClock.Before => // local is newer (localGossip, true, Older) - case VectorClock.After ⇒ + case VectorClock.After => // remote is newer val talkback = !exitingTasksInProgress && !remoteGossip.seenByNode(selfUniqueAddress) (remoteGossip, talkback, Newer) - case _ ⇒ + case _ => // conflicting versions, merge // We can see that a removal was done when it is not in one of the gossips has status // Down or Exiting in the other gossip. // Perform the same pruning (clear of VectorClock) as the leader did when removing a member. // Removal of member itself is handled in merge (pickHighestPriority) - val prunedLocalGossip = localGossip.members.foldLeft(localGossip) { (g, m) ⇒ + val prunedLocalGossip = localGossip.members.foldLeft(localGossip) { (g, m) => if (removeUnreachableWithMemberStatus(m.status) && !remoteGossip.members.contains(m)) { logDebug("Pruned conflicting local gossip: {}", m) g.prune(VectorClock.Node(Gossip.vclockName(m.uniqueAddress))) } else g } - val prunedRemoteGossip = remoteGossip.members.foldLeft(remoteGossip) { (g, m) ⇒ + val prunedRemoteGossip = remoteGossip.members.foldLeft(remoteGossip) { (g, m) => if (removeUnreachableWithMemberStatus(m.status) && !localGossip.members.contains(m)) { logDebug("Pruned conflicting remote gossip: {}", m) g.prune(VectorClock.Node(Gossip.vclockName(m.uniqueAddress))) @@ -976,7 +976,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh // for all new nodes we remove them from the failure detector latestGossip.members foreach { - node ⇒ + node => if (!localGossip.members(node)) { failureDetector.remove(node.address) crossDcFailureDetector.remove(node.address) @@ -993,11 +993,11 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh if (statsEnabled) { gossipStats = gossipType match { - case Merge ⇒ gossipStats.incrementMergeCount - case Same ⇒ gossipStats.incrementSameCount - case Newer ⇒ gossipStats.incrementNewerCount - case Older ⇒ gossipStats.incrementOlderCount - case Ignored ⇒ gossipStats // included in receivedGossipCount + case Merge => gossipStats.incrementMergeCount + case Same => gossipStats.incrementSameCount + case Newer => gossipStats.incrementNewerCount + case Older => gossipStats.incrementOlderCount + case Ignored => gossipStats // included in receivedGossipCount } } @@ -1056,13 +1056,13 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def gossip(): Unit = if (!isSingletonCluster) { gossipTargetSelector.gossipTarget(membershipState) match { - case Some(peer) ⇒ + case Some(peer) => if (!membershipState.isInSameDc(peer) || latestGossip.seenByNode(peer)) // avoid transferring the full state if possible gossipStatusTo(peer) else gossipTo(peer) - case None ⇒ // nothing to see here + case None => // nothing to see here if (cluster.settings.Debug.VerboseGossipLogging) logDebug("will not gossip this round") @@ -1096,7 +1096,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh "Leader can currently not perform its duties, reachability status: [{}], member status: [{}]", membershipState.dcReachabilityExcludingDownedObservers, latestGossip.members.collect { - case m if m.dataCenter == selfDc ⇒ + case m if m.dataCenter == selfDc => s"${m.address} ${m.status} seen=${latestGossip.seenByNode(m.uniqueAddress)}" }.mkString(", ")) } @@ -1113,8 +1113,8 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh // When all reachable have seen the state this member will shutdown itself when it has // status Down. The down commands should spread before we shutdown. val unreachable = membershipState.dcReachability.allUnreachableOrTerminated - val downed = membershipState.dcMembers.collect { case m if m.status == Down ⇒ m.uniqueAddress } - if (selfDownCounter >= MaxTicksBeforeShuttingDownMyself || downed.forall(node ⇒ unreachable(node) || latestGossip.seenByNode(node))) { + val downed = membershipState.dcMembers.collect { case m if m.status == Down => m.uniqueAddress } + if (selfDownCounter >= MaxTicksBeforeShuttingDownMyself || downed.forall(node => unreachable(node) || latestGossip.seenByNode(node))) { // the reason for not shutting down immediately is to give the gossip a chance to spread // the downing information to other downed nodes, so that they can shutdown themselves logInfo("Shutting down myself") @@ -1130,7 +1130,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def isMinNrOfMembersFulfilled: Boolean = { latestGossip.members.size >= MinNrOfMembers && MinNrOfMembersOfRole.forall { - case (role, threshold) ⇒ latestGossip.members.count(_.hasRole(role)) >= threshold + case (role, threshold) => latestGossip.members.count(_.hasRole(role)) >= threshold } } @@ -1150,19 +1150,19 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def leaderActionsOnConvergence(): Unit = { val removedUnreachable = for { - node ← membershipState.dcReachability.allUnreachableOrTerminated + node <- membershipState.dcReachability.allUnreachableOrTerminated m = latestGossip.member(node) if m.dataCenter == selfDc && removeUnreachableWithMemberStatus(m.status) } yield m - val removedExitingConfirmed = exitingConfirmed.filter { n ⇒ + val removedExitingConfirmed = exitingConfirmed.filter { n => val member = latestGossip.member(n) member.dataCenter == selfDc && member.status == Exiting } val removedOtherDc = if (latestGossip.isMultiDc) { - latestGossip.members.filter { m ⇒ + latestGossip.members.filter { m => (m.dataCenter != selfDc && removeUnreachableWithMemberStatus(m.status)) } } else @@ -1176,7 +1176,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh var upNumber = 0 { - case m if m.dataCenter == selfDc && isJoiningToUp(m) ⇒ + case m if m.dataCenter == selfDc && isJoiningToUp(m) => // Move JOINING => UP (once all nodes have seen that this node is JOINING, i.e. we have a convergence) // and minimum number of nodes have joined the cluster if (upNumber == 0) { @@ -1189,7 +1189,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } m.copyUp(upNumber) - case m if m.dataCenter == selfDc && m.status == Leaving ⇒ + case m if m.dataCenter == selfDc && m.status == Leaving => // Move LEAVING => EXITING (once we have a convergence on LEAVING) m copy (status = Exiting) } @@ -1219,17 +1219,17 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh exitingConfirmed = exitingConfirmed.filterNot(removedExitingConfirmed) - changedMembers foreach { m ⇒ + changedMembers foreach { m => logInfo("Leader is moving node [{}] to [{}]", m.address, m.status) } - removedUnreachable foreach { m ⇒ + removedUnreachable foreach { m => val status = if (m.status == Exiting) "exiting" else "unreachable" logInfo("Leader is removing {} node [{}]", status, m.address) } - removedExitingConfirmed.foreach { n ⇒ + removedExitingConfirmed.foreach { n => logInfo("Leader is removing confirmed Exiting node [{}]", n.address) } - removedOtherDc foreach { m ⇒ + removedOtherDc foreach { m => logInfo("Leader is removing {} node [{}] in DC [{}]", m.status, m.address, m.dataCenter) } @@ -1257,7 +1257,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh "Gossip exiting members [{}] to the two oldest (per role) [{}] (singleton optimization).", exitingMembers.mkString(", "), targets.mkString(", ")) - targets.foreach(m ⇒ gossipTo(m.uniqueAddress)) + targets.foreach(m => gossipTo(m.uniqueAddress)) } } @@ -1272,7 +1272,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh enoughMembers && membershipState.dcReachabilityExcludingDownedObservers.isReachable(m.uniqueAddress) val changedMembers = localMembers.collect { - case m if isJoiningToWeaklyUp(m) ⇒ m.copy(status = WeaklyUp) + case m if isJoiningToWeaklyUp(m) => m.copy(status = WeaklyUp) } if (changedMembers.nonEmpty) { @@ -1280,7 +1280,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh updateLatestGossip(newGossip) // log status changes - changedMembers foreach { m ⇒ + changedMembers foreach { m => logInfo("Leader is moving node [{}] to [{}]", m.address, m.status) } @@ -1305,7 +1305,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh else crossDcFailureDetector.isAvailable(member.address) } - val newlyDetectedUnreachableMembers = localMembers filterNot { member ⇒ + val newlyDetectedUnreachableMembers = localMembers filterNot { member => member.uniqueAddress == selfUniqueAddress || localOverview.reachability.status(selfUniqueAddress, member.uniqueAddress) == Reachability.Unreachable || localOverview.reachability.status(selfUniqueAddress, member.uniqueAddress) == Reachability.Terminated || @@ -1313,17 +1313,17 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } val newlyDetectedReachableMembers = localOverview.reachability.allUnreachableFrom(selfUniqueAddress) collect { - case node if node != selfUniqueAddress && isAvailable(localGossip.member(node)) ⇒ + case node if node != selfUniqueAddress && isAvailable(localGossip.member(node)) => localGossip.member(node) } if (newlyDetectedUnreachableMembers.nonEmpty || newlyDetectedReachableMembers.nonEmpty) { val newReachability1 = newlyDetectedUnreachableMembers.foldLeft(localOverview.reachability) { - (reachability, m) ⇒ reachability.unreachable(selfUniqueAddress, m.uniqueAddress) + (reachability, m) => reachability.unreachable(selfUniqueAddress, m.uniqueAddress) } val newReachability2 = newlyDetectedReachableMembers.foldLeft(newReachability1) { - (reachability, m) ⇒ reachability.reachable(selfUniqueAddress, m.uniqueAddress) + (reachability, m) => reachability.reachable(selfUniqueAddress, m.uniqueAddress) } if (newReachability2 ne localOverview.reachability) { @@ -1352,7 +1352,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh // needed for tests def sendGossipTo(address: Address): Unit = { - latestGossip.members.foreach(m ⇒ + latestGossip.members.foreach(m => if (m.address == address) gossipTo(m.uniqueAddress)) } @@ -1411,7 +1411,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def publishInternalStats(): Unit = { val vclockStats = VectorClockStats( versionSize = latestGossip.version.versions.size, - seenLatest = latestGossip.members.count(m ⇒ latestGossip.seenByNode(m.uniqueAddress))) + seenLatest = latestGossip.members.count(m => latestGossip.seenByNode(m.uniqueAddress))) publisher ! CurrentInternalStats(gossipStats, vclockStats) } @@ -1460,13 +1460,13 @@ private[cluster] final class FirstSeedNodeProcess(seedNodes: immutable.IndexedSe override def postStop(): Unit = retryTask.cancel() def receive = { - case JoinSeedNode ⇒ + case JoinSeedNode => if (timeout.hasTimeLeft) { val requiredNonSensitiveKeys = JoinConfigCompatChecker.removeSensitiveKeys(joinConfigCompatChecker.requiredKeys, cluster.settings) // configToValidate only contains the keys that are required according to JoinConfigCompatChecker on this node val configToValidate = JoinConfigCompatChecker.filterWithKeys(requiredNonSensitiveKeys, context.system.settings.config) // send InitJoin to remaining seed nodes (except myself) - remainingSeedNodes foreach { a ⇒ context.actorSelection(context.parent.path.toStringWithAddress(a)) ! InitJoin(configToValidate) } + remainingSeedNodes foreach { a => context.actorSelection(context.parent.path.toStringWithAddress(a)) ! InitJoin(configToValidate) } } else { // no InitJoinAck received, initialize new cluster by joining myself if (isDebugEnabled) @@ -1477,22 +1477,22 @@ private[cluster] final class FirstSeedNodeProcess(seedNodes: immutable.IndexedSe context.stop(self) } - case InitJoinAck(address, CompatibleConfig(clusterConfig)) ⇒ + case InitJoinAck(address, CompatibleConfig(clusterConfig)) => logInfo("Received InitJoinAck message from [{}] to [{}]", sender(), selfAddress) // validates config coming from cluster against this node config joinConfigCompatChecker.check(clusterConfig, context.system.settings.config) match { - case Valid ⇒ + case Valid => // first InitJoinAck reply context.parent ! JoinTo(address) context.stop(self) - case Invalid(messages) if ByPassConfigCompatCheck ⇒ + case Invalid(messages) if ByPassConfigCompatCheck => logWarning("Cluster validated this node config, but sent back incompatible settings: {}. " + "Join will be performed because compatibility check is configured to not be enforced.", messages.mkString(", ")) context.parent ! JoinTo(address) context.stop(self) - case Invalid(messages) ⇒ + case Invalid(messages) => logError("Cluster validated this node config, but sent back incompatible settings: {}. " + "It's recommended to perform a full cluster shutdown in order to deploy this new version. " + "If a cluster shutdown isn't an option, you may want to disable this protection by setting " + @@ -1503,13 +1503,13 @@ private[cluster] final class FirstSeedNodeProcess(seedNodes: immutable.IndexedSe CoordinatedShutdown(context.system).run(IncompatibleConfigurationDetected) } - case InitJoinAck(address, UncheckedConfig) ⇒ + case InitJoinAck(address, UncheckedConfig) => logInfo("Received InitJoinAck message from [{}] to [{}]", sender(), selfAddress) logWarning("Joining a cluster without configuration compatibility check feature.") context.parent ! JoinTo(address) context.stop(self) - case InitJoinAck(address, IncompatibleConfig) ⇒ + case InitJoinAck(address, IncompatibleConfig) => // first InitJoinAck reply, but incompatible if (ByPassConfigCompatCheck) { // only join if set to ignore config validation @@ -1530,7 +1530,7 @@ private[cluster] final class FirstSeedNodeProcess(seedNodes: immutable.IndexedSe CoordinatedShutdown(context.system).run(IncompatibleConfigurationDetected) } - case InitJoinNack(address) ⇒ + case InitJoinNack(address) => logInfo("Received InitJoinNack message from [{}] to [{}]", sender(), selfAddress) remainingSeedNodes -= address if (remainingSeedNodes.isEmpty) { @@ -1589,30 +1589,30 @@ private[cluster] final class JoinSeedNodeProcess(seedNodes: immutable.IndexedSeq override def preStart(): Unit = self ! JoinSeedNode def receive = { - case JoinSeedNode ⇒ + case JoinSeedNode => val requiredNonSensitiveKeys = JoinConfigCompatChecker.removeSensitiveKeys(joinConfigCompatChecker.requiredKeys, cluster.settings) // configToValidate only contains the keys that are required according to JoinConfigCompatChecker on this node val configToValidate = JoinConfigCompatChecker.filterWithKeys(requiredNonSensitiveKeys, context.system.settings.config) // send InitJoin to all seed nodes (except myself) attempt += 1 - otherSeedNodes.foreach { a ⇒ context.actorSelection(context.parent.path.toStringWithAddress(a)) ! InitJoin(configToValidate) } + otherSeedNodes.foreach { a => context.actorSelection(context.parent.path.toStringWithAddress(a)) ! InitJoin(configToValidate) } - case InitJoinAck(address, CompatibleConfig(clusterConfig)) ⇒ + case InitJoinAck(address, CompatibleConfig(clusterConfig)) => logInfo("Received InitJoinAck message from [{}] to [{}]", sender(), selfAddress) // validates config coming from cluster against this node config joinConfigCompatChecker.check(clusterConfig, context.system.settings.config) match { - case Valid ⇒ + case Valid => // first InitJoinAck reply context.parent ! JoinTo(address) context.become(done) - case Invalid(messages) if ByPassConfigCompatCheck ⇒ + case Invalid(messages) if ByPassConfigCompatCheck => logWarning("Cluster validated this node config, but sent back incompatible settings: {}. " + "Join will be performed because compatibility check is configured to not be enforced.", messages.mkString(", ")) context.parent ! JoinTo(address) context.become(done) - case Invalid(messages) ⇒ + case Invalid(messages) => logError("Cluster validated this node config, but sent back incompatible settings: {}. " + "It's recommended to perform a full cluster shutdown in order to deploy this new version. " + "If a cluster shutdown isn't an option, you may want to disable this protection by setting " + @@ -1623,12 +1623,12 @@ private[cluster] final class JoinSeedNodeProcess(seedNodes: immutable.IndexedSeq CoordinatedShutdown(context.system).run(IncompatibleConfigurationDetected) } - case InitJoinAck(address, UncheckedConfig) ⇒ + case InitJoinAck(address, UncheckedConfig) => logWarning("Joining a cluster without configuration compatibility check feature.") context.parent ! JoinTo(address) context.become(done) - case InitJoinAck(address, IncompatibleConfig) ⇒ + case InitJoinAck(address, IncompatibleConfig) => // first InitJoinAck reply, but incompatible if (ByPassConfigCompatCheck) { logInfo("Received InitJoinAck message from [{}] to [{}]", sender(), selfAddress) @@ -1649,9 +1649,9 @@ private[cluster] final class JoinSeedNodeProcess(seedNodes: immutable.IndexedSeq CoordinatedShutdown(context.system).run(IncompatibleConfigurationDetected) } - case InitJoinNack(_) ⇒ // that seed was uninitialized + case InitJoinNack(_) => // that seed was uninitialized - case ReceiveTimeout ⇒ + case ReceiveTimeout => if (attempt >= 2) logWarning( "Couldn't join seed nodes after [{}] attempts, will try again. seed-nodes=[{}]", @@ -1661,8 +1661,8 @@ private[cluster] final class JoinSeedNodeProcess(seedNodes: immutable.IndexedSeq } def done: Actor.Receive = { - case InitJoinAck(_, _) ⇒ // already received one, skip rest - case ReceiveTimeout ⇒ context.stop(self) + case InitJoinAck(_, _) => // already received one, skip rest + case ReceiveTimeout => context.stop(self) } } @@ -1678,9 +1678,9 @@ private[cluster] class OnMemberStatusChangedListener(callback: Runnable, status: import cluster.ClusterLogger._ private val to = status match { - case Up ⇒ classOf[MemberUp] - case Removed ⇒ classOf[MemberRemoved] - case other ⇒ throw new IllegalArgumentException( + case Up => classOf[MemberUp] + case Removed => classOf[MemberRemoved] + case other => throw new IllegalArgumentException( s"Expected Up or Removed in OnMemberStatusChangedListener, got [$other]") } @@ -1694,20 +1694,20 @@ private[cluster] class OnMemberStatusChangedListener(callback: Runnable, status: } def receive = { - case state: CurrentClusterState ⇒ + case state: CurrentClusterState => if (state.members.exists(isTriggered)) done() - case MemberUp(member) ⇒ + case MemberUp(member) => if (isTriggered(member)) done() - case MemberRemoved(member, _) ⇒ + case MemberRemoved(member, _) => if (isTriggered(member)) done() } private def done(): Unit = { try callback.run() catch { - case NonFatal(e) ⇒ logError(e, "[{}] callback failed with [{}]", s"On${to.getSimpleName}", e.getMessage) + case NonFatal(e) => logError(e, "[{}] callback failed with [{}]", s"On${to.getSimpleName}", e.getMessage) } finally { context stop self } diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterEvent.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterEvent.scala index 3d1430f931..c80189e88c 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterEvent.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterEvent.scala @@ -186,19 +186,19 @@ object ClusterEvent { new CurrentClusterState(members, unreachable, seenBy, leader, roleLeaderMap, unreachableDataCenters) override def equals(other: Any): Boolean = other match { - case that: CurrentClusterState ⇒ + case that: CurrentClusterState => (this eq that) || ( members == that.members && unreachable == that.unreachable && seenBy == that.seenBy && leader == that.leader && roleLeaderMap == that.roleLeaderMap) - case _ ⇒ false + case _ => false } override def hashCode(): Int = { val state = Seq(members, unreachable, seenBy, leader, roleLeaderMap) - state.map(_.hashCode()).foldLeft(0)((a, b) ⇒ 31 * a + b) + state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) } // Product5 @@ -381,7 +381,7 @@ object ClusterEvent { val newGossip = newState.latestGossip val oldUnreachableNodes = oldState.dcReachabilityNoOutsideNodes.allUnreachableOrTerminated newState.dcReachabilityNoOutsideNodes.allUnreachableOrTerminated.iterator.collect { - case node if !oldUnreachableNodes.contains(node) && node != newState.selfUniqueAddress ⇒ + case node if !oldUnreachableNodes.contains(node) && node != newState.selfUniqueAddress => UnreachableMember(newGossip.member(node)) }.to(immutable.IndexedSeq) } @@ -394,7 +394,7 @@ object ClusterEvent { else { val newGossip = newState.latestGossip oldState.dcReachabilityNoOutsideNodes.allUnreachable.iterator.collect { - case node if newGossip.hasMember(node) && newState.dcReachabilityNoOutsideNodes.isReachable(node) && node != newState.selfUniqueAddress ⇒ + case node if newGossip.hasMember(node) && newState.dcReachabilityNoOutsideNodes.isReachable(node) && node != newState.selfUniqueAddress => ReachableMember(newGossip.member(node)) }.to(immutable.IndexedSeq) } @@ -404,7 +404,7 @@ object ClusterEvent { */ private[cluster] def isReachable(state: MembershipState, oldUnreachableNodes: Set[UniqueAddress])(otherDc: DataCenter): Boolean = { val unrelatedDcNodes = state.latestGossip.members.collect { - case m if m.dataCenter != otherDc && m.dataCenter != state.selfDc ⇒ m.uniqueAddress + case m if m.dataCenter != otherDc && m.dataCenter != state.selfDc => m.uniqueAddress } val reachabilityForOtherDc = state.dcReachabilityWithoutObservationsWithin.remove(unrelatedDcNodes) @@ -448,22 +448,22 @@ object ClusterEvent { val newMembers = newGossip.members diff oldGossip.members val membersGroupedByAddress = List(newGossip.members, oldGossip.members).flatten.groupBy(_.uniqueAddress) val changedMembers = membersGroupedByAddress collect { - case (_, newMember :: oldMember :: Nil) if newMember.status != oldMember.status || newMember.upNumber != oldMember.upNumber ⇒ + case (_, newMember :: oldMember :: Nil) if newMember.status != oldMember.status || newMember.upNumber != oldMember.upNumber => newMember } import akka.util.ccompat.imm._ val memberEvents = (newMembers ++ changedMembers).unsorted collect { - case m if m.status == Joining ⇒ MemberJoined(m) - case m if m.status == WeaklyUp ⇒ MemberWeaklyUp(m) - case m if m.status == Up ⇒ MemberUp(m) - case m if m.status == Leaving ⇒ MemberLeft(m) - case m if m.status == Exiting ⇒ MemberExited(m) - case m if m.status == Down ⇒ MemberDowned(m) + case m if m.status == Joining => MemberJoined(m) + case m if m.status == WeaklyUp => MemberWeaklyUp(m) + case m if m.status == Up => MemberUp(m) + case m if m.status == Leaving => MemberLeft(m) + case m if m.status == Exiting => MemberExited(m) + case m if m.status == Down => MemberDowned(m) // no events for other transitions } val removedMembers = oldGossip.members diff newGossip.members - val removedEvents = removedMembers.unsorted.map(m ⇒ MemberRemoved(m.copy(status = Removed), m.status)) + val removedEvents = removedMembers.unsorted.map(m => MemberRemoved(m.copy(status = Removed), m.status)) (new VectorBuilder[MemberEvent]() ++= removedEvents ++= memberEvents).result() } @@ -484,7 +484,7 @@ object ClusterEvent { @InternalApi private[cluster] def diffRolesLeader(oldState: MembershipState, newState: MembershipState): Set[RoleLeaderChanged] = { for { - role ← oldState.latestGossip.allRoles union newState.latestGossip.allRoles + role <- oldState.latestGossip.allRoles union newState.latestGossip.allRoles newLeader = newState.roleLeader(role) if newLeader != oldState.roleLeader(role) } yield RoleLeaderChanged(role, newLeader.map(_.address)) @@ -544,12 +544,12 @@ private[cluster] final class ClusterDomainEventPublisher extends Actor with Acto } def receive = { - case PublishChanges(newState) ⇒ publishChanges(newState) - case currentStats: CurrentInternalStats ⇒ publishInternalStats(currentStats) - case SendCurrentClusterState(receiver) ⇒ sendCurrentClusterState(receiver) - case Subscribe(subscriber, initMode, to) ⇒ subscribe(subscriber, initMode, to) - case Unsubscribe(subscriber, to) ⇒ unsubscribe(subscriber, to) - case PublishEvent(event) ⇒ publish(event) + case PublishChanges(newState) => publishChanges(newState) + case currentStats: CurrentInternalStats => publishInternalStats(currentStats) + case SendCurrentClusterState(receiver) => sendCurrentClusterState(receiver) + case Subscribe(subscriber, initMode, to) => subscribe(subscriber, initMode, to) + case Unsubscribe(subscriber, to) => unsubscribe(subscriber, to) + case PublishEvent(event) => publish(event) } def eventStream: EventStream = context.system.eventStream @@ -561,7 +561,7 @@ private[cluster] final class ClusterDomainEventPublisher extends Actor with Acto def sendCurrentClusterState(receiver: ActorRef): Unit = { val unreachable: Set[Member] = membershipState.dcReachabilityNoOutsideNodes.allUnreachableOrTerminated.collect { - case node if node != selfUniqueAddress ⇒ membershipState.latestGossip.member(node) + case node if node != selfUniqueAddress => membershipState.latestGossip.member(node) } val unreachableDataCenters: Set[DataCenter] = @@ -573,21 +573,21 @@ private[cluster] final class ClusterDomainEventPublisher extends Actor with Acto unreachable = unreachable, seenBy = membershipState.latestGossip.seenBy.map(_.address), leader = membershipState.leader.map(_.address), - roleLeaderMap = membershipState.latestGossip.allRoles.iterator.map(r ⇒ - r → membershipState.roleLeader(r).map(_.address)).toMap, + roleLeaderMap = membershipState.latestGossip.allRoles.iterator.map(r => + r -> membershipState.roleLeader(r).map(_.address)).toMap, unreachableDataCenters) receiver ! state } def subscribe(subscriber: ActorRef, initMode: SubscriptionInitialStateMode, to: Set[Class[_]]): Unit = { initMode match { - case InitialStateAsEvents ⇒ + case InitialStateAsEvents => def pub(event: AnyRef): Unit = { if (to.exists(_.isAssignableFrom(event.getClass))) subscriber ! event } publishDiff(emptyMembershipState, membershipState, pub) - case InitialStateAsSnapshot ⇒ + case InitialStateAsSnapshot => sendCurrentClusterState(subscriber) } @@ -595,8 +595,8 @@ private[cluster] final class ClusterDomainEventPublisher extends Actor with Acto } def unsubscribe(subscriber: ActorRef, to: Option[Class[_]]): Unit = to match { - case None ⇒ eventStream.unsubscribe(subscriber) - case Some(c) ⇒ eventStream.unsubscribe(subscriber, c) + case None => eventStream.unsubscribe(subscriber) + case Some(c) => eventStream.unsubscribe(subscriber, c) } def publishChanges(newState: MembershipState): Unit = { @@ -606,7 +606,7 @@ private[cluster] final class ClusterDomainEventPublisher extends Actor with Acto publishDiff(oldState, newState, publish) } - def publishDiff(oldState: MembershipState, newState: MembershipState, pub: AnyRef ⇒ Unit): Unit = { + def publishDiff(oldState: MembershipState, newState: MembershipState, pub: AnyRef => Unit): Unit = { diffMemberEvents(oldState, newState) foreach pub diffUnreachable(oldState, newState) foreach pub diffReachable(oldState, newState) foreach pub diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterHeartbeat.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterHeartbeat.scala index 9703439a63..5126bb814d 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterHeartbeat.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterHeartbeat.scala @@ -32,7 +32,7 @@ private[cluster] final class ClusterHeartbeatReceiver extends Actor with ActorLo lazy val verboseHeartbeat = cluster.settings.Debug.VerboseHeartbeatLogging def receive = { - case Heartbeat(from) ⇒ + case Heartbeat(from) => if (verboseHeartbeat) cluster.ClusterLogger.logDebug("Heartbeat from [{}]", from) sender() ! selfHeartbeatRsp } @@ -85,7 +85,7 @@ private[cluster] final class ClusterHeartbeatSender extends Actor with ActorLogg import cluster.settings._ import context.dispatcher - val filterInternalClusterMembers: Member ⇒ Boolean = + val filterInternalClusterMembers: Member => Boolean = _.dataCenter == cluster.selfDataCenter val selfHeartbeat = Heartbeat(selfAddress) @@ -110,7 +110,7 @@ private[cluster] final class ClusterHeartbeatSender extends Actor with ActorLogg } override def postStop(): Unit = { - state.activeReceivers.foreach(a ⇒ failureDetector.remove(a.address)) + state.activeReceivers.foreach(a => failureDetector.remove(a.address)) heartbeatTask.cancel() cluster.unsubscribe(self) } @@ -124,26 +124,26 @@ private[cluster] final class ClusterHeartbeatSender extends Actor with ActorLogg def receive = initializing def initializing: Actor.Receive = { - case s: CurrentClusterState ⇒ + case s: CurrentClusterState => init(s) context.become(active) - case HeartbeatTick ⇒ + case HeartbeatTick => tickTimestamp = System.nanoTime() // start checks when active } def active: Actor.Receive = { - case HeartbeatTick ⇒ heartbeat() - case HeartbeatRsp(from) ⇒ heartbeatRsp(from) - case MemberRemoved(m, _) ⇒ removeMember(m) - case evt: MemberEvent ⇒ addMember(evt.member) - case UnreachableMember(m) ⇒ unreachableMember(m) - case ReachableMember(m) ⇒ reachableMember(m) - case ExpectedFirstHeartbeat(from) ⇒ triggerFirstHeartbeat(from) + case HeartbeatTick => heartbeat() + case HeartbeatRsp(from) => heartbeatRsp(from) + case MemberRemoved(m, _) => removeMember(m) + case evt: MemberEvent => addMember(evt.member) + case UnreachableMember(m) => unreachableMember(m) + case ReachableMember(m) => reachableMember(m) + case ExpectedFirstHeartbeat(from) => triggerFirstHeartbeat(from) } def init(snapshot: CurrentClusterState): Unit = { - val nodes = snapshot.members.collect { case m if filterInternalClusterMembers(m) ⇒ m.uniqueAddress } - val unreachable = snapshot.unreachable.collect { case m if filterInternalClusterMembers(m) ⇒ m.uniqueAddress } + val nodes = snapshot.members.collect { case m if filterInternalClusterMembers(m) => m.uniqueAddress } + val unreachable = snapshot.unreachable.collect { case m if filterInternalClusterMembers(m) => m.uniqueAddress } state = state.init(nodes, unreachable) } @@ -173,7 +173,7 @@ private[cluster] final class ClusterHeartbeatSender extends Actor with ActorLogg state = state.reachableMember(m.uniqueAddress) def heartbeat(): Unit = { - state.activeReceivers foreach { to ⇒ + state.activeReceivers foreach { to => if (failureDetector.isMonitoring(to.address)) { if (verboseHeartbeat) logDebug("Heartbeat to [{}]", to.address) } else { @@ -256,7 +256,7 @@ private[cluster] final case class ClusterHeartbeatSenderState( val oldReceivers = ring.myReceivers val removedReceivers = oldReceivers diff newRing.myReceivers var adjustedOldReceiversNowUnreachable = oldReceiversNowUnreachable - removedReceivers foreach { a ⇒ + removedReceivers foreach { a => if (failureDetector.isAvailable(a.address)) failureDetector remove a.address else @@ -296,7 +296,7 @@ private[cluster] final case class HeartbeatNodeRing( require(nodes contains selfAddress, s"nodes [${nodes.mkString(", ")}] must contain selfAddress [${selfAddress}]") private val nodeRing: immutable.SortedSet[UniqueAddress] = { - implicit val ringOrdering: Ordering[UniqueAddress] = Ordering.fromLessThan[UniqueAddress] { (a, b) ⇒ + implicit val ringOrdering: Ordering[UniqueAddress] = Ordering.fromLessThan[UniqueAddress] { (a, b) => val ha = a.## val hb = b.## ha < hb || (ha == hb && Member.addressOrdering.compare(a.address, b.address) < 0) diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterJmx.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterJmx.scala index 0e30739c57..5db449ab72 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterJmx.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterJmx.scala @@ -151,7 +151,7 @@ private[akka] class ClusterJmx(cluster: Cluster, log: LoggingAdapter) { // JMX attributes (bean-style) def getClusterStatus: String = { - val members = clusterView.members.toSeq.sorted(Member.ordering).map { m ⇒ + val members = clusterView.members.toSeq.sorted(Member.ordering).map { m => s"""{ | "address": "${m.address}", | "roles": [${if (m.roles.isEmpty) "" else m.roles.toList.sorted.map("\"" + _ + "\"").mkString("\n ", ",\n ", "\n ")}], @@ -160,7 +160,7 @@ private[akka] class ClusterJmx(cluster: Cluster, log: LoggingAdapter) { } mkString (",\n ") val unreachable = clusterView.reachability.observersGroupedByUnreachable.toSeq.sortBy(_._1).map { - case (subject, observers) ⇒ { + case (subject, observers) => { val observerAddresses = observers.toSeq.sorted.map("\"" + _.address + "\"") s"""{ | "node": "${subject.address}", @@ -204,7 +204,7 @@ private[akka] class ClusterJmx(cluster: Cluster, log: LoggingAdapter) { mBeanServer.registerMBean(mbean, clusterMBeanName) logInfo("Registered cluster JMX MBean [{}]", clusterMBeanName) } catch { - case e: InstanceAlreadyExistsException ⇒ { + case e: InstanceAlreadyExistsException => { if (cluster.settings.JmxMultiMbeansInSameEnabled) { log.error(e, s"Failed to register Cluster JMX MBean with name=$clusterMBeanName") } else { @@ -223,7 +223,7 @@ private[akka] class ClusterJmx(cluster: Cluster, log: LoggingAdapter) { try { mBeanServer.unregisterMBean(clusterMBeanName) } catch { - case e: InstanceNotFoundException ⇒ { + case e: InstanceNotFoundException => { if (cluster.settings.JmxMultiMbeansInSameEnabled) { log.error(e, s"Failed to unregister Cluster JMX MBean with name=$clusterMBeanName") } else { diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterReadView.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterReadView.scala index a045763c23..3c56975c90 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterReadView.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterReadView.scala @@ -54,20 +54,20 @@ private[akka] class ClusterReadView(cluster: Cluster) extends Closeable { override def postStop(): Unit = cluster.unsubscribe(self) def receive = { - case e: ClusterDomainEvent ⇒ + case e: ClusterDomainEvent => e match { - case SeenChanged(_, seenBy) ⇒ + case SeenChanged(_, seenBy) => _state = _state.copy(seenBy = seenBy) - case ReachabilityChanged(reachability) ⇒ + case ReachabilityChanged(reachability) => _reachability = reachability - case MemberRemoved(member, _) ⇒ + case MemberRemoved(member, _) => _state = _state.copy(members = _state.members - member, unreachable = _state.unreachable - member) - case UnreachableMember(member) ⇒ + case UnreachableMember(member) => // replace current member with new member (might have different status, only address is used in equals) _state = _state.copy(unreachable = _state.unreachable - member + member) - case ReachableMember(member) ⇒ + case ReachableMember(member) => _state = _state.copy(unreachable = _state.unreachable - member) - case event: MemberEvent ⇒ + case event: MemberEvent => // replace current member with new member (might have different status, only address is used in equals) val newUnreachable = if (_state.unreachable.contains(event.member)) _state.unreachable - event.member + event.member @@ -75,40 +75,40 @@ private[akka] class ClusterReadView(cluster: Cluster) extends Closeable { _state = _state.copy( members = _state.members - event.member + event.member, unreachable = newUnreachable) - case LeaderChanged(leader) ⇒ + case LeaderChanged(leader) => _state = _state.copy(leader = leader) - case RoleLeaderChanged(role, leader) ⇒ - _state = _state.copy(roleLeaderMap = _state.roleLeaderMap + (role → leader)) - case stats: CurrentInternalStats ⇒ _latestStats = stats - case ClusterShuttingDown ⇒ + case RoleLeaderChanged(role, leader) => + _state = _state.copy(roleLeaderMap = _state.roleLeaderMap + (role -> leader)) + case stats: CurrentInternalStats => _latestStats = stats + case ClusterShuttingDown => - case r: ReachableDataCenter ⇒ + case r: ReachableDataCenter => _state = _state.withUnreachableDataCenters(_state.unreachableDataCenters - r.dataCenter) - case r: UnreachableDataCenter ⇒ + case r: UnreachableDataCenter => _state = _state.withUnreachableDataCenters(_state.unreachableDataCenters + r.dataCenter) } e match { - case e: MemberEvent if e.member.address == selfAddress ⇒ + case e: MemberEvent if e.member.address == selfAddress => _cachedSelf match { - case OptionVal.Some(s) if s.status == MemberStatus.Removed && _closed ⇒ + case OptionVal.Some(s) if s.status == MemberStatus.Removed && _closed => // ignore as Cluster.close has been called - case _ ⇒ + case _ => _cachedSelf = OptionVal.Some(e.member) } - case _ ⇒ + case _ => } // once captured, optional verbose logging of event e match { - case _: SeenChanged ⇒ // ignore - case event ⇒ + case _: SeenChanged => // ignore + case event => if (cluster.settings.LogInfoVerbose) logInfo("event {}", event) } - case s: CurrentClusterState ⇒ _state = s + case s: CurrentClusterState => _state = s } }).withDispatcher(cluster.settings.UseDispatcher).withDeploy(Deploy.local), name = "clusterEventBusListener") } @@ -117,11 +117,11 @@ private[akka] class ClusterReadView(cluster: Cluster) extends Closeable { def self: Member = { _cachedSelf match { - case OptionVal.None ⇒ + case OptionVal.None => // lazy initialization here, later updated from elsewhere _cachedSelf = OptionVal.Some(selfFromStateOrPlaceholder) _cachedSelf.get - case OptionVal.Some(member) ⇒ member + case OptionVal.Some(member) => member } } diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterRemoteWatcher.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterRemoteWatcher.scala index 2d6aac176d..5ed99cd96a 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterRemoteWatcher.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterRemoteWatcher.scala @@ -81,16 +81,16 @@ private[cluster] class ClusterRemoteWatcher( override def receive = receiveClusterEvent orElse super.receive def receiveClusterEvent: Actor.Receive = { - case state: CurrentClusterState ⇒ - clusterNodes = state.members.collect { case m if m.address != selfAddress ⇒ m.address } + case state: CurrentClusterState => + clusterNodes = state.members.collect { case m if m.address != selfAddress => m.address } clusterNodes foreach takeOverResponsibility unreachable = unreachable diff clusterNodes - case MemberJoined(m) ⇒ memberJoined(m) - case MemberUp(m) ⇒ memberUp(m) - case MemberWeaklyUp(m) ⇒ memberUp(m) - case MemberRemoved(m, previousStatus) ⇒ memberRemoved(m, previousStatus) - case _: MemberEvent ⇒ // not interesting - case DelayedQuarantine(m, previousStatus) ⇒ delayedQuarantine(m, previousStatus) + case MemberJoined(m) => memberJoined(m) + case MemberUp(m) => memberUp(m) + case MemberWeaklyUp(m) => memberUp(m) + case MemberRemoved(m, previousStatus) => memberRemoved(m, previousStatus) + case _: MemberEvent => // not interesting + case DelayedQuarantine(m, previousStatus) => delayedQuarantine(m, previousStatus) } private def memberJoined(m: Member): Unit = { @@ -129,7 +129,7 @@ private[cluster] class ClusterRemoteWatcher( def quarantineOldIncarnation(newIncarnation: Member): Unit = { // If new incarnation of same host:port is seen then quarantine previous incarnation if (pendingDelayedQuarantine.nonEmpty) - pendingDelayedQuarantine.find(_.address == newIncarnation.address).foreach { oldIncarnation ⇒ + pendingDelayedQuarantine.find(_.address == newIncarnation.address).foreach { oldIncarnation => pendingDelayedQuarantine -= oldIncarnation quarantine(oldIncarnation.address, Some(oldIncarnation.longUid), s"Cluster member removed, new incarnation joined", harmless = true) diff --git a/akka-cluster/src/main/scala/akka/cluster/ClusterSettings.scala b/akka-cluster/src/main/scala/akka/cluster/ClusterSettings.scala index 54700b8133..463d6eb7cf 100644 --- a/akka-cluster/src/main/scala/akka/cluster/ClusterSettings.scala +++ b/akka-cluster/src/main/scala/akka/cluster/ClusterSettings.scala @@ -68,27 +68,27 @@ final class ClusterSettings(val config: Config, val systemName: String) { .requiring(_ > 0, "cross-data-center-connections must be > 0") val CrossDcGossipProbability: Double = cc.getDouble("multi-data-center.cross-data-center-gossip-probability") - .requiring(d ⇒ d >= 0.0D && d <= 1.0D, "cross-data-center-gossip-probability must be >= 0.0 and <= 1.0") + .requiring(d => d >= 0.0D && d <= 1.0D, "cross-data-center-gossip-probability must be >= 0.0 and <= 1.0") val CrossDcFailureDetectorSettings: CrossDcFailureDetectorSettings = new CrossDcFailureDetectorSettings(cc.getConfig("multi-data-center.failure-detector")) } val SeedNodes: immutable.IndexedSeq[Address] = - immutableSeq(cc.getStringList("seed-nodes")).map { case AddressFromURIString(address) ⇒ address }.toVector + immutableSeq(cc.getStringList("seed-nodes")).map { case AddressFromURIString(address) => address }.toVector val SeedNodeTimeout: FiniteDuration = cc.getMillisDuration("seed-node-timeout") val RetryUnsuccessfulJoinAfter: Duration = { val key = "retry-unsuccessful-join-after" toRootLowerCase(cc.getString(key)) match { - case "off" ⇒ Duration.Undefined - case _ ⇒ cc.getMillisDuration(key) requiring (_ > Duration.Zero, key + " > 0s, or off") + case "off" => Duration.Undefined + case _ => cc.getMillisDuration(key) requiring (_ > Duration.Zero, key + " > 0s, or off") } } val ShutdownAfterUnsuccessfulJoinSeedNodes: Duration = { val key = "shutdown-after-unsuccessful-join-seed-nodes" toRootLowerCase(cc.getString(key)) match { - case "off" ⇒ Duration.Undefined - case _ ⇒ cc.getMillisDuration(key) requiring (_ > Duration.Zero, key + " > 0s, or off") + case "off" => Duration.Undefined + case _ => cc.getMillisDuration(key) requiring (_ > Duration.Zero, key + " > 0s, or off") } } val PeriodicTasksInitialDelay: FiniteDuration = cc.getMillisDuration("periodic-tasks-initial-delay") @@ -101,8 +101,8 @@ final class ClusterSettings(val config: Config, val systemName: String) { val PublishStatsInterval: Duration = { val key = "publish-stats-interval" toRootLowerCase(cc.getString(key)) match { - case "off" ⇒ Duration.Undefined - case _ ⇒ cc.getMillisDuration(key) requiring (_ >= Duration.Zero, key + " >= 0s, or off") + case "off" => Duration.Undefined + case _ => cc.getMillisDuration(key) requiring (_ >= Duration.Zero, key + " >= 0s, or off") } } @@ -118,8 +118,8 @@ final class ClusterSettings(val config: Config, val systemName: String) { val AutoDownUnreachableAfter: Duration = { val key = "auto-down-unreachable-after" toRootLowerCase(cc.getString(key)) match { - case "off" ⇒ Duration.Undefined - case _ ⇒ cc.getMillisDuration(key) requiring (_ >= Duration.Zero, key + " >= 0s, or off") + case "off" => Duration.Undefined + case _ => cc.getMillisDuration(key) requiring (_ >= Duration.Zero, key + " >= 0s, or off") } } @@ -132,8 +132,8 @@ final class ClusterSettings(val config: Config, val systemName: String) { val DownRemovalMargin: FiniteDuration = { val key = "down-removal-margin" toRootLowerCase(cc.getString(key)) match { - case "off" ⇒ Duration.Zero - case _ ⇒ cc.getMillisDuration(key) requiring (_ >= Duration.Zero, key + " >= 0s, or off") + case "off" => Duration.Zero + case _ => cc.getMillisDuration(key) requiring (_ >= Duration.Zero, key + " >= 0s, or off") } } @@ -165,15 +165,15 @@ final class ClusterSettings(val config: Config, val systemName: String) { val MinNrOfMembersOfRole: Map[String, Int] = { import scala.collection.JavaConverters._ cc.getConfig("role").root.asScala.collect { - case (key, value: ConfigObject) ⇒ key → value.toConfig.getInt("min-nr-of-members") + case (key, value: ConfigObject) => key -> value.toConfig.getInt("min-nr-of-members") }.toMap } val RunCoordinatedShutdownWhenDown: Boolean = cc.getBoolean("run-coordinated-shutdown-when-down") val JmxEnabled: Boolean = cc.getBoolean("jmx.enabled") val JmxMultiMbeansInSameEnabled: Boolean = cc.getBoolean("jmx.multi-mbeans-in-same-jvm") val UseDispatcher: String = cc.getString("use-dispatcher") match { - case "" ⇒ Dispatchers.DefaultDispatcherId - case id ⇒ id + case "" => Dispatchers.DefaultDispatcherId + case id => id } val GossipDifferentViewProbability: Double = cc.getDouble("gossip-different-view-probability") val ReduceGossipDifferentViewProbability: Int = cc.getInt("reduce-gossip-different-view-probability") diff --git a/akka-cluster/src/main/scala/akka/cluster/CoordinatedShutdownLeave.scala b/akka-cluster/src/main/scala/akka/cluster/CoordinatedShutdownLeave.scala index cec95910f1..51b39dc9ab 100644 --- a/akka-cluster/src/main/scala/akka/cluster/CoordinatedShutdownLeave.scala +++ b/akka-cluster/src/main/scala/akka/cluster/CoordinatedShutdownLeave.scala @@ -33,7 +33,7 @@ private[akka] class CoordinatedShutdownLeave extends Actor { } def receive = { - case LeaveReq ⇒ + case LeaveReq => // MemberRemoved is needed in case it was downed instead cluster.leave(cluster.selfAddress) cluster.subscribe(self, classOf[MemberLeft], classOf[MemberRemoved]) @@ -41,22 +41,22 @@ private[akka] class CoordinatedShutdownLeave extends Actor { } def waitingLeaveCompleted(replyTo: ActorRef): Receive = { - case s: CurrentClusterState ⇒ + case s: CurrentClusterState => if (s.members.isEmpty) { // not joined yet done(replyTo) - } else if (s.members.exists(m ⇒ m.uniqueAddress == cluster.selfUniqueAddress && + } else if (s.members.exists(m => m.uniqueAddress == cluster.selfUniqueAddress && (m.status == Leaving || m.status == Exiting || m.status == Down))) { done(replyTo) } - case MemberLeft(m) ⇒ + case MemberLeft(m) => if (m.uniqueAddress == cluster.selfUniqueAddress) done(replyTo) - case MemberDowned(m) ⇒ + case MemberDowned(m) => // in case it was downed instead if (m.uniqueAddress == cluster.selfUniqueAddress) done(replyTo) - case MemberRemoved(m, _) ⇒ + case MemberRemoved(m, _) => // final safety fallback if (m.uniqueAddress == cluster.selfUniqueAddress) done(replyTo) diff --git a/akka-cluster/src/main/scala/akka/cluster/CrossDcClusterHeartbeat.scala b/akka-cluster/src/main/scala/akka/cluster/CrossDcClusterHeartbeat.scala index a6f8da8b53..7cbfd40d2b 100644 --- a/akka-cluster/src/main/scala/akka/cluster/CrossDcClusterHeartbeat.scala +++ b/akka-cluster/src/main/scala/akka/cluster/CrossDcClusterHeartbeat.scala @@ -47,8 +47,8 @@ private[cluster] final class CrossDcHeartbeatSender extends Actor with ActorLogg // For inspecting if in active state; allows avoiding "becoming active" when already active var activelyMonitoring = false - val isExternalClusterMember: Member ⇒ Boolean = - member ⇒ member.dataCenter != cluster.selfDataCenter + val isExternalClusterMember: Member => Boolean = + member => member.dataCenter != cluster.selfDataCenter val crossDcSettings: cluster.settings.CrossDcFailureDetectorSettings = cluster.settings.MultiDataCenter.CrossDcFailureDetectorSettings @@ -74,7 +74,7 @@ private[cluster] final class CrossDcHeartbeatSender extends Actor with ActorLogg } override def postStop(): Unit = { - dataCentersState.activeReceivers.foreach(a ⇒ crossDcFailureDetector.remove(a.address)) + dataCentersState.activeReceivers.foreach(a => crossDcFailureDetector.remove(a.address)) heartbeatTask.cancel() cluster.unsubscribe(self) } @@ -99,22 +99,22 @@ private[cluster] final class CrossDcHeartbeatSender extends Actor with ActorLogg * in case it becomes "old enough". */ def dormant: Actor.Receive = { - case s: CurrentClusterState ⇒ init(s) - case MemberRemoved(m, _) ⇒ removeMember(m) - case evt: MemberEvent ⇒ addMember(evt.member) - case ClusterHeartbeatSender.HeartbeatTick ⇒ // ignore... + case s: CurrentClusterState => init(s) + case MemberRemoved(m, _) => removeMember(m) + case evt: MemberEvent => addMember(evt.member) + case ClusterHeartbeatSender.HeartbeatTick => // ignore... } def active: Actor.Receive = { - case ClusterHeartbeatSender.HeartbeatTick ⇒ heartbeat() - case ClusterHeartbeatSender.HeartbeatRsp(from) ⇒ heartbeatRsp(from) - case MemberRemoved(m, _) ⇒ removeMember(m) - case evt: MemberEvent ⇒ addMember(evt.member) - case ClusterHeartbeatSender.ExpectedFirstHeartbeat(from) ⇒ triggerFirstHeartbeat(from) + case ClusterHeartbeatSender.HeartbeatTick => heartbeat() + case ClusterHeartbeatSender.HeartbeatRsp(from) => heartbeatRsp(from) + case MemberRemoved(m, _) => removeMember(m) + case evt: MemberEvent => addMember(evt.member) + case ClusterHeartbeatSender.ExpectedFirstHeartbeat(from) => triggerFirstHeartbeat(from) } def introspecting: Actor.Receive = { - case ReportStatus() ⇒ + case ReportStatus() => sender() ! { if (activelyMonitoring) CrossDcHeartbeatSender.MonitoringActive(dataCentersState) else CrossDcHeartbeatSender.MonitoringDormant() @@ -150,7 +150,7 @@ private[cluster] final class CrossDcHeartbeatSender extends Actor with ActorLogg } def heartbeat(): Unit = { - dataCentersState.activeReceivers foreach { to ⇒ + dataCentersState.activeReceivers foreach { to => if (crossDcFailureDetector.isMonitoring(to.address)) { if (verboseHeartbeat) logDebug("(Cross) Heartbeat to [{}]", to.address) } else { @@ -250,7 +250,7 @@ private[cluster] final case class CrossDcHeartbeatingState( // in the same DC. If it happens though, we need to remove the previously monitored node from the failure // detector, to prevent both a resource leak and that node actually appearing as unreachable in the gossip (!) val stoppedMonitoringReceivers = updatedState.activeReceiversIn(dc) diff this.activeReceiversIn(dc) - stoppedMonitoringReceivers.foreach(m ⇒ failureDetector.remove(m.address)) // at most one element difference + stoppedMonitoringReceivers.foreach(m => failureDetector.remove(m.address)) // at most one element difference updatedState } @@ -258,12 +258,12 @@ private[cluster] final case class CrossDcHeartbeatingState( def removeMember(m: Member): CrossDcHeartbeatingState = { val dc = m.dataCenter state.get(dc) match { - case Some(dcMembers) ⇒ + case Some(dcMembers) => val updatedMembers = dcMembers.filterNot(_.uniqueAddress == m.uniqueAddress) failureDetector.remove(m.address) copy(state = state.updated(dc, updatedMembers)) - case None ⇒ + case None => this // no change needed, was certainly not present (not even its DC was) } } @@ -333,8 +333,8 @@ private[cluster] object CrossDcHeartbeatingState { } else { // we need to enforce the ageOrdering for the SortedSet in each DC groupedByDc.map { - case (dc, ms) ⇒ - dc → (SortedSet.empty[Member](Member.ageOrdering) union ms) + case (dc, ms) => + dc -> (SortedSet.empty[Member](Member.ageOrdering) union ms) } } }) diff --git a/akka-cluster/src/main/scala/akka/cluster/DowningProvider.scala b/akka-cluster/src/main/scala/akka/cluster/DowningProvider.scala index f43b61d1ef..a8930b6a57 100644 --- a/akka-cluster/src/main/scala/akka/cluster/DowningProvider.scala +++ b/akka-cluster/src/main/scala/akka/cluster/DowningProvider.scala @@ -24,7 +24,7 @@ private[cluster] object DowningProvider { eas.dynamicAccess.createInstanceFor[DowningProvider]( fqcn, List((classOf[ActorSystem], system))).recover { - case e ⇒ throw new ConfigurationException( + case e => throw new ConfigurationException( s"Could not create cluster downing provider [$fqcn]", e) }.get } diff --git a/akka-cluster/src/main/scala/akka/cluster/Gossip.scala b/akka-cluster/src/main/scala/akka/cluster/Gossip.scala index d29ceec97c..6d6f4c3edc 100644 --- a/akka-cluster/src/main/scala/akka/cluster/Gossip.scala +++ b/akka-cluster/src/main/scala/akka/cluster/Gossip.scala @@ -71,7 +71,7 @@ private[cluster] final case class Gossip( private def assertInvariants(): Unit = { - def ifTrueThrow(func: ⇒ Boolean, expected: String, actual: String): Unit = + def ifTrueThrow(func: => Boolean, expected: String, actual: String): Unit = if (func) throw new IllegalArgumentException(s"$expected, but found [$actual]") ifTrueThrow( @@ -99,7 +99,7 @@ private[cluster] final case class Gossip( } @transient private lazy val membersMap: Map[UniqueAddress, Member] = - members.iterator.map(m ⇒ m.uniqueAddress → m).toMap + members.iterator.map(m => m.uniqueAddress -> m).toMap @transient lazy val isMultiDc = if (members.size <= 1) false @@ -168,7 +168,7 @@ private[cluster] final case class Gossip( val mergedTombstones = tombstones ++ that.tombstones // 2. merge vector clocks (but remove entries for tombstoned nodes) - val mergedVClock = mergedTombstones.keys.foldLeft(this.version merge that.version) { (vclock, node) ⇒ + val mergedVClock = mergedTombstones.keys.foldLeft(this.version merge that.version) { (vclock, node) => vclock.prune(VectorClock.Node(Gossip.vclockName(node))) } @@ -187,7 +187,7 @@ private[cluster] final case class Gossip( } lazy val reachabilityExcludingDownedObservers: Reachability = { - val downed = members.collect { case m if m.status == Down ⇒ m } + val downed = members.collect { case m if m.status == Down => m } overview.reachability.removeObservers(downed.map(_.uniqueAddress)) } @@ -217,7 +217,7 @@ private[cluster] final case class Gossip( def hasMember(node: UniqueAddress): Boolean = membersMap.contains(node) def removeAll(nodes: Iterable[UniqueAddress], removalTimestamp: Long): Gossip = { - nodes.foldLeft(this)((gossip, node) ⇒ gossip.remove(node, removalTimestamp)) + nodes.foldLeft(this)((gossip, node) => gossip.remove(node, removalTimestamp)) } def update(updatedMembers: immutable.SortedSet[Member]): Gossip = { @@ -241,7 +241,7 @@ private[cluster] final case class Gossip( // taken care of when receiving gossips. val newVersion = version.prune(VectorClock.Node(Gossip.vclockName(node))) val newMembers = members.filterNot(_.uniqueAddress == node) - val newTombstones = tombstones + (node → removalTimestamp) + val newTombstones = tombstones + (node -> removalTimestamp) copy(version = newVersion, members = newMembers, overview = newOverview, tombstones = newTombstones) } @@ -263,7 +263,7 @@ private[cluster] final case class Gossip( } def pruneTombstones(removeEarlierThan: Gossip.Timestamp): Gossip = { - val newTombstones = tombstones.filter { case (_, timestamp) ⇒ timestamp > removeEarlierThan } + val newTombstones = tombstones.filter { case (_, timestamp) => timestamp > removeEarlierThan } if (newTombstones.size == tombstones.size) this else copy(tombstones = newTombstones) } @@ -289,7 +289,7 @@ object GossipEnvelope { def apply(from: UniqueAddress, to: UniqueAddress, gossip: Gossip): GossipEnvelope = new GossipEnvelope(from, to, gossip, null, null) - def apply(from: UniqueAddress, to: UniqueAddress, serDeadline: Deadline, ser: () ⇒ Gossip): GossipEnvelope = + def apply(from: UniqueAddress, to: UniqueAddress, serDeadline: Deadline, ser: () => Gossip): GossipEnvelope = new GossipEnvelope(from, to, null, serDeadline, ser) } @@ -307,7 +307,7 @@ private[cluster] class GossipEnvelope private ( val to: UniqueAddress, @volatile var g: Gossip, serDeadline: Deadline, - @transient @volatile var ser:() ⇒ Gossip) extends ClusterMessage { + @transient @volatile var ser:() => Gossip) extends ClusterMessage { def gossip: Gossip = { deserialize() diff --git a/akka-cluster/src/main/scala/akka/cluster/JoinConfigCompatCheckCluster.scala b/akka-cluster/src/main/scala/akka/cluster/JoinConfigCompatCheckCluster.scala index 15ae5f50e1..fdce57e0d6 100644 --- a/akka-cluster/src/main/scala/akka/cluster/JoinConfigCompatCheckCluster.scala +++ b/akka-cluster/src/main/scala/akka/cluster/JoinConfigCompatCheckCluster.scala @@ -7,7 +7,7 @@ package akka.cluster import akka.annotation.InternalApi import com.typesafe.config.Config -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } /** * INTERNAL API diff --git a/akka-cluster/src/main/scala/akka/cluster/JoinConfigCompatChecker.scala b/akka-cluster/src/main/scala/akka/cluster/JoinConfigCompatChecker.scala index 4391b849f3..393225a99c 100644 --- a/akka-cluster/src/main/scala/akka/cluster/JoinConfigCompatChecker.scala +++ b/akka-cluster/src/main/scala/akka/cluster/JoinConfigCompatChecker.scala @@ -12,7 +12,7 @@ import akka.util.ccompat._ import com.typesafe.config.{ Config, ConfigFactory, ConfigValue } import scala.collection.JavaConverters._ -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } abstract class JoinConfigCompatChecker { @@ -45,7 +45,7 @@ object JoinConfigCompatChecker { // return all not found required keys val result = requiredKeys.collect { - case requiredKey if !allKeys.contains(requiredKey) ⇒ requiredKey + " is missing" + case requiredKey if !allKeys.contains(requiredKey) => requiredKey + " is missing" } if (result.isEmpty) Valid @@ -75,7 +75,7 @@ object JoinConfigCompatChecker { val incompatibleKeys = toCheck.entrySet().asScala .collect { - case entry if requiredKeys.contains(entry.getKey) && !checkCompat(entry) ⇒ s"${entry.getKey} is incompatible" + case entry if requiredKeys.contains(entry.getKey) && !checkCompat(entry) => s"${entry.getKey} is incompatible" } if (incompatibleKeys.isEmpty) Valid @@ -99,7 +99,7 @@ object JoinConfigCompatChecker { val filtered = config.entrySet().asScala .collect { - case e if requiredKeys.contains(e.getKey) ⇒ (e.getKey, e.getValue) + case e if requiredKeys.contains(e.getKey) => (e.getKey, e.getValue) } ConfigFactory.parseMap(filtered.toMap.asJava) @@ -112,8 +112,8 @@ object JoinConfigCompatChecker { */ @InternalApi private[cluster] def removeSensitiveKeys(requiredKeys: im.Seq[String], clusterSettings: ClusterSettings): im.Seq[String] = { - requiredKeys.filter { key ⇒ - !clusterSettings.SensitiveConfigPaths.exists(s ⇒ key.startsWith(s)) + requiredKeys.filter { key => + !clusterSettings.SensitiveConfigPaths.exists(s => key.startsWith(s)) } } @@ -138,7 +138,7 @@ object JoinConfigCompatChecker { private[cluster] def load(system: ExtendedActorSystem, clusterSettings: ClusterSettings): JoinConfigCompatChecker = { val checkers = - clusterSettings.ConfigCompatCheckers.map { fqcn ⇒ + clusterSettings.ConfigCompatCheckers.map { fqcn => system.dynamicAccess .createInstanceFor[JoinConfigCompatChecker](fqcn, im.Seq.empty) .get // can't continue if we can't load it @@ -151,7 +151,7 @@ object JoinConfigCompatChecker { "akka.version" +: checkers.flatMap(_.requiredKeys).to(im.Seq) } override def check(toValidate: Config, clusterConfig: Config): ConfigValidation = - checkers.foldLeft(Valid: ConfigValidation) { (acc, checker) ⇒ + checkers.foldLeft(Valid: ConfigValidation) { (acc, checker) => acc ++ checker.check(toValidate, clusterConfig) } } @@ -165,10 +165,10 @@ sealed trait ConfigValidation { def concat(that: ConfigValidation) = { (this, that) match { - case (Invalid(a), Invalid(b)) ⇒ Invalid(a ++ b) - case (_, i @ Invalid(_)) ⇒ i - case (i @ Invalid(_), _) ⇒ i - case _ ⇒ Valid + case (Invalid(a), Invalid(b)) => Invalid(a ++ b) + case (_, i @ Invalid(_)) => i + case (i @ Invalid(_), _) => i + case _ => Valid } } } diff --git a/akka-cluster/src/main/scala/akka/cluster/Member.scala b/akka-cluster/src/main/scala/akka/cluster/Member.scala index 26d42fada6..a4c3a2677d 100644 --- a/akka-cluster/src/main/scala/akka/cluster/Member.scala +++ b/akka-cluster/src/main/scala/akka/cluster/Member.scala @@ -32,8 +32,8 @@ class Member private[cluster] ( override def hashCode = uniqueAddress.## override def equals(other: Any) = other match { - case m: Member ⇒ uniqueAddress == m.uniqueAddress - case _ ⇒ false + case m: Member => uniqueAddress == m.uniqueAddress + case _ => false } override def toString = if (dataCenter == ClusterSettings.DefaultDataCenter) @@ -112,7 +112,7 @@ object Member { /** * `Address` ordering type class, sorts addresses by host and port. */ - implicit val addressOrdering: Ordering[Address] = Ordering.fromLessThan[Address] { (a, b) ⇒ + implicit val addressOrdering: Ordering[Address] = Ordering.fromLessThan[Address] { (a, b) => // cluster node identifier is the host and port of the address; protocol and system is assumed to be the same if (a eq b) false else if (a.host != b.host) a.host.getOrElse("").compareTo(b.host.getOrElse("")) < 0 @@ -125,18 +125,18 @@ object Member { * Orders the members by their address except that members with status * Joining, Exiting and Down are ordered last (in that order). */ - private[cluster] val leaderStatusOrdering: Ordering[Member] = Ordering.fromLessThan[Member] { (a, b) ⇒ + private[cluster] val leaderStatusOrdering: Ordering[Member] = Ordering.fromLessThan[Member] { (a, b) => (a.status, b.status) match { - case (as, bs) if as == bs ⇒ ordering.compare(a, b) <= 0 - case (Down, _) ⇒ false - case (_, Down) ⇒ true - case (Exiting, _) ⇒ false - case (_, Exiting) ⇒ true - case (Joining, _) ⇒ false - case (_, Joining) ⇒ true - case (WeaklyUp, _) ⇒ false - case (_, WeaklyUp) ⇒ true - case _ ⇒ ordering.compare(a, b) <= 0 + case (as, bs) if as == bs => ordering.compare(a, b) <= 0 + case (Down, _) => false + case (_, Down) => true + case (Exiting, _) => false + case (_, Exiting) => true + case (Joining, _) => false + case (_, Joining) => true + case (WeaklyUp, _) => false + case (_, WeaklyUp) => true + case _ => ordering.compare(a, b) <= 0 } } @@ -158,7 +158,7 @@ object Member { * members belong to different data centers. */ val ageOrdering: Ordering[Member] = Ordering.fromLessThan[Member] { - (a, b) ⇒ a.isOlderThan(b) + (a, b) => a.isOlderThan(b) } @deprecated("Was accidentally made a public API, internal", since = "2.5.4") @@ -174,7 +174,7 @@ object Member { val groupedByAddress = (a.toSeq ++ b.toSeq).groupBy(_.uniqueAddress) // pick highest MemberStatus groupedByAddress.foldLeft(Member.none) { - case (acc, (_, members)) ⇒ + case (acc, (_, members)) => if (members.size == 2) acc + members.reduceLeft(highestPriorityOf) else { val m = members.head @@ -192,19 +192,19 @@ object Member { // preserve the oldest in case of different upNumber if (m1.isOlderThan(m2)) m1 else m2 else (m1.status, m2.status) match { - case (Removed, _) ⇒ m1 - case (_, Removed) ⇒ m2 - case (Down, _) ⇒ m1 - case (_, Down) ⇒ m2 - case (Exiting, _) ⇒ m1 - case (_, Exiting) ⇒ m2 - case (Leaving, _) ⇒ m1 - case (_, Leaving) ⇒ m2 - case (Joining, _) ⇒ m2 - case (_, Joining) ⇒ m1 - case (WeaklyUp, _) ⇒ m2 - case (_, WeaklyUp) ⇒ m1 - case (Up, Up) ⇒ m1 + case (Removed, _) => m1 + case (_, Removed) => m2 + case (Down, _) => m1 + case (_, Down) => m2 + case (Exiting, _) => m1 + case (_, Exiting) => m2 + case (Leaving, _) => m1 + case (_, Leaving) => m2 + case (Joining, _) => m2 + case (_, Joining) => m1 + case (WeaklyUp, _) => m2 + case (_, WeaklyUp) => m1 + case (Up, Up) => m1 } } @@ -266,13 +266,13 @@ object MemberStatus { */ private[cluster] val allowedTransitions: Map[MemberStatus, Set[MemberStatus]] = Map( - Joining → Set(WeaklyUp, Up, Leaving, Down, Removed), - WeaklyUp → Set(Up, Leaving, Down, Removed), - Up → Set(Leaving, Down, Removed), - Leaving → Set(Exiting, Down, Removed), - Down → Set(Removed), - Exiting → Set(Removed, Down), - Removed → Set.empty[MemberStatus]) + Joining -> Set(WeaklyUp, Up, Leaving, Down, Removed), + WeaklyUp -> Set(Up, Leaving, Down, Removed), + Up -> Set(Leaving, Down, Removed), + Leaving -> Set(Exiting, Down, Removed), + Down -> Set(Removed), + Exiting -> Set(Removed, Down), + Removed -> Set.empty[MemberStatus]) } object UniqueAddress extends AbstractFunction2[Address, Int, UniqueAddress] { diff --git a/akka-cluster/src/main/scala/akka/cluster/MembershipState.scala b/akka-cluster/src/main/scala/akka/cluster/MembershipState.scala index ca2e3edd7a..5cf8c5574c 100644 --- a/akka-cluster/src/main/scala/akka/cluster/MembershipState.scala +++ b/akka-cluster/src/main/scala/akka/cluster/MembershipState.scala @@ -57,7 +57,7 @@ import scala.util.Random // If another member in the data center that is UP or LEAVING and has not seen this gossip or is exiting // convergence cannot be reached def memberHinderingConvergenceExists = - members.exists(member ⇒ + members.exists(member => member.dataCenter == selfDc && convergenceMemberStatus(member.status) && !(latestGossip.seenByNode(member.uniqueAddress) || exitingConfirmed(member.uniqueAddress))) @@ -65,11 +65,11 @@ import scala.util.Random // Find cluster members in the data center that are unreachable from other members of the data center // excluding observations from members outside of the data center, that have status DOWN or is passed in as confirmed exiting. val unreachableInDc = dcReachabilityExcludingDownedObservers.allUnreachableOrTerminated.collect { - case node if node != selfUniqueAddress && !exitingConfirmed(node) ⇒ latestGossip.member(node) + case node if node != selfUniqueAddress && !exitingConfirmed(node) => latestGossip.member(node) } // unreachables outside of the data center or with status DOWN or EXITING does not affect convergence val allUnreachablesCanBeIgnored = - unreachableInDc.forall(unreachable ⇒ convergenceSkipUnreachableWithMemberStatus(unreachable.status)) + unreachableInDc.forall(unreachable => convergenceSkipUnreachableWithMemberStatus(unreachable.status)) allUnreachablesCanBeIgnored && !memberHinderingConvergenceExists } @@ -79,35 +79,35 @@ import scala.util.Random * nodes outside of the data center */ lazy val dcReachability: Reachability = - overview.reachability.removeObservers(members.collect { case m if m.dataCenter != selfDc ⇒ m.uniqueAddress }) + overview.reachability.removeObservers(members.collect { case m if m.dataCenter != selfDc => m.uniqueAddress }) /** * @return Reachability excluding observations from nodes outside of the data center and observations within self data center, * but including observed unreachable nodes outside of the data center */ lazy val dcReachabilityWithoutObservationsWithin: Reachability = - dcReachability.filterRecords { r ⇒ latestGossip.member(r.subject).dataCenter != selfDc } + dcReachability.filterRecords { r => latestGossip.member(r.subject).dataCenter != selfDc } /** * @return reachability for data center nodes, with observations from outside the data center or from downed nodes filtered out */ lazy val dcReachabilityExcludingDownedObservers: Reachability = { - val membersToExclude = members.collect { case m if m.status == Down || m.dataCenter != selfDc ⇒ m.uniqueAddress } - overview.reachability.removeObservers(membersToExclude).remove(members.collect { case m if m.dataCenter != selfDc ⇒ m.uniqueAddress }) + val membersToExclude = members.collect { case m if m.status == Down || m.dataCenter != selfDc => m.uniqueAddress } + overview.reachability.removeObservers(membersToExclude).remove(members.collect { case m if m.dataCenter != selfDc => m.uniqueAddress }) } lazy val dcReachabilityNoOutsideNodes: Reachability = - overview.reachability.remove(members.collect { case m if m.dataCenter != selfDc ⇒ m.uniqueAddress }) + overview.reachability.remove(members.collect { case m if m.dataCenter != selfDc => m.uniqueAddress }) /** * @return Up to `crossDcConnections` oldest members for each DC */ lazy val ageSortedTopOldestMembersPerDc: Map[DataCenter, SortedSet[Member]] = { - latestGossip.members.foldLeft(Map.empty[DataCenter, SortedSet[Member]]) { (acc, member) ⇒ + latestGossip.members.foldLeft(Map.empty[DataCenter, SortedSet[Member]]) { (acc, member) => acc.get(member.dataCenter) match { - case Some(set) ⇒ + case Some(set) => if (set.size < crossDcConnections) { - acc + (member.dataCenter → (set + member)) + acc + (member.dataCenter -> (set + member)) } else { if (set.exists(member.isOlderThan)) { acc + (member.dataCenter -> (set + member).take(crossDcConnections)) @@ -115,8 +115,8 @@ import scala.util.Random acc } } - case None ⇒ - acc + (member.dataCenter → (SortedSet.empty(Member.ageOrdering) + member)) + case None => + acc + (member.dataCenter -> (SortedSet.empty(Member.ageOrdering) + member)) } } } @@ -154,13 +154,13 @@ import scala.util.Random val reachability = dcReachability val reachableMembersInDc = - if (reachability.isAllReachable) mbrs.filter(m ⇒ m.dataCenter == selfDc && m.status != Down) - else mbrs.filter(m ⇒ + if (reachability.isAllReachable) mbrs.filter(m => m.dataCenter == selfDc && m.status != Down) + else mbrs.filter(m => m.dataCenter == selfDc && m.status != Down && (reachability.isReachable(m.uniqueAddress) || m.uniqueAddress == selfUniqueAddress)) if (reachableMembersInDc.isEmpty) None - else reachableMembersInDc.find(m ⇒ leaderMemberStatus(m.status)) + else reachableMembersInDc.find(m => leaderMemberStatus(m.status)) .orElse(Some(reachableMembersInDc.min(Member.leaderStatusOrdering))) .map(_.uniqueAddress) } @@ -179,7 +179,7 @@ import scala.util.Random def youngestMember: Member = { val mbrs = dcMembers require(mbrs.nonEmpty, "No youngest when no members") - mbrs.maxBy(m ⇒ if (m.upNumber == Int.MaxValue) 0 else m.upNumber) + mbrs.maxBy(m => if (m.upNumber == Int.MaxValue) 0 else m.upNumber) } /** @@ -194,10 +194,10 @@ import scala.util.Random targets += membersSortedByAge.head // oldest of all nodes (in DC) if (membersSortedByAge.tail.nonEmpty) targets += membersSortedByAge.tail.head // second oldest of all nodes (in DC) - roles.foreach { role ⇒ - membersSortedByAge.find(_.hasRole(role)).foreach { first ⇒ + roles.foreach { role => + membersSortedByAge.find(_.hasRole(role)).foreach { first => targets += first // oldest with the role (in DC) - membersSortedByAge.find(m ⇒ m != first && m.hasRole(role)).foreach { next ⇒ + membersSortedByAge.find(m => m != first && m.hasRole(role)).foreach { next => targets += next // second oldest with the role (in DC) } } @@ -232,33 +232,33 @@ import scala.util.Random if (state.latestGossip.isMultiDc && state.ageSortedTopOldestMembersPerDc(state.selfDc).contains(state.selfMember)) { // this node is one of the N oldest in the cluster, gossip to one cross-dc but mostly locally val randomLocalNodes = Random.shuffle(state.members.toVector.collect { - case m if m.dataCenter == state.selfDc && state.validNodeForGossip(m.uniqueAddress) ⇒ m.uniqueAddress + case m if m.dataCenter == state.selfDc && state.validNodeForGossip(m.uniqueAddress) => m.uniqueAddress }) @tailrec def selectOtherDcNode(randomizedDcs: List[DataCenter]): Option[UniqueAddress] = randomizedDcs match { - case Nil ⇒ None // couldn't find a single cross-dc-node to talk to - case dc :: tail ⇒ + case Nil => None // couldn't find a single cross-dc-node to talk to + case dc :: tail => state.ageSortedTopOldestMembersPerDc(dc).collectFirst { - case m if state.validNodeForGossip(m.uniqueAddress) ⇒ m.uniqueAddress + case m if state.validNodeForGossip(m.uniqueAddress) => m.uniqueAddress } match { - case Some(addr) ⇒ Some(addr) - case None ⇒ selectOtherDcNode(tail) + case Some(addr) => Some(addr) + case None => selectOtherDcNode(tail) } } val otherDcs = Random.shuffle((state.ageSortedTopOldestMembersPerDc.keySet - state.selfDc).toList) selectOtherDcNode(otherDcs) match { - case Some(node) ⇒ randomLocalNodes.take(n - 1) :+ node - case None ⇒ randomLocalNodes.take(n) + case Some(node) => randomLocalNodes.take(n - 1) :+ node + case None => randomLocalNodes.take(n) } } else { // single dc or not among the N oldest - select local nodes val selectedNodes = state.members.toVector.collect { - case m if m.dataCenter == state.selfDc && state.validNodeForGossip(m.uniqueAddress) ⇒ m.uniqueAddress + case m if m.dataCenter == state.selfDc && state.validNodeForGossip(m.uniqueAddress) => m.uniqueAddress } if (selectedNodes.size <= n) selectedNodes @@ -276,7 +276,7 @@ import scala.util.Random // If it's time to try to gossip to some nodes with a different view // gossip to a random alive same dc member with preference to a member with older gossip version latestGossip.members.iterator.collect { - case m if m.dataCenter == state.selfDc && !latestGossip.seenByNode(m.uniqueAddress) && state.validNodeForGossip(m.uniqueAddress) ⇒ + case m if m.dataCenter == state.selfDc && !latestGossip.seenByNode(m.uniqueAddress) && state.validNodeForGossip(m.uniqueAddress) => m.uniqueAddress }.to(Vector) } else Vector.empty @@ -284,7 +284,7 @@ import scala.util.Random // Fall back to localGossip if (firstSelection.isEmpty) { latestGossip.members.toVector.collect { - case m if m.dataCenter == state.selfDc && state.validNodeForGossip(m.uniqueAddress) ⇒ m.uniqueAddress + case m if m.dataCenter == state.selfDc && state.validNodeForGossip(m.uniqueAddress) => m.uniqueAddress } } else firstSelection @@ -307,17 +307,17 @@ import scala.util.Random @tailrec def findFirstDcWithValidNodes(left: List[DataCenter]): Vector[UniqueAddress] = left match { - case dc :: tail ⇒ + case dc :: tail => val validNodes = nodesPerDc(dc).collect { - case member if state.validNodeForGossip(member.uniqueAddress) ⇒ + case member if state.validNodeForGossip(member.uniqueAddress) => member.uniqueAddress } if (validNodes.nonEmpty) validNodes.toVector else findFirstDcWithValidNodes(tail) // no valid nodes in dc, try next - case Nil ⇒ + case Nil => Vector.empty } diff --git a/akka-cluster/src/main/scala/akka/cluster/Reachability.scala b/akka-cluster/src/main/scala/akka/cluster/Reachability.scala index 1a7848aea5..aa3b5be486 100644 --- a/akka-cluster/src/main/scala/akka/cluster/Reachability.scala +++ b/akka-cluster/src/main/scala/akka/cluster/Reachability.scala @@ -19,8 +19,8 @@ private[cluster] object Reachability { new Reachability(records, versions) def create(records: immutable.Seq[Record], versions: Map[UniqueAddress, Long]): Reachability = records match { - case r: immutable.IndexedSeq[Record] ⇒ apply(r, versions) - case _ ⇒ apply(records.toVector, versions) + case r: immutable.IndexedSeq[Record] => apply(r, versions) + case _ => apply(records.toVector, versions) } @SerialVersionUID(1L) @@ -75,12 +75,12 @@ private[cluster] class Reachability private ( var allTerminated = Set.empty[UniqueAddress] var allUnreachable = Set.empty[UniqueAddress] - records foreach { r ⇒ + records foreach { r => val m = mapBuilder.get(r.observer) match { - case None ⇒ Map(r.subject → r) - case Some(m) ⇒ m.updated(r.subject, r) + case None => Map(r.subject -> r) + case Some(m) => m.updated(r.subject, r) } - mapBuilder += (r.observer → m) + mapBuilder += (r.observer -> m) if (r.status == Unreachable) allUnreachable += r.subject else if (r.status == Terminated) allTerminated += r.subject @@ -113,8 +113,8 @@ private[cluster] class Reachability private ( change(observer, subject, Terminated) private def currentVersion(observer: UniqueAddress): Long = versions.get(observer) match { - case None ⇒ 0 - case Some(v) ⇒ v + case None => 0 + case Some(v) => v } private def nextVersion(observer: UniqueAddress): Long = currentVersion(observer) + 1 @@ -125,27 +125,27 @@ private[cluster] class Reachability private ( val newRecord = Record(observer, subject, status, v) observerRows(observer) match { // don't record Reachable observation if nothing has been noted so far - case None if status == Reachable ⇒ this + case None if status == Reachable => this // otherwise, create new instance including this first observation - case None ⇒ + case None => new Reachability(records :+ newRecord, newVersions) // otherwise, update old observations - case Some(oldObserverRows) ⇒ + case Some(oldObserverRows) => oldObserverRows.get(subject) match { - case None ⇒ - if (status == Reachable && oldObserverRows.forall { case (_, r) ⇒ r.status == Reachable }) { + case None => + if (status == Reachable && oldObserverRows.forall { case (_, r) => r.status == Reachable }) { // FIXME: how should we have gotten into this state? // all Reachable, prune by removing the records of the observer, and bump the version new Reachability(records.filterNot(_.observer == observer), newVersions) } else new Reachability(records :+ newRecord, newVersions) - case Some(oldRecord) ⇒ + case Some(oldRecord) => if (oldRecord.status == Terminated || oldRecord.status == status) this else { - if (status == Reachable && oldObserverRows.forall { case (_, r) ⇒ r.status == Reachable || r.subject == subject }) { + if (status == Reachable && oldObserverRows.forall { case (_, r) => r.status == Reachable || r.subject == subject }) { // all Reachable, prune by removing the records of the observer, and bump the version new Reachability(records.filterNot(_.observer == observer), newVersions) } else { @@ -161,39 +161,39 @@ private[cluster] class Reachability private ( val recordBuilder = new immutable.VectorBuilder[Record] recordBuilder.sizeHint(math.max(this.records.size, other.records.size)) var newVersions = versions - allowed foreach { observer ⇒ + allowed foreach { observer => val observerVersion1 = this.currentVersion(observer) val observerVersion2 = other.currentVersion(observer) (this.observerRows(observer), other.observerRows(observer)) match { - case (None, None) ⇒ - case (Some(rows1), Some(rows2)) ⇒ + case (None, None) => + case (Some(rows1), Some(rows2)) => // We throw away a complete set of records based on the version here. Couldn't we lose records here? No, // because the observer gossips always the complete set of records. (That's hard to see in the model, because // records also contain the version number for which they were introduced but actually the version number // corresponds to the whole set of records of one observer at one point in time. val rows = if (observerVersion1 > observerVersion2) rows1 else rows2 - recordBuilder ++= rows.collect { case (_, r) if allowed(r.subject) ⇒ r } - case (Some(rows1), None) ⇒ + recordBuilder ++= rows.collect { case (_, r) if allowed(r.subject) => r } + case (Some(rows1), None) => if (observerVersion1 > observerVersion2) - recordBuilder ++= rows1.collect { case (_, r) if allowed(r.subject) ⇒ r } - case (None, Some(rows2)) ⇒ + recordBuilder ++= rows1.collect { case (_, r) if allowed(r.subject) => r } + case (None, Some(rows2)) => if (observerVersion2 > observerVersion1) - recordBuilder ++= rows2.collect { case (_, r) if allowed(r.subject) ⇒ r } + recordBuilder ++= rows2.collect { case (_, r) if allowed(r.subject) => r } } if (observerVersion2 > observerVersion1) - newVersions += (observer → observerVersion2) + newVersions += (observer -> observerVersion2) } - newVersions = newVersions.filterNot { case (k, _) ⇒ !allowed(k) } + newVersions = newVersions.filterNot { case (k, _) => !allowed(k) } new Reachability(recordBuilder.result(), newVersions) } def remove(nodes: Iterable[UniqueAddress]): Reachability = { val nodesSet = nodes.to(immutable.HashSet) - val newRecords = records.filterNot(r ⇒ nodesSet(r.observer) || nodesSet(r.subject)) + val newRecords = records.filterNot(r => nodesSet(r.observer) || nodesSet(r.subject)) val newVersions = versions -- nodes Reachability(newRecords, newVersions) } @@ -202,20 +202,20 @@ private[cluster] class Reachability private ( if (nodes.isEmpty) this else { - val newRecords = records.filterNot(r ⇒ nodes(r.observer)) + val newRecords = records.filterNot(r => nodes(r.observer)) val newVersions = versions -- nodes Reachability(newRecords, newVersions) } - def filterRecords(f: Record ⇒ Boolean) = + def filterRecords(f: Record => Boolean) = Reachability(records.filter(f), versions) def status(observer: UniqueAddress, subject: UniqueAddress): ReachabilityStatus = observerRows(observer) match { - case None ⇒ Reachable - case Some(observerRows) ⇒ observerRows.get(subject) match { - case None ⇒ Reachable - case Some(record) ⇒ record.status + case None => Reachable + case Some(observerRows) => observerRows.get(subject) match { + case None => Reachable + case Some(record) => record.status } } @@ -260,19 +260,19 @@ private[cluster] class Reachability private ( */ def allUnreachableFrom(observer: UniqueAddress): Set[UniqueAddress] = observerRows(observer) match { - case None ⇒ Set.empty - case Some(observerRows) ⇒ + case None => Set.empty + case Some(observerRows) => observerRows.iterator.collect { - case (subject, record) if record.status == Unreachable ⇒ subject + case (subject, record) if record.status == Unreachable => subject }.to(immutable.Set) } def observersGroupedByUnreachable: Map[UniqueAddress, Set[UniqueAddress]] = { records.groupBy(_.subject).collect { - case (subject, records) if records.exists(_.status == Unreachable) ⇒ + case (subject, records) if records.exists(_.status == Unreachable) => val observers: Set[UniqueAddress] = - records.iterator.collect { case r if r.status == Unreachable ⇒ r.observer }.to(immutable.Set) - (subject → observers) + records.iterator.collect { case r if r.status == Unreachable => r.observer }.to(immutable.Set) + (subject -> observers) } } @@ -280,8 +280,8 @@ private[cluster] class Reachability private ( def recordsFrom(observer: UniqueAddress): immutable.IndexedSeq[Record] = { observerRows(observer) match { - case None ⇒ Vector.empty - case Some(rows) ⇒ rows.valuesIterator.toVector + case None => Vector.empty + case Some(rows) => rows.valuesIterator.toVector } } @@ -290,19 +290,19 @@ private[cluster] class Reachability private ( // only used for testing override def equals(obj: Any): Boolean = obj match { - case other: Reachability ⇒ + case other: Reachability => records.size == other.records.size && versions == other.versions && cache.observerRowsMap == other.cache.observerRowsMap - case _ ⇒ false + case _ => false } override def toString: String = { val rows = for { - observer ← versions.keys.toSeq.sorted + observer <- versions.keys.toSeq.sorted rowsOption = observerRows(observer) if rowsOption.isDefined // compilation err for subject <- rowsOption rows = rowsOption.get - subject ← rows.keys.toSeq.sorted + subject <- rows.keys.toSeq.sorted } yield { val record = rows(subject) val aggregated = status(subject) diff --git a/akka-cluster/src/main/scala/akka/cluster/VectorClock.scala b/akka-cluster/src/main/scala/akka/cluster/VectorClock.scala index ef7b09764a..0e047c2893 100644 --- a/akka-cluster/src/main/scala/akka/cluster/VectorClock.scala +++ b/akka-cluster/src/main/scala/akka/cluster/VectorClock.scala @@ -29,7 +29,7 @@ private[cluster] object VectorClock { private def hash(name: String): String = { val digester = MessageDigest.getInstance("MD5") digester update name.getBytes("UTF-8") - digester.digest.map { h ⇒ "%02x".format(0xFF & h) }.mkString + digester.digest.map { h => "%02x".format(0xFF & h) }.mkString } } @@ -175,7 +175,7 @@ final case class VectorClock( */ def merge(that: VectorClock): VectorClock = { var mergedVersions = that.versions - for ((node, time) ← versions) { + for ((node, time) <- versions) { val mergedVersionsCurrentTime = mergedVersions.getOrElse(node, Timestamp.Zero) if (time > mergedVersionsCurrentTime) mergedVersions = mergedVersions.updated(node, time) @@ -189,5 +189,5 @@ final case class VectorClock( else this - override def toString = versions.map { case ((n, t)) ⇒ n + " -> " + t }.mkString("VectorClock(", ", ", ")") + override def toString = versions.map { case ((n, t)) => n + " -> " + t }.mkString("VectorClock(", ", ", ")") } diff --git a/akka-cluster/src/main/scala/akka/cluster/protobuf/ClusterMessageSerializer.scala b/akka-cluster/src/main/scala/akka/cluster/protobuf/ClusterMessageSerializer.scala index 4855ae3b43..51d06b451c 100644 --- a/akka-cluster/src/main/scala/akka/cluster/protobuf/ClusterMessageSerializer.scala +++ b/akka-cluster/src/main/scala/akka/cluster/protobuf/ClusterMessageSerializer.scala @@ -9,7 +9,7 @@ import java.util.zip.{ GZIPInputStream, GZIPOutputStream } import akka.actor.{ Address, ExtendedActorSystem } import akka.cluster._ -import akka.cluster.protobuf.msg.{ ClusterMessages ⇒ cm } +import akka.cluster.protobuf.msg.{ ClusterMessages => cm } import akka.serialization._ import akka.protobuf.{ ByteString, MessageLite } import scala.annotation.tailrec @@ -62,56 +62,56 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se private lazy val GossipTimeToLive = Cluster(system).settings.GossipTimeToLive def manifest(o: AnyRef): String = o match { - case _: InternalClusterAction.Join ⇒ JoinManifest - case _: InternalClusterAction.Welcome ⇒ WelcomeManifest - case _: ClusterUserAction.Leave ⇒ LeaveManifest - case _: ClusterUserAction.Down ⇒ DownManifest - case _: InternalClusterAction.InitJoin ⇒ InitJoinManifest - case _: InternalClusterAction.InitJoinAck ⇒ InitJoinAckManifest - case _: InternalClusterAction.InitJoinNack ⇒ InitJoinNackManifest - case _: ClusterHeartbeatSender.Heartbeat ⇒ HeartBeatManifest - case _: ClusterHeartbeatSender.HeartbeatRsp ⇒ HeartBeatRspManifest - case _: ExitingConfirmed ⇒ ExitingConfirmedManifest - case _: GossipStatus ⇒ GossipStatusManifest - case _: GossipEnvelope ⇒ GossipEnvelopeManifest - case _: ClusterRouterPool ⇒ ClusterRouterPoolManifest - case _ ⇒ + case _: InternalClusterAction.Join => JoinManifest + case _: InternalClusterAction.Welcome => WelcomeManifest + case _: ClusterUserAction.Leave => LeaveManifest + case _: ClusterUserAction.Down => DownManifest + case _: InternalClusterAction.InitJoin => InitJoinManifest + case _: InternalClusterAction.InitJoinAck => InitJoinAckManifest + case _: InternalClusterAction.InitJoinNack => InitJoinNackManifest + case _: ClusterHeartbeatSender.Heartbeat => HeartBeatManifest + case _: ClusterHeartbeatSender.HeartbeatRsp => HeartBeatRspManifest + case _: ExitingConfirmed => ExitingConfirmedManifest + case _: GossipStatus => GossipStatusManifest + case _: GossipEnvelope => GossipEnvelopeManifest + case _: ClusterRouterPool => ClusterRouterPoolManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass} in [${getClass.getName}]") } def toBinary(obj: AnyRef): Array[Byte] = obj match { - case ClusterHeartbeatSender.Heartbeat(from) ⇒ addressToProtoByteArray(from) - case ClusterHeartbeatSender.HeartbeatRsp(from) ⇒ uniqueAddressToProtoByteArray(from) - case m: GossipEnvelope ⇒ gossipEnvelopeToProto(m).toByteArray - case m: GossipStatus ⇒ gossipStatusToProto(m).toByteArray - case InternalClusterAction.Join(node, roles) ⇒ joinToProto(node, roles).toByteArray - case InternalClusterAction.Welcome(from, gossip) ⇒ compress(welcomeToProto(from, gossip)) - case ClusterUserAction.Leave(address) ⇒ addressToProtoByteArray(address) - case ClusterUserAction.Down(address) ⇒ addressToProtoByteArray(address) - case InternalClusterAction.InitJoin(config) ⇒ initJoinToProto(config).toByteArray - case InternalClusterAction.InitJoinAck(address, configCheck) ⇒ initJoinAckToByteArray(address, configCheck) - case InternalClusterAction.InitJoinNack(address) ⇒ addressToProtoByteArray(address) - case InternalClusterAction.ExitingConfirmed(node) ⇒ uniqueAddressToProtoByteArray(node) - case rp: ClusterRouterPool ⇒ clusterRouterPoolToProtoByteArray(rp) - case _ ⇒ + case ClusterHeartbeatSender.Heartbeat(from) => addressToProtoByteArray(from) + case ClusterHeartbeatSender.HeartbeatRsp(from) => uniqueAddressToProtoByteArray(from) + case m: GossipEnvelope => gossipEnvelopeToProto(m).toByteArray + case m: GossipStatus => gossipStatusToProto(m).toByteArray + case InternalClusterAction.Join(node, roles) => joinToProto(node, roles).toByteArray + case InternalClusterAction.Welcome(from, gossip) => compress(welcomeToProto(from, gossip)) + case ClusterUserAction.Leave(address) => addressToProtoByteArray(address) + case ClusterUserAction.Down(address) => addressToProtoByteArray(address) + case InternalClusterAction.InitJoin(config) => initJoinToProto(config).toByteArray + case InternalClusterAction.InitJoinAck(address, configCheck) => initJoinAckToByteArray(address, configCheck) + case InternalClusterAction.InitJoinNack(address) => addressToProtoByteArray(address) + case InternalClusterAction.ExitingConfirmed(node) => uniqueAddressToProtoByteArray(node) + case rp: ClusterRouterPool => clusterRouterPoolToProtoByteArray(rp) + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case HeartBeatManifest ⇒ deserializeHeartBeat(bytes) - case HeartBeatRspManifest ⇒ deserializeHeartBeatRsp(bytes) - case GossipStatusManifest ⇒ deserializeGossipStatus(bytes) - case GossipEnvelopeManifest ⇒ deserializeGossipEnvelope(bytes) - case InitJoinManifest ⇒ deserializeInitJoin(bytes) - case InitJoinAckManifest ⇒ deserializeInitJoinAck(bytes) - case InitJoinNackManifest ⇒ deserializeInitJoinNack(bytes) - case JoinManifest ⇒ deserializeJoin(bytes) - case WelcomeManifest ⇒ deserializeWelcome(bytes) - case LeaveManifest ⇒ deserializeLeave(bytes) - case DownManifest ⇒ deserializeDown(bytes) - case ExitingConfirmedManifest ⇒ deserializeExitingConfirmed(bytes) - case ClusterRouterPoolManifest ⇒ deserializeClusterRouterPool(bytes) - case _ ⇒ throw new IllegalArgumentException(s"Unknown manifest [${manifest}]") + case HeartBeatManifest => deserializeHeartBeat(bytes) + case HeartBeatRspManifest => deserializeHeartBeatRsp(bytes) + case GossipStatusManifest => deserializeGossipStatus(bytes) + case GossipEnvelopeManifest => deserializeGossipEnvelope(bytes) + case InitJoinManifest => deserializeInitJoin(bytes) + case InitJoinAckManifest => deserializeInitJoinAck(bytes) + case InitJoinNackManifest => deserializeInitJoinNack(bytes) + case JoinManifest => deserializeJoin(bytes) + case WelcomeManifest => deserializeWelcome(bytes) + case LeaveManifest => deserializeLeave(bytes) + case DownManifest => deserializeDown(bytes) + case ExitingConfirmedManifest => deserializeExitingConfirmed(bytes) + case ClusterRouterPoolManifest => deserializeClusterRouterPool(bytes) + case _ => throw new IllegalArgumentException(s"Unknown manifest [${manifest}]") } def compress(msg: MessageLite): Array[Byte] = { @@ -128,8 +128,8 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se val buffer = new Array[Byte](BufferSize) @tailrec def readChunk(): Unit = in.read(buffer) match { - case -1 ⇒ () - case n ⇒ + case -1 => () + case n => out.write(buffer, 0, n) readChunk() } @@ -146,9 +146,9 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se uniqueAddressFromProto(cm.UniqueAddress.parseFrom(bytes)) private[akka] def addressToProto(address: Address): cm.Address.Builder = address match { - case Address(protocol, actorSystem, Some(host), Some(port)) ⇒ + case Address(protocol, actorSystem, Some(host), Some(port)) => cm.Address.newBuilder().setSystem(actorSystem).setHostname(host).setPort(port).setProtocol(protocol) - case _ ⇒ throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") } private def addressToProtoByteArray(address: Address): Array[Byte] = addressToProto(address).build.toByteArray @@ -255,14 +255,14 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se val i = cm.InitJoinAck.parseFrom(bytes) val configCheck = i.getConfigCheck.getType match { - case cm.ConfigCheck.Type.CompatibleConfig ⇒ CompatibleConfig(ConfigFactory.parseString(i.getConfigCheck.getClusterConfig)) - case cm.ConfigCheck.Type.IncompatibleConfig ⇒ IncompatibleConfig - case cm.ConfigCheck.Type.UncheckedConfig ⇒ UncheckedConfig + case cm.ConfigCheck.Type.CompatibleConfig => CompatibleConfig(ConfigFactory.parseString(i.getConfigCheck.getClusterConfig)) + case cm.ConfigCheck.Type.IncompatibleConfig => IncompatibleConfig + case cm.ConfigCheck.Type.UncheckedConfig => UncheckedConfig } InternalClusterAction.InitJoinAck(addressFromProto(i.getAddress), configCheck) } catch { - case _: akka.protobuf.InvalidProtocolBufferException ⇒ + case _: akka.protobuf.InvalidProtocolBufferException => // nodes previous to 2.5.9 sends just an address InternalClusterAction.InitJoinAck(addressFromBinary(bytes), UncheckedConfig) } @@ -301,26 +301,26 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se } private val memberStatusToInt = scala.collection.immutable.HashMap[MemberStatus, Int]( - MemberStatus.Joining → cm.MemberStatus.Joining_VALUE, - MemberStatus.Up → cm.MemberStatus.Up_VALUE, - MemberStatus.Leaving → cm.MemberStatus.Leaving_VALUE, - MemberStatus.Exiting → cm.MemberStatus.Exiting_VALUE, - MemberStatus.Down → cm.MemberStatus.Down_VALUE, - MemberStatus.Removed → cm.MemberStatus.Removed_VALUE, - MemberStatus.WeaklyUp → cm.MemberStatus.WeaklyUp_VALUE) + MemberStatus.Joining -> cm.MemberStatus.Joining_VALUE, + MemberStatus.Up -> cm.MemberStatus.Up_VALUE, + MemberStatus.Leaving -> cm.MemberStatus.Leaving_VALUE, + MemberStatus.Exiting -> cm.MemberStatus.Exiting_VALUE, + MemberStatus.Down -> cm.MemberStatus.Down_VALUE, + MemberStatus.Removed -> cm.MemberStatus.Removed_VALUE, + MemberStatus.WeaklyUp -> cm.MemberStatus.WeaklyUp_VALUE) - private val memberStatusFromInt = memberStatusToInt.map { case (a, b) ⇒ (b, a) } + private val memberStatusFromInt = memberStatusToInt.map { case (a, b) => (b, a) } private val reachabilityStatusToInt = scala.collection.immutable.HashMap[Reachability.ReachabilityStatus, Int]( - Reachability.Reachable → cm.ReachabilityStatus.Reachable_VALUE, - Reachability.Unreachable → cm.ReachabilityStatus.Unreachable_VALUE, - Reachability.Terminated → cm.ReachabilityStatus.Terminated_VALUE) + Reachability.Reachable -> cm.ReachabilityStatus.Reachable_VALUE, + Reachability.Unreachable -> cm.ReachabilityStatus.Unreachable_VALUE, + Reachability.Terminated -> cm.ReachabilityStatus.Terminated_VALUE) - private val reachabilityStatusFromInt = reachabilityStatusToInt.map { case (a, b) ⇒ (b, a) } + private val reachabilityStatusFromInt = reachabilityStatusToInt.map { case (a, b) => (b, a) } private def mapWithErrorMessage[T](map: Map[T, Int], value: T, unknown: String): Int = map.get(value) match { - case Some(x) ⇒ x - case _ ⇒ throw new IllegalArgumentException(s"Unknown $unknown [$value] in cluster message") + case Some(x) => x + case _ => throw new IllegalArgumentException(s"Unknown $unknown [$value] in cluster message") } private def joinToProto(node: UniqueAddress, roles: Set[String]): cm.Join = @@ -343,18 +343,18 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se val configCheckBuilder = cm.ConfigCheck.newBuilder() configCheck match { - case UncheckedConfig ⇒ + case UncheckedConfig => configCheckBuilder.setType(cm.ConfigCheck.Type.UncheckedConfig) - case IncompatibleConfig ⇒ + case IncompatibleConfig => configCheckBuilder.setType(cm.ConfigCheck.Type.IncompatibleConfig) - case CompatibleConfig(conf) ⇒ + case CompatibleConfig(conf) => configCheckBuilder .setType(cm.ConfigCheck.Type.CompatibleConfig) .setClusterConfig(conf.root.render(ConfigRenderOptions.concise)) - case ConfigCheckUnsupportedByJoiningNode ⇒ + case ConfigCheckUnsupportedByJoiningNode => // handled as Address in initJoinAckToByteArray throw new IllegalStateException("Unexpected ConfigCheckUnsupportedByJoiningNode") } @@ -372,7 +372,7 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se val allMembers = gossip.members.toVector val allAddresses: Vector[UniqueAddress] = allMembers.map(_.uniqueAddress) ++ gossip.tombstones.keys val addressMapping = allAddresses.zipWithIndex.toMap - val allRoles = allMembers.foldLeft(Set.empty[String])((acc, m) ⇒ acc union m.roles).to(Vector) + val allRoles = allMembers.foldLeft(Set.empty[String])((acc, m) => acc union m.roles).to(Vector) val roleMapping = allRoles.zipWithIndex.toMap val allHashes = gossip.version.versions.keys.to(Vector) val hashMapping = allHashes.zipWithIndex.toMap @@ -388,8 +388,8 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se def reachabilityToProto(reachability: Reachability): Iterable[cm.ObserverReachability.Builder] = { reachability.versions.map { - case (observer, version) ⇒ - val subjectReachability = reachability.recordsFrom(observer).map(r ⇒ + case (observer, version) => + val subjectReachability = reachability.recordsFrom(observer).map(r => cm.SubjectReachability.newBuilder().setAddressIndex(mapUniqueAddress(r.subject)). setStatus(cm.ReachabilityStatus.valueOf(reachabilityStatusToInt(r.status))). setVersion(r.version)) @@ -422,7 +422,7 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se private def vectorClockToProto(version: VectorClock, hashMapping: Map[String, Int]): cm.VectorClock.Builder = { val versions: Iterable[cm.VectorClock.Version.Builder] = version.versions.map { - case (n, t) ⇒ cm.VectorClock.Version.newBuilder().setHashIndex(mapWithErrorMessage(hashMapping, n, "hash")). + case (n, t) => cm.VectorClock.Version.newBuilder().setHashIndex(mapWithErrorMessage(hashMapping, n, "hash")). setTimestamp(t) } cm.VectorClock.newBuilder().setTimestamp(0).addAllVersions(versions.map(_.build).asJava) @@ -457,10 +457,10 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se def reachabilityFromProto(observerReachability: Iterable[cm.ObserverReachability]): Reachability = { val recordBuilder = new immutable.VectorBuilder[Reachability.Record] val versionsBuilder = Map.newBuilder[UniqueAddress, Long] - for (o ← observerReachability) { + for (o <- observerReachability) { val observer = addressMapping(o.getAddressIndex) versionsBuilder += ((observer, o.getVersion)) - for (s ← o.getSubjectReachabilityList.asScala) { + for (s <- o.getSubjectReachabilityList.asScala) { val subject = addressMapping(s.getAddressIndex) val record = Reachability.Record(observer, subject, reachabilityStatusFromInt(s.getStatus.getNumber), s.getVersion) recordBuilder += record @@ -479,7 +479,7 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se var roles = Set.empty[String] for { - roleIndex ← roleIndexes + roleIndex <- roleIndexes role = roleMapping(roleIndex) } { if (role.startsWith(ClusterSettings.DcRolePrefix)) containsDc = true @@ -505,13 +505,13 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) extends Se private def vectorClockFromProto(version: cm.VectorClock, hashMapping: immutable.Seq[String]) = { VectorClock(scala.collection.immutable.TreeMap.from(version.getVersionsList.asScala.iterator.map( - v ⇒ (VectorClock.Node.fromHash(hashMapping(v.getHashIndex)), v.getTimestamp)))) + v => (VectorClock.Node.fromHash(hashMapping(v.getHashIndex)), v.getTimestamp)))) } private def gossipEnvelopeFromProto(envelope: cm.GossipEnvelope): GossipEnvelope = { val serializedGossip = envelope.getSerializedGossip GossipEnvelope(uniqueAddressFromProto(envelope.getFrom), uniqueAddressFromProto(envelope.getTo), - Deadline.now + GossipTimeToLive, () ⇒ gossipFromProto(cm.Gossip.parseFrom(decompress(serializedGossip.toByteArray)))) + Deadline.now + GossipTimeToLive, () => gossipFromProto(cm.Gossip.parseFrom(decompress(serializedGossip.toByteArray)))) } private def gossipStatusFromProto(status: cm.GossipStatus): GossipStatus = diff --git a/akka-cluster/src/main/scala/akka/cluster/routing/ClusterRouterConfig.scala b/akka-cluster/src/main/scala/akka/cluster/routing/ClusterRouterConfig.scala index f7664fca53..769e2e0beb 100644 --- a/akka-cluster/src/main/scala/akka/cluster/routing/ClusterRouterConfig.scala +++ b/akka-cluster/src/main/scala/akka/cluster/routing/ClusterRouterConfig.scala @@ -90,8 +90,8 @@ final case class ClusterRouterGroupSettings( throw new IllegalArgumentException("routeesPaths must be defined") routeesPaths.foreach { - case RelativeActorPath(_) ⇒ // good - case p ⇒ + case RelativeActorPath(_) => // good + case p => throw new IllegalArgumentException(s"routeesPaths [$p] is not a valid actor path without address information") } @@ -180,8 +180,8 @@ final case class ClusterRouterPoolSettings( */ private[akka] object ClusterRouterSettingsBase { def useRoleOption(role: String): Option[String] = role match { - case null | "" ⇒ None - case _ ⇒ Some(role) + case null | "" => None + case _ => Some(role) } /** @@ -192,8 +192,8 @@ private[akka] object ClusterRouterSettingsBase { */ def getMaxTotalNrOfInstances(config: Config): Int = config.getInt("nr-of-instances") match { - case 1 | 0 ⇒ config.getInt("cluster.max-nr-of-instances-per-node") - case other ⇒ other + case 1 | 0 => config.getInt("cluster.max-nr-of-instances-per-node") + case other => other } } @@ -207,7 +207,7 @@ private[akka] trait ClusterRouterSettingsBase { require(totalInstances > 0, "totalInstances of cluster router must be > 0") require(useRoles != null, "useRoles must be non-null") - require(!useRoles.exists(role ⇒ role == null || role.isEmpty), "All roles in useRoles must be non-empty") + require(!useRoles.exists(role => role == null || role.isEmpty), "All roles in useRoles must be non-empty") } /** @@ -234,11 +234,11 @@ final case class ClusterRouterGroup(local: Group, settings: ClusterRouterGroupSe override private[akka] def createRouterActor(): RouterActor = new ClusterRouterGroupActor(settings) override def withFallback(other: RouterConfig): RouterConfig = other match { - case ClusterRouterGroup(_: ClusterRouterGroup, _) ⇒ throw new IllegalStateException( + case ClusterRouterGroup(_: ClusterRouterGroup, _) => throw new IllegalStateException( "ClusterRouterGroup is not allowed to wrap a ClusterRouterGroup") - case ClusterRouterGroup(otherLocal, _) ⇒ + case ClusterRouterGroup(otherLocal, _) => copy(local = this.local.withFallback(otherLocal).asInstanceOf[Group]) - case _ ⇒ + case _ => copy(local = this.local.withFallback(other).asInstanceOf[Group]) } @@ -289,11 +289,11 @@ final case class ClusterRouterPool(local: Pool, settings: ClusterRouterPoolSetti override def supervisorStrategy: SupervisorStrategy = local.supervisorStrategy override def withFallback(other: RouterConfig): RouterConfig = other match { - case ClusterRouterPool(_: ClusterRouterPool, _) ⇒ + case ClusterRouterPool(_: ClusterRouterPool, _) => throw new IllegalStateException("ClusterRouterPool is not allowed to wrap a ClusterRouterPool") - case ClusterRouterPool(otherLocal, _) ⇒ + case ClusterRouterPool(otherLocal, _) => copy(local = this.local.withFallback(otherLocal).asInstanceOf[Pool]) - case _ ⇒ + case _ => copy(local = this.local.withFallback(other).asInstanceOf[Pool]) } @@ -331,8 +331,8 @@ private[akka] class ClusterRouterPoolActor( override def addRoutees(): Unit = { @tailrec def doAddRoutees(): Unit = selectDeploymentTarget match { - case None ⇒ // done - case Some(target) ⇒ + case None => // done + case Some(target) => val routeeProps = cell.routeeProps val deploy = Deploy(config = ConfigFactory.empty(), routerConfig = routeeProps.routerConfig, scope = RemoteScope(target)) @@ -355,10 +355,10 @@ private[akka] class ClusterRouterPoolActor( } else { // find the node with least routees val numberOfRouteesPerNode: Map[Address, Int] = { - val nodeMap: Map[Address, Int] = currentNodes.map(_ → 0).toMap.withDefaultValue(0) - currentRoutees.foldLeft(nodeMap) { (acc, x) ⇒ + val nodeMap: Map[Address, Int] = currentNodes.map(_ -> 0).toMap.withDefaultValue(0) + currentRoutees.foldLeft(nodeMap) { (acc, x) => val address = fullAddress(x) - acc + (address → (acc(address) + 1)) + acc + (address -> (acc(address) + 1)) } } @@ -376,8 +376,8 @@ private[akka] class ClusterRouterGroupActor(val settings: ClusterRouterGroupSett extends RouterActor with ClusterRouterActor { val group = cell.routerConfig match { - case x: Group ⇒ x - case other ⇒ + case x: Group => x + case other => throw ActorInitializationException("ClusterRouterGroupActor can only be used with group, not " + other.getClass) } @@ -385,7 +385,7 @@ private[akka] class ClusterRouterGroupActor(val settings: ClusterRouterGroupSett var usedRouteePaths: Map[Address, Set[String]] = if (settings.allowLocalRoutees) - Map(cluster.selfAddress → settings.routeesPaths.toSet) + Map(cluster.selfAddress -> settings.routeesPaths.toSet) else Map.empty @@ -395,8 +395,8 @@ private[akka] class ClusterRouterGroupActor(val settings: ClusterRouterGroupSett override def addRoutees(): Unit = { @tailrec def doAddRoutees(): Unit = selectDeploymentTarget match { - case None ⇒ // done - case Some((address, path)) ⇒ + case None => // done + case Some((address, path)) => val routee = group.routeeFor(address + path, context) usedRouteePaths = usedRouteePaths.updated(address, usedRouteePaths.getOrElse(address, Set.empty) + path) // must register each one, since registered routees are used in selectDeploymentTarget @@ -421,9 +421,9 @@ private[akka] class ClusterRouterGroupActor(val settings: ClusterRouterGroupSett if (unusedNodes.nonEmpty) { Some((unusedNodes.head, settings.routeesPaths.head)) } else { - val (address, used) = usedRouteePaths.minBy { case (_, used) ⇒ used.size } + val (address, used) = usedRouteePaths.minBy { case (_, used) => used.size } // pick next of the unused paths - settings.routeesPaths.collectFirst { case p if !used.contains(p) ⇒ (address, p) } + settings.routeesPaths.collectFirst { case p if !used.contains(p) => (address, p) } } } } @@ -439,7 +439,7 @@ private[akka] class ClusterRouterGroupActor(val settings: ClusterRouterGroupSett * The router actor, subscribes to cluster events and * adjusts the routees. */ -private[akka] trait ClusterRouterActor { this: RouterActor ⇒ +private[akka] trait ClusterRouterActor { this: RouterActor => def settings: ClusterRouterSettingsBase @@ -458,7 +458,7 @@ private[akka] trait ClusterRouterActor { this: RouterActor ⇒ var nodes: immutable.SortedSet[Address] = { import akka.cluster.Member.addressOrdering cluster.readView.members.collect { - case m if isAvailable(m) ⇒ m.address + case m if isAvailable(m) => m.address } } @@ -483,12 +483,12 @@ private[akka] trait ClusterRouterActor { this: RouterActor ⇒ */ def fullAddress(routee: Routee): Address = { val address = routee match { - case ActorRefRoutee(ref) ⇒ ref.path.address - case ActorSelectionRoutee(sel) ⇒ sel.anchor.path.address + case ActorRefRoutee(ref) => ref.path.address + case ActorSelectionRoutee(sel) => sel.anchor.path.address } address match { - case Address(_, _, None, None) ⇒ cluster.selfAddress - case a ⇒ a + case Address(_, _, None, None) => cluster.selfAddress + case a => a } } @@ -516,23 +516,23 @@ private[akka] trait ClusterRouterActor { this: RouterActor ⇒ } def clusterReceive: Receive = { - case s: CurrentClusterState ⇒ + case s: CurrentClusterState => import akka.cluster.Member.addressOrdering - nodes = s.members.collect { case m if isAvailable(m) ⇒ m.address } + nodes = s.members.collect { case m if isAvailable(m) => m.address } addRoutees() - case m: MemberEvent if isAvailable(m.member) ⇒ + case m: MemberEvent if isAvailable(m.member) => addMember(m.member) - case other: MemberEvent ⇒ + case other: MemberEvent => // other events means that it is no longer interesting, such as // MemberExited, MemberRemoved removeMember(other.member) - case UnreachableMember(m) ⇒ + case UnreachableMember(m) => removeMember(m) - case ReachableMember(m) ⇒ + case ReachableMember(m) => if (isAvailable(m)) addMember(m) } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/AttemptSysMsgRedeliverySpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/AttemptSysMsgRedeliverySpec.scala index 69c5342ada..a821156408 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/AttemptSysMsgRedeliverySpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/AttemptSysMsgRedeliverySpec.scala @@ -27,7 +27,7 @@ object AttemptSysMsgRedeliveryMultiJvmSpec extends MultiNodeConfig { class Echo extends Actor { def receive = { - case m ⇒ sender ! m + case m => sender ! m } } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/ClusterDeathWatchSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/ClusterDeathWatchSpec.scala index 7423e915c1..00560acedf 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/ClusterDeathWatchSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/ClusterDeathWatchSpec.scala @@ -76,13 +76,13 @@ abstract class ClusterDeathWatchSpec context.actorSelection(path3) ! Identify(path3) def receive = { - case ActorIdentity(`path2`, Some(ref)) ⇒ + case ActorIdentity(`path2`, Some(ref)) => context.watch(ref) watchEstablished.countDown - case ActorIdentity(`path3`, Some(ref)) ⇒ + case ActorIdentity(`path3`, Some(ref)) => context.watch(ref) watchEstablished.countDown - case Terminated(actor) ⇒ testActor ! actor.path + case Terminated(actor) => testActor ! actor.path } }).withDeploy(Deploy.local), name = "observer1") @@ -142,7 +142,7 @@ abstract class ClusterDeathWatchSpec system.actorOf(Props(new Actor { context.watch(context.actorFor(path)) def receive = { - case t: Terminated ⇒ testActor ! t.actor.path + case t: Terminated => testActor ! t.actor.path } }).withDeploy(Deploy.local), name = "observer3") @@ -167,7 +167,7 @@ abstract class ClusterDeathWatchSpec awaitAssert { remoteWatcher ! RemoteWatcher.Stats val stats = expectMsgType[RemoteWatcher.Stats] - stats.watchingRefs should contain(subject5 → testActor) + stats.watchingRefs should contain(subject5 -> testActor) stats.watchingAddresses should contain(address(fifth)) } } @@ -235,7 +235,7 @@ abstract class ClusterDeathWatchSpec val timeout = remainingOrDefault try Await.ready(system.whenTerminated, timeout) catch { - case _: TimeoutException ⇒ + case _: TimeoutException => fail("Failed to stop [%s] within [%s] \n%s".format(system.name, timeout, system.asInstanceOf[ActorSystemImpl].printTree)) } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/ConvergenceSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/ConvergenceSpec.scala index d83815b78e..6fc404bbaf 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/ConvergenceSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/ConvergenceSpec.scala @@ -93,12 +93,12 @@ abstract class ConvergenceSpec(multiNodeConfig: ConvergenceMultiNodeConfig) } def memberStatus(address: Address): Option[MemberStatus] = - clusterView.members.collectFirst { case m if m.address == address ⇒ m.status } + clusterView.members.collectFirst { case m if m.address == address => m.status } enterBarrier("after-join") runOn(first, second, fourth) { - for (n ← 1 to 5) { + for (n <- 1 to 5) { awaitAssert(clusterView.members.size should ===(4)) awaitSeenSameState(first, second, fourth) memberStatus(first) should ===(Some(MemberStatus.Up)) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/DeterministicOldestWhenJoiningSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/DeterministicOldestWhenJoiningSpec.scala index 57ecf2d505..c17457e3dc 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/DeterministicOldestWhenJoiningSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/DeterministicOldestWhenJoiningSpec.scala @@ -39,7 +39,7 @@ abstract class DeterministicOldestWhenJoiningSpec // reverse order because that expose the bug in issue #18554 def seedNodes: immutable.IndexedSeq[Address] = Vector(address(seed1), address(seed2), address(seed3)).sorted(Member.addressOrdering).reverse - val roleByAddress = Map(address(seed1) → seed1, address(seed2) → seed2, address(seed3) → seed3) + val roleByAddress = Map(address(seed1) -> seed1, address(seed2) -> seed2, address(seed3) -> seed3) "Joining a cluster" must { "result in deterministic oldest node" taggedAs LongRunningTest in { diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/DisallowJoinOfTwoClustersSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/DisallowJoinOfTwoClustersSpec.scala index 3c8ae82806..60558d49be 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/DisallowJoinOfTwoClustersSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/DisallowJoinOfTwoClustersSpec.scala @@ -65,7 +65,7 @@ abstract class DisallowJoinOfTwoClustersSpec } // no change expected - 1 to 5 foreach { _ ⇒ + 1 to 5 foreach { _ => clusterView.members.size should ===(expectedSize) Thread.sleep(1000) } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/LargeMessageClusterSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/LargeMessageClusterSpec.scala index a922ec0c05..48bf538129 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/LargeMessageClusterSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/LargeMessageClusterSpec.scala @@ -66,7 +66,7 @@ object LargeMessageClusterMultiJvmSpec extends MultiNodeConfig { override def identifier = 999 override def manifest(o: AnyRef) = "a" override def toBinary(o: AnyRef) = o match { - case Slow(payload) ⇒ + case Slow(payload) => // simulate slow serialization to not completely overload the machine/network, see issue #24576 Thread.sleep(100) payload @@ -125,9 +125,9 @@ abstract class LargeMessageClusterSpec extends MultiNodeSpec(LargeMessageCluster val largeMsg = ("0" * largeMsgSize).getBytes("utf-8") val largeMsgBurst = 3 val repeat = 15 - for (n ← 1 to repeat) { + for (n <- 1 to repeat) { val startTime = System.nanoTime() - for (_ ← 1 to largeMsgBurst) { + for (_ <- 1 to largeMsgBurst) { largeEcho3.tell(largeMsg, largeEchoProbe.ref) } @@ -161,7 +161,7 @@ abstract class LargeMessageClusterSpec extends MultiNodeSpec(LargeMessageCluster val largeMsgSize = 1 * 1000 * 1000 val payload = ("0" * largeMsgSize).getBytes("utf-8") val largeMsg = if (aeronUdpEnabled) payload else Slow(payload) - (1 to 3).foreach { _ ⇒ + (1 to 3).foreach { _ => // this will ping-pong between second and third largeEcho2.tell(largeMsg, largeEcho3) } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderDowningAllOtherNodesSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderDowningAllOtherNodesSpec.scala index 1263efad22..11f30a83e4 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderDowningAllOtherNodesSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderDowningAllOtherNodesSpec.scala @@ -51,7 +51,7 @@ abstract class LeaderDowningAllOtherNodesSpec val shutdownAddresses = others.map(address).toSet enterBarrier("before-all-other-shutdown") runOn(first) { - for (node ← others) + for (node <- others) testConductor.exit(node, 0).await } enterBarrier("all-other-shutdown") diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderElectionSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderElectionSpec.scala index edcbcf1e2a..64309440ac 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderElectionSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderElectionSpec.scala @@ -66,17 +66,17 @@ abstract class LeaderElectionSpec(multiNodeConfig: LeaderElectionMultiNodeConfig myself match { - case `controller` ⇒ + case `controller` => val leaderAddress = address(leader) enterBarrier("before-shutdown" + n) testConductor.exit(leader, 0).await enterBarrier("after-shutdown" + n, "after-unavailable" + n, "after-down" + n, "completed" + n) - case `leader` ⇒ + case `leader` => enterBarrier("before-shutdown" + n, "after-shutdown" + n) // this node will be shutdown by the controller and doesn't participate in more barriers - case `aUser` ⇒ + case `aUser` => val leaderAddress = address(leader) enterBarrier("before-shutdown" + n, "after-shutdown" + n) @@ -91,7 +91,7 @@ abstract class LeaderElectionSpec(multiNodeConfig: LeaderElectionMultiNodeConfig awaitAssert(clusterView.unreachableMembers.map(_.address) should not contain (leaderAddress)) enterBarrier("after-down" + n, "completed" + n) - case _ if remainingRoles.contains(myself) ⇒ + case _ if remainingRoles.contains(myself) => // remaining cluster nodes, not shutdown val leaderAddress = address(leader) enterBarrier("before-shutdown" + n, "after-shutdown" + n) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderLeavingSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderLeavingSpec.scala index 1947252b7b..c0d6faf0f1 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderLeavingSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/LeaderLeavingSpec.scala @@ -62,11 +62,11 @@ abstract class LeaderLeavingSpec cluster.subscribe(system.actorOf(Props(new Actor { def receive = { - case state: CurrentClusterState ⇒ - if (state.members.exists(m ⇒ m.address == oldLeaderAddress && m.status == Exiting)) + case state: CurrentClusterState => + if (state.members.exists(m => m.address == oldLeaderAddress && m.status == Exiting)) exitingLatch.countDown() - case MemberExited(m) if m.address == oldLeaderAddress ⇒ exitingLatch.countDown() - case _ ⇒ // ignore + case MemberExited(m) if m.address == oldLeaderAddress => exitingLatch.countDown() + case _ => // ignore } }).withDeploy(Deploy.local)), classOf[MemberEvent]) enterBarrier("registered-listener") diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MemberWeaklyUpSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MemberWeaklyUpSpec.scala index ece84b71f4..fe2ffa4c75 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MemberWeaklyUpSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MemberWeaklyUpSpec.scala @@ -58,7 +58,7 @@ abstract class MemberWeaklyUpSpec "detect network partition and mark nodes on other side as unreachable" taggedAs LongRunningTest in within(20 seconds) { runOn(first) { // split the cluster in two parts (first, second) / (third, fourth, fifth) - for (role1 ← side1; role2 ← side2) { + for (role1 <- side1; role2 <- side2) { testConductor.blackhole(role1, role2, Direction.Both).await } } @@ -87,14 +87,14 @@ abstract class MemberWeaklyUpSpec runOn(side1: _*) { awaitAssert { clusterView.members.size should be(4) - clusterView.members.exists { m ⇒ m.address == address(second) && m.status == WeaklyUp } should be(true) + clusterView.members.exists { m => m.address == address(second) && m.status == WeaklyUp } should be(true) } } runOn(side2: _*) { awaitAssert { clusterView.members.size should be(4) - clusterView.members.exists { m ⇒ m.address == address(fifth) && m.status == WeaklyUp } should be(true) + clusterView.members.exists { m => m.address == address(fifth) && m.status == WeaklyUp } should be(true) } } @@ -103,7 +103,7 @@ abstract class MemberWeaklyUpSpec "change status to Up after healed network partition" taggedAs LongRunningTest in within(20 seconds) { runOn(first) { - for (role1 ← side1; role2 ← side2) { + for (role1 <- side1; role2 <- side2) { testConductor.passThrough(role1, role2, Direction.Both).await } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MembershipChangeListenerExitingSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MembershipChangeListenerExitingSpec.scala index 9fd2151f7e..9c9aeca855 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MembershipChangeListenerExitingSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MembershipChangeListenerExitingSpec.scala @@ -47,14 +47,14 @@ abstract class MembershipChangeListenerExitingSpec val secondAddress = address(second) cluster.subscribe(system.actorOf(Props(new Actor { def receive = { - case state: CurrentClusterState ⇒ - if (state.members.exists(m ⇒ m.address == secondAddress && m.status == Exiting)) + case state: CurrentClusterState => + if (state.members.exists(m => m.address == secondAddress && m.status == Exiting)) exitingLatch.countDown() - case MemberExited(m) if m.address == secondAddress ⇒ + case MemberExited(m) if m.address == secondAddress => exitingLatch.countDown() - case MemberRemoved(m, Exiting) if m.address == secondAddress ⇒ + case MemberRemoved(m, Exiting) if m.address == secondAddress => removedLatch.countDown() - case _ ⇒ // ignore + case _ => // ignore } }).withDeploy(Deploy.local)), classOf[MemberEvent]) enterBarrier("registered-listener") @@ -67,12 +67,12 @@ abstract class MembershipChangeListenerExitingSpec val secondAddress = address(second) cluster.subscribe(system.actorOf(Props(new Actor { def receive = { - case state: CurrentClusterState ⇒ - if (state.members.exists(m ⇒ m.address == secondAddress && m.status == Exiting)) + case state: CurrentClusterState => + if (state.members.exists(m => m.address == secondAddress && m.status == Exiting)) exitingLatch.countDown() - case MemberExited(m) if m.address == secondAddress ⇒ + case MemberExited(m) if m.address == secondAddress => exitingLatch.countDown() - case _ ⇒ // ignore + case _ => // ignore } }).withDeploy(Deploy.local)), classOf[MemberEvent]) enterBarrier("registered-listener") diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MembershipChangeListenerUpSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MembershipChangeListenerUpSpec.scala index dbadff3daf..4741d86bae 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MembershipChangeListenerUpSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MembershipChangeListenerUpSpec.scala @@ -42,12 +42,12 @@ abstract class MembershipChangeListenerUpSpec cluster.subscribe(system.actorOf(Props(new Actor { var members = Set.empty[Member] def receive = { - case state: CurrentClusterState ⇒ members = state.members - case MemberUp(m) ⇒ + case state: CurrentClusterState => members = state.members + case MemberUp(m) => members = members - m + m if (members.map(_.address) == expectedAddresses) latch.countDown() - case _ ⇒ // ignore + case _ => // ignore } }).withDeploy(Deploy.local)), classOf[MemberEvent]) enterBarrier("listener-1-registered") @@ -69,12 +69,12 @@ abstract class MembershipChangeListenerUpSpec cluster.subscribe(system.actorOf(Props(new Actor { var members = Set.empty[Member] def receive = { - case state: CurrentClusterState ⇒ members = state.members - case MemberUp(m) ⇒ + case state: CurrentClusterState => members = state.members + case MemberUp(m) => members = members - m + m if (members.map(_.address) == expectedAddresses) latch.countDown() - case _ ⇒ // ignore + case _ => // ignore } }).withDeploy(Deploy.local)), classOf[MemberEvent]) enterBarrier("listener-2-registered") diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MinMembersBeforeUpSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MinMembersBeforeUpSpec.scala index 03c50a57f7..de4bf5851b 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MinMembersBeforeUpSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MinMembersBeforeUpSpec.scala @@ -134,7 +134,7 @@ abstract class MinMembersBeforeUpBase(multiNodeConfig: MultiNodeConfig) } clusterView.members.unsorted.map(_.status) should ===(Set(Joining)) // and it should not change - 1 to 5 foreach { _ ⇒ + 1 to 5 foreach { _ => Thread.sleep(1000) clusterView.members.map(_.address) should ===(expectedAddresses) clusterView.members.unsorted.map(_.status) should ===(Set(Joining)) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcClusterSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcClusterSpec.scala index 86ae661dab..4d876bd262 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcClusterSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcClusterSpec.scala @@ -141,7 +141,7 @@ abstract class MultiDcSpec(config: MultiDcSpecConfig) cluster.leave(fourth) awaitAssert(clusterView.members.map(_.address) should not contain address(fourth)) - awaitAssert(clusterView.members.collect { case m if m.status == Up ⇒ m.address } should contain(address(fifth))) + awaitAssert(clusterView.members.collect { case m if m.status == Up => m.address } should contain(address(fifth))) } enterBarrier("other-data-center-internal-unreachable changed") diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcHeartbeatTakingOverSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcHeartbeatTakingOverSpec.scala index d9f0bc92d4..e60293d591 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcHeartbeatTakingOverSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcHeartbeatTakingOverSpec.scala @@ -166,7 +166,7 @@ abstract class MultiDcHeartbeatTakingOverSpec extends MultiNodeSpec(MultiDcHeart observer.expectMsgType[CrossDcHeartbeatSender.MonitoringActive](5.seconds) info(s"Got confirmation from ${observer.lastSender} that it is actively monitoring now") } catch { - case ex: Throwable ⇒ + case ex: Throwable => throw new AssertionError(s"Monitoring was Dormant on ${cluster.selfAddress}, where we expected it to be active!", ex) } }, 20.seconds) @@ -184,7 +184,7 @@ abstract class MultiDcHeartbeatTakingOverSpec extends MultiNodeSpec(MultiDcHeart */ private def membersByAge(dataCenter: ClusterSettings.DataCenter): immutable.SortedSet[Member] = SortedSet.empty(Member.ageOrdering) - .union(cluster.state.members.filter(m ⇒ m.dataCenter == dataCenter && + .union(cluster.state.members.filter(m => m.dataCenter == dataCenter && m.status != MemberStatus.Joining && m.status != MemberStatus.WeaklyUp)) /** INTERNAL API */ @@ -193,7 +193,7 @@ abstract class MultiDcHeartbeatTakingOverSpec extends MultiNodeSpec(MultiDcHeart membersByAge(dataCenter).take(n) private def membersAsRoles(ms: SortedSet[Member]): List[RoleName] = { - val res = ms.toList.flatMap(m ⇒ roleName(m.address)) + val res = ms.toList.flatMap(m => roleName(m.address)) require(res.size == ms.size, s"Not all members were converted to roles! Got: ${ms}, found ${res}") res } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcSplitBrainSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcSplitBrainSpec.scala index 73189f8d27..6cd84bb6f3 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcSplitBrainSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcSplitBrainSpec.scala @@ -83,7 +83,7 @@ abstract class MultiDcSplitBrainSpec enterBarrier(s"split-$splits") runOn(first) { - for (dc1Node ← dc1; dc2Node ← dc2) { + for (dc1Node <- dc1; dc2Node <- dc2) { testConductor.blackhole(dc1Node, dc2Node, Direction.Both).await } } @@ -119,7 +119,7 @@ abstract class MultiDcSplitBrainSpec enterBarrier(s"unsplit-$unsplits") runOn(first) { - for (dc1Node ← dc1; dc2Node ← dc2) { + for (dc1Node <- dc1; dc2Node <- dc2) { testConductor.passThrough(dc1Node, dc2Node, Direction.Both).await } } @@ -156,7 +156,7 @@ abstract class MultiDcSplitBrainSpec // split is between dc1 and dc2 runOn(third, fourth) { awaitAssert(clusterView.members.collect { - case m if m.dataCenter == "dc2" && m.status == MemberStatus.Up ⇒ m.address + case m if m.dataCenter == "dc2" && m.status == MemberStatus.Up => m.address } should ===(Set(address(third), address(fourth)))) } enterBarrier("dc2-join-completed") @@ -165,7 +165,7 @@ abstract class MultiDcSplitBrainSpec runOn(dc1: _*) { awaitAssert(clusterView.members.collect { - case m if m.dataCenter == "dc2" && m.status == MemberStatus.Up ⇒ m.address + case m if m.dataCenter == "dc2" && m.status == MemberStatus.Up => m.address } should ===(Set(address(third), address(fourth)))) } @@ -210,9 +210,9 @@ abstract class MultiDcSplitBrainSpec var fifthOriginalUniqueAddress: Option[UniqueAddress] = None runOn(first, second, third, fifth) { awaitAssert(clusterView.members.collect { - case m if m.dataCenter == "dc2" && m.status == MemberStatus.Up ⇒ m.address + case m if m.dataCenter == "dc2" && m.status == MemberStatus.Up => m.address } should ===(Set(address(third), address(fifth)))) - fifthOriginalUniqueAddress = clusterView.members.collectFirst { case m if m.address == address(fifth) ⇒ m.uniqueAddress } + fifthOriginalUniqueAddress = clusterView.members.collectFirst { case m if m.address == address(fifth) => m.uniqueAddress } } enterBarrier("fifth-joined") @@ -224,7 +224,7 @@ abstract class MultiDcSplitBrainSpec runOn(third) { awaitAssert(clusterView.members.collect { - case m if m.dataCenter == "dc2" ⇒ m.address + case m if m.dataCenter == "dc2" => m.address } should ===(Set(address(third)))) } @@ -258,7 +258,7 @@ abstract class MultiDcSplitBrainSpec } runOn(first) { - for (dc1Node ← dc1; dc2Node ← dc2) { + for (dc1Node <- dc1; dc2Node <- dc2) { testConductor.passThrough(dc1Node, dc2Node, Direction.Both).await } testConductor.shutdown(fifth) @@ -270,7 +270,7 @@ abstract class MultiDcSplitBrainSpec runOn(first, second, third) { awaitAssert(clusterView.members.collectFirst { - case m if m.dataCenter == "dc2" && m.address == fifthOriginalUniqueAddress.get.address ⇒ m.uniqueAddress + case m if m.dataCenter == "dc2" && m.address == fifthOriginalUniqueAddress.get.address => m.uniqueAddress } should not be fifthOriginalUniqueAddress) // different uid subscribeProbe.expectMsgType[MemberUp].member.uniqueAddress should ===(fifthOriginalUniqueAddress.get) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcSunnyWeatherSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcSunnyWeatherSpec.scala index 768848b964..475347e81e 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcSunnyWeatherSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiDcSunnyWeatherSpec.scala @@ -123,15 +123,15 @@ abstract class MultiDcSunnyWeatherSpec extends MultiNodeSpec(MultiDcSunnyWeather implicit val sender = observer.ref selectCrossDcHeartbeatSender ! CrossDcHeartbeatSender.ReportStatus() observer.expectMsgType[CrossDcHeartbeatSender.MonitoringStateReport](5.seconds) match { - case CrossDcHeartbeatSender.MonitoringDormant() ⇒ // ok ... - case CrossDcHeartbeatSender.MonitoringActive(state) ⇒ + case CrossDcHeartbeatSender.MonitoringDormant() => // ok ... + case CrossDcHeartbeatSender.MonitoringActive(state) => // must not heartbeat myself state.activeReceivers should not contain cluster.selfUniqueAddress // not any of the members in the same datacenter; it's "cross-dc" after all val myDataCenterMembers = state.state.getOrElse(cluster.selfDataCenter, Set.empty) - myDataCenterMembers foreach { myDcMember ⇒ + myDataCenterMembers foreach { myDcMember => state.activeReceivers should not contain myDcMember.uniqueAddress } @@ -150,7 +150,7 @@ abstract class MultiDcSunnyWeatherSpec extends MultiNodeSpec(MultiDcSunnyWeather */ private def membersByAge(dataCenter: ClusterSettings.DataCenter): immutable.SortedSet[Member] = SortedSet.empty(Member.ageOrdering) - .union(cluster.state.members.filter(m ⇒ m.dataCenter == dataCenter && + .union(cluster.state.members.filter(m => m.dataCenter == dataCenter && m.status != MemberStatus.Joining && m.status != MemberStatus.WeaklyUp)) /** INTERNAL API */ @@ -159,7 +159,7 @@ abstract class MultiDcSunnyWeatherSpec extends MultiNodeSpec(MultiDcSunnyWeather membersByAge(dataCenter).take(n) private def membersAsRoles(ms: immutable.Set[Member]): immutable.Set[RoleName] = { - val res = ms.flatMap(m ⇒ roleName(m.address)) + val res = ms.flatMap(m => roleName(m.address)) require(res.size == ms.size, s"Not all members were converted to roles! Got: ${ms}, found ${res}") res } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiNodeClusterSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiNodeClusterSpec.scala index c93d49b741..7af09e95e7 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiNodeClusterSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/MultiNodeClusterSpec.scala @@ -83,20 +83,20 @@ object MultiNodeClusterSpec { class EndActor(testActor: ActorRef, target: Option[Address]) extends Actor { import EndActor._ def receive: Receive = { - case SendEnd ⇒ - target foreach { t ⇒ + case SendEnd => + target foreach { t => context.actorSelection(RootActorPath(t) / self.path.elements) ! End } - case End ⇒ + case End => testActor forward End sender() ! EndAck - case EndAck ⇒ + case EndAck => testActor forward EndAck } } } -trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoroner with FlightRecordingSupport { self: MultiNodeSpec ⇒ +trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoroner with FlightRecordingSupport { self: MultiNodeSpec => override def initialParticipants = roles.size @@ -126,7 +126,7 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoro ".*Cluster Node.* - is starting up.*", ".*Shutting down cluster Node.*", ".*Cluster node successfully shut down.*", - ".*Using a dedicated scheduler for cluster.*") foreach { s ⇒ + ".*Using a dedicated scheduler for cluster.*") foreach { s => sys.eventStream.publish(Mute(EventFilter.info(pattern = s))) } @@ -174,11 +174,11 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoro */ implicit def address(role: RoleName): Address = { cachedAddresses.get(role) match { - case null ⇒ + case null => val address = node(role).address cachedAddresses.put(role, address) address - case address ⇒ address + case address => address } } @@ -241,7 +241,7 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoro */ def joinWithin(joinNode: RoleName, max: Duration = remainingOrDefault, interval: Duration = 1.second): Unit = { def memberInState(member: Address, status: Seq[MemberStatus]): Boolean = - clusterView.members.exists { m ⇒ (m.address == member) && status.contains(m.status) } + clusterView.members.exists { m => (m.address == member) && status.contains(m.status) } cluster.join(joinNode) awaitCond({ @@ -264,7 +264,7 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoro import Member.addressOrdering val members = gotMembers.toIndexedSeq members.size should ===(expectedAddresses.length) - expectedAddresses.sorted.zipWithIndex.foreach { case (a, i) ⇒ members(i).address should ===(a) } + expectedAddresses.sorted.zipWithIndex.foreach { case (a, i) => members(i).address should ===(a) } } /** @@ -310,12 +310,12 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoro timeout: FiniteDuration = 25.seconds): Unit = { within(timeout) { if (!canNotBePartOfMemberRing.isEmpty) // don't run this on an empty set - awaitAssert(canNotBePartOfMemberRing foreach (a ⇒ clusterView.members.map(_.address) should not contain (a))) + awaitAssert(canNotBePartOfMemberRing foreach (a => clusterView.members.map(_.address) should not contain (a))) awaitAssert(clusterView.members.size should ===(numberOfMembers)) awaitAssert(clusterView.members.unsorted.map(_.status) should ===(Set(MemberStatus.Up))) // clusterView.leader is updated by LeaderChanged, await that to be updated also val expectedLeader = clusterView.members.collectFirst { - case m if m.dataCenter == cluster.settings.SelfDataCenter ⇒ m.address + case m if m.dataCenter == cluster.settings.SelfDataCenter => m.address } awaitAssert(clusterView.leader should ===(expectedLeader)) } @@ -335,9 +335,9 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoro val awaiter = system.actorOf(Props(new Actor { def receive = { - case MemberRemoved(m, _) if m.address == toBeRemovedAddress ⇒ + case MemberRemoved(m, _) if m.address == toBeRemovedAddress => exitingLatch.countDown() - case _ ⇒ + case _ => // ignore } }).withDeploy(Deploy.local)) @@ -349,7 +349,7 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoro // verify that the member is EXITING try Await.result(exitingLatch, timeout) catch { - case cause: Exception ⇒ + case cause: Exception => throw new AssertionError(s"Member ${toBeRemovedAddress} was not removed within ${timeout}!", cause) } awaiter ! PoisonPill // you've done your job, now die @@ -420,9 +420,9 @@ trait MultiNodeClusterSpec extends Suite with STMultiNodeSpec with WatchedByCoro private def failureDetectorPuppet(address: Address): Option[FailureDetectorPuppet] = cluster.failureDetector match { - case reg: DefaultFailureDetectorRegistry[Address] ⇒ - reg.failureDetector(address) collect { case p: FailureDetectorPuppet ⇒ p } - case _ ⇒ None + case reg: DefaultFailureDetectorRegistry[Address] => + reg.failureDetector(address) collect { case p: FailureDetectorPuppet => p } + case _ => None } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeChurnSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeChurnSpec.scala index 5e418ff170..fc92909fa4 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeChurnSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeChurnSpec.scala @@ -35,9 +35,9 @@ object NodeChurnMultiJvmSpec extends MultiNodeConfig { class LogListener(testActor: ActorRef) extends Actor { def receive = { - case Info(_, _, msg: String) if msg.startsWith("New maximum payload size for [akka.cluster.GossipEnvelope]") ⇒ + case Info(_, _, msg: String) if msg.startsWith("New maximum payload size for [akka.cluster.GossipEnvelope]") => testActor ! msg - case _ ⇒ + case _ => } } } @@ -78,7 +78,7 @@ abstract class NodeChurnSpec awaitMembersUp(numberOfMembers) within(20.seconds) { awaitAssert { - additionaSystems.foreach { s ⇒ + additionaSystems.foreach { s => val c = Cluster(s) c.state.members.size should be(numberOfMembers) c.state.members.forall(_.status == MemberStatus.Up) shouldBe true @@ -92,7 +92,7 @@ abstract class NodeChurnSpec enterBarrier("removed-" + round) within(3.seconds) { awaitAssert { - additionaSystems.foreach { s ⇒ + additionaSystems.foreach { s => withClue(s"${Cluster(s).selfAddress}:") { Cluster(s).isTerminated should be(true) } @@ -121,16 +121,16 @@ abstract class NodeChurnSpec // This test is configured with log-frame-size-exceeding and the LogListener // will send to the testActor if unexpected increase in message payload size. // It will fail after a while if vector clock entries of removed nodes are not pruned. - for (n ← 1 to rounds) { + for (n <- 1 to rounds) { log.info("round-" + n) val systems = Vector.fill(2)(ActorSystem(system.name, system.settings.config)) - systems.foreach { s ⇒ + systems.foreach { s => muteDeadLetters()(s) Cluster(s).joinSeedNodes(seedNodes) } awaitAllMembersUp(systems) enterBarrier("members-up-" + n) - systems.foreach { node ⇒ + systems.foreach { node => if (n % 2 == 0) Cluster(node).down(Cluster(node).selfAddress) else @@ -138,7 +138,7 @@ abstract class NodeChurnSpec } awaitRemoved(systems, n) enterBarrier("members-removed-" + n) - systems.foreach(s ⇒ TestKit.shutdownActorSystem(s, verifySystemShutdown = true)) + systems.foreach(s => TestKit.shutdownActorSystem(s, verifySystemShutdown = true)) enterBarrier("end-round-" + n) log.info("end of round-" + n) // log listener will send to testActor if payload size exceed configured log-frame-size-exceeding diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeLeavingAndExitingSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeLeavingAndExitingSpec.scala index 09fe555b01..63e068f4eb 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeLeavingAndExitingSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeLeavingAndExitingSpec.scala @@ -43,11 +43,11 @@ abstract class NodeLeavingAndExitingSpec val exitingLatch = TestLatch() cluster.subscribe(system.actorOf(Props(new Actor { def receive = { - case state: CurrentClusterState ⇒ - if (state.members.exists(m ⇒ m.address == secondAddess && m.status == Exiting)) + case state: CurrentClusterState => + if (state.members.exists(m => m.address == secondAddess && m.status == Exiting)) exitingLatch.countDown() - case MemberExited(m) if m.address == secondAddess ⇒ exitingLatch.countDown() - case _: MemberRemoved ⇒ // not tested here + case MemberExited(m) if m.address == secondAddess => exitingLatch.countDown() + case _: MemberRemoved => // not tested here } }).withDeploy(Deploy.local)), classOf[MemberEvent]) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeUpSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeUpSpec.scala index f2acc945d3..605b44b859 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeUpSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/NodeUpSpec.scala @@ -54,9 +54,9 @@ abstract class NodeUpSpec val unexpected = new AtomicReference[SortedSet[Member]](SortedSet.empty) cluster.subscribe(system.actorOf(Props(new Actor { def receive = { - case event: MemberEvent ⇒ + case event: MemberEvent => unexpected.set(unexpected.get + event.member) - case _: CurrentClusterState ⇒ // ignore + case _: CurrentClusterState => // ignore } })), classOf[MemberEvent]) enterBarrier("listener-registered") @@ -67,7 +67,7 @@ abstract class NodeUpSpec enterBarrier("joined-again") // let it run for a while to make sure that nothing bad happens - for (n ← 1 to 20) { + for (n <- 1 to 20) { Thread.sleep(100.millis.dilated.toMillis) unexpected.get should ===(SortedSet.empty) clusterView.members.forall(_.status == MemberStatus.Up) should ===(true) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/QuickRestartSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/QuickRestartSpec.scala index 2ebb05c6bb..49bd44cc1c 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/QuickRestartSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/QuickRestartSpec.scala @@ -55,7 +55,7 @@ abstract class QuickRestartSpec "join and restart" taggedAs LongRunningTest in { val totalNumberOfNodes = roles.size + 1 var restartingSystem: ActorSystem = null // only used on second - for (n ← 1 to rounds) { + for (n <- 1 to rounds) { log.info("round-" + n) runOn(second) { restartingSystem = diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartFirstSeedNodeSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartFirstSeedNodeSpec.scala index 377ac4a90b..ed60bd6fb5 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartFirstSeedNodeSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartFirstSeedNodeSpec.scala @@ -76,7 +76,7 @@ abstract class RestartFirstSeedNodeSpec runOn(seed2, seed3) { system.actorOf(Props(new Actor { def receive = { - case a: Address ⇒ + case a: Address => seedNode1Address = a sender() ! "ok" } @@ -87,7 +87,7 @@ abstract class RestartFirstSeedNodeSpec runOn(seed1) { enterBarrier("seed1-address-receiver-ready") seedNode1Address = Cluster(seed1System).selfAddress - List(seed2, seed3) foreach { r ⇒ + List(seed2, seed3) foreach { r => system.actorSelection(RootActorPath(r) / "user" / "address-receiver") ! seedNode1Address expectMsg(5 seconds, "ok") } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNode2Spec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNode2Spec.scala index bd79fc2acb..6117de961e 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNode2Spec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNode2Spec.scala @@ -77,7 +77,7 @@ abstract class RestartNode2SpecSpec runOn(seed2) { system.actorOf(Props(new Actor { def receive = { - case a: Address ⇒ + case a: Address => seedNode1Address = a sender() ! "ok" } @@ -88,7 +88,7 @@ abstract class RestartNode2SpecSpec runOn(seed1) { enterBarrier("seed1-address-receiver-ready") seedNode1Address = Cluster(seed1System).selfAddress - List(seed2) foreach { r ⇒ + List(seed2) foreach { r => system.actorSelection(RootActorPath(r) / "user" / "address-receiver") ! seedNode1Address expectMsg(5.seconds, "ok") } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNode3Spec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNode3Spec.scala index 18874534d8..00e12a59e1 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNode3Spec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNode3Spec.scala @@ -79,7 +79,7 @@ abstract class RestartNode3Spec runOn(first, third) { system.actorOf(Props(new Actor { def receive = { - case a: UniqueAddress ⇒ + case a: UniqueAddress => secondUniqueAddress = a sender() ! "ok" } @@ -90,7 +90,7 @@ abstract class RestartNode3Spec runOn(second) { enterBarrier("second-address-receiver-ready") secondUniqueAddress = Cluster(secondSystem).selfUniqueAddress - List(first, third) foreach { r ⇒ + List(first, third) foreach { r => system.actorSelection(RootActorPath(r) / "user" / "address-receiver") ! secondUniqueAddress expectMsg(5.seconds, "ok") } @@ -116,7 +116,7 @@ abstract class RestartNode3Spec Cluster(secondSystem).joinSeedNodes(seedNodes) awaitAssert(Cluster(secondSystem).readView.members.size should ===(3)) awaitAssert(Cluster(secondSystem).readView.members.collectFirst { - case m if m.address == Cluster(secondSystem).selfAddress ⇒ m.status + case m if m.address == Cluster(secondSystem).selfAddress => m.status } should ===(Some(Joining))) } enterBarrier("second-joined") @@ -139,7 +139,7 @@ abstract class RestartNode3Spec runOn(first, third) { awaitAssert { Cluster(system).readView.members.size should ===(3) - Cluster(system).readView.members.exists { m ⇒ + Cluster(system).readView.members.exists { m => m.address == secondUniqueAddress.address && m.uniqueAddress.longUid != secondUniqueAddress.longUid } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNodeSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNodeSpec.scala index 29b3d9dc84..140ca2685e 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNodeSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartNodeSpec.scala @@ -47,10 +47,10 @@ object RestartNodeMultiJvmSpec extends MultiNodeConfig { context.actorSelection(RootActorPath(a) / "user" / "address-receiver") ! Identify(None) def receive = { - case ActorIdentity(None, Some(ref)) ⇒ + case ActorIdentity(None, Some(ref)) => context.watch(ref) replyTo ! Done - case t: Terminated ⇒ + case t: Terminated => } } } @@ -96,7 +96,7 @@ abstract class RestartNodeSpec runOn(first, third) { system.actorOf(Props(new Actor { def receive = { - case a: UniqueAddress ⇒ + case a: UniqueAddress => secondUniqueAddress = a sender() ! "ok" } @@ -107,7 +107,7 @@ abstract class RestartNodeSpec runOn(second) { enterBarrier("second-address-receiver-ready") secondUniqueAddress = Cluster(secondSystem).selfUniqueAddress - List(first, third) foreach { r ⇒ + List(first, third) foreach { r => system.actorSelection(RootActorPath(r) / "user" / "address-receiver") ! secondUniqueAddress expectMsg(5.seconds, "ok") } @@ -145,7 +145,7 @@ abstract class RestartNodeSpec runOn(first, third) { awaitAssert { Cluster(system).readView.members.size should ===(3) - Cluster(system).readView.members.exists { m ⇒ + Cluster(system).readView.members.exists { m => m.address == secondUniqueAddress.address && m.uniqueAddress.longUid != secondUniqueAddress.longUid } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/SharedMediaDriverSupport.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/SharedMediaDriverSupport.scala index 87d9b65833..4bf526b9c2 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/SharedMediaDriverSupport.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/SharedMediaDriverSupport.scala @@ -46,7 +46,7 @@ object SharedMediaDriverSupport { println(msg) } }) catch { - case NonFatal(e) ⇒ + case NonFatal(e) => println(e.getMessage) false } @@ -77,7 +77,7 @@ object SharedMediaDriverSupport { } } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => println(s"Failed to start media driver in [${aeronDir}]: ${e.getMessage}") } } @@ -87,7 +87,7 @@ object SharedMediaDriverSupport { def stopMediaDriver(config: MultiNodeConfig): Unit = { val maybeDriver = mediaDriver.getAndSet(None) - maybeDriver.foreach { driver ⇒ + maybeDriver.foreach { driver => val arterySettings = loadArterySettings(config) // let other nodes shutdown first @@ -100,7 +100,7 @@ object SharedMediaDriverSupport { IoUtil.delete(new File(driver.aeronDirectoryName), false) } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => println( s"Couldn't delete Aeron embedded media driver files in [${driver.aeronDirectoryName}] " + s"due to [${e.getMessage}]") diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/SplitBrainSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/SplitBrainSpec.scala index 4e2fab3d30..f47067f8fe 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/SplitBrainSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/SplitBrainSpec.scala @@ -71,21 +71,21 @@ abstract class SplitBrainSpec(multiNodeConfig: SplitBrainMultiNodeConfig) runOn(first) { // split the cluster in two parts (first, second) / (third, fourth, fifth) - for (role1 ← side1; role2 ← side2) { + for (role1 <- side1; role2 <- side2) { testConductor.blackhole(role1, role2, Direction.Both).await } } enterBarrier("after-split") runOn(side1: _*) { - for (role ← side2) markNodeAsUnavailable(role) + for (role <- side2) markNodeAsUnavailable(role) // auto-down awaitMembersUp(side1.size, side2.toSet map address) assertLeader(side1: _*) } runOn(side2: _*) { - for (role ← side1) markNodeAsUnavailable(role) + for (role <- side1) markNodeAsUnavailable(role) // auto-down awaitMembersUp(side2.size, side1.toSet map address) assertLeader(side2: _*) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/StreamRefSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/StreamRefSpec.scala index d6d2d3770f..183815fbc0 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/StreamRefSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/StreamRefSpec.scala @@ -59,22 +59,22 @@ object StreamRefSpec extends MultiNodeConfig { implicit val mat = ActorMaterializer()(context) def receive = { - case RequestLogs(streamId) ⇒ + case RequestLogs(streamId) => // materialize the SourceRef: val (done: Future[Done], ref: Future[SourceRef[String]]) = - Source.fromIterator(() ⇒ Iterator.from(1)) - .map(n ⇒ s"elem-$n") + Source.fromIterator(() => Iterator.from(1)) + .map(n => s"elem-$n") .watchTermination()(Keep.right) .toMat(StreamRefs.sourceRef())(Keep.both) - .mapMaterializedValue { m ⇒ + .mapMaterializedValue { m => streamLifecycleProbe ! s"started-$streamId" m } .run() done.onComplete { - case Success(_) ⇒ streamLifecycleProbe ! s"completed-$streamId" - case Failure(_) ⇒ streamLifecycleProbe ! s"failed-$streamId" + case Success(_) => streamLifecycleProbe ! s"completed-$streamId" + case Failure(_) => streamLifecycleProbe ! s"failed-$streamId" } // wrap the SourceRef in some domain message, such that the sender knows what source it is @@ -100,22 +100,22 @@ object StreamRefSpec extends MultiNodeConfig { implicit val mat = ActorMaterializer()(context) def receive = { - case PrepareUpload(nodeId) ⇒ + case PrepareUpload(nodeId) => // materialize the SinkRef (the remote is like a source of data for us): val (ref: Future[SinkRef[String]], done: Future[Done]) = StreamRefs.sinkRef[String]() .throttle(1, 1.second) .toMat(Sink.ignore)(Keep.both) - .mapMaterializedValue { m ⇒ + .mapMaterializedValue { m => streamLifecycleProbe ! s"started-$nodeId" m } .run() done.onComplete { - case Success(_) ⇒ streamLifecycleProbe ! s"completed-$nodeId" - case Failure(_) ⇒ streamLifecycleProbe ! s"failed-$nodeId" + case Success(_) => streamLifecycleProbe ! s"completed-$nodeId" + case Failure(_) => streamLifecycleProbe ! s"failed-$nodeId" } // wrap the SinkRef in some domain message, such that the sender knows what source it is @@ -215,14 +215,14 @@ abstract class StreamRefSpec extends MultiNodeSpec(StreamRefSpec) ref ! PrepareUpload("system-42-tmp") val ready = expectMsgType[MeasurementsSinkReady] - Source.fromIterator(() ⇒ Iterator.from(1)) - .map(n ⇒ s"elem-$n") + Source.fromIterator(() => Iterator.from(1)) + .map(n => s"elem-$n") .watchTermination()(Keep.right) .to(ready.sinkRef) .run() .onComplete { - case Success(_) ⇒ streamLifecycle1.ref ! s"completed-system-42-tmp" - case Failure(_) ⇒ streamLifecycle1.ref ! s"failed-system-42-tmp" + case Success(_) => streamLifecycle1.ref ! s"completed-system-42-tmp" + case Failure(_) => streamLifecycle1.ref ! s"failed-system-42-tmp" } } runOn(third) { diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/StressSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/StressSpec.scala index d9a57e978c..c492a3d6ce 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/StressSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/StressSpec.scala @@ -65,11 +65,11 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { val totalNumberOfNodes = System.getProperty("MultiJvm.akka.cluster.Stress.nrOfNodes") match { - case null ⇒ 13 - case value ⇒ value.toInt requiring (_ >= 10, "nrOfNodes should be >= 10") + case null => 13 + case value => value.toInt requiring (_ >= 10, "nrOfNodes should be >= 10") } - for (n ← 1 to totalNumberOfNodes) role("node-" + n) + for (n <- 1 to totalNumberOfNodes) role("node-" + n) // Note that this test uses default configuration, // not MultiNodeClusterSpec.clusterConfig @@ -257,12 +257,12 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { } def receive = { - case PhiResult(from, phiValues) ⇒ phiValuesObservedByNode += from → phiValues - case StatsResult(from, stats) ⇒ clusterStatsObservedByNode += from → stats - case ReportTick ⇒ + case PhiResult(from, phiValues) => phiValuesObservedByNode += from -> phiValues + case StatsResult(from, stats) => clusterStatsObservedByNode += from -> stats + case ReportTick => if (infolog) log.info(s"[${title}] in progress\n\n${formatPhi}\n\n${formatStats}") - case r: ClusterResult ⇒ + case r: ClusterResult => results :+= r if (results.size == expectedResults) { val aggregated = AggregatedClusterResult(title, maxDuration, totalGossipStats) @@ -271,8 +271,8 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { reportTo foreach { _ ! aggregated } context stop self } - case _: CurrentClusterState ⇒ - case ReportTo(ref) ⇒ reportTo = ref + case _: CurrentClusterState => + case ReportTo(ref) => reportTo = ref } def maxDuration = results.map(_.duration).max @@ -280,8 +280,8 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { def totalGossipStats = results.foldLeft(GossipStats()) { _ :+ _.clusterStats } def format(opt: Option[Double]) = opt match { - case None ⇒ "N/A" - case Some(x) ⇒ x.form + case None => "N/A" + case Some(x) => x.form } def formatPhi: String = { @@ -289,8 +289,8 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { else { val lines = for { - (monitor, phiValues) ← phiValuesObservedByNode - phi ← phiValues + (monitor, phiValues) <- phiValuesObservedByNode + phi <- phiValues } yield formatPhiLine(monitor, phi.address, phi) lines.mkString(formatPhiHeader + "\n", "\n", "") @@ -308,7 +308,7 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { import stats.vclockStats._ s"ClusterStats($receivedGossipCount, $mergeCount, $sameCount, $newerCount, $olderCount, $versionSize, $seenLatest)" } - (clusterStatsObservedByNode map { case (monitor, stats) ⇒ s"${monitor}\t${f(stats)}" }). + (clusterStatsObservedByNode map { case (monitor, stats) => s"${monitor}\t${f(stats)}" }). mkString("ClusterStats(gossip, merge, same, newer, older, vclockSize, seenLatest)\n", "\n", "") } @@ -323,7 +323,7 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { var history = Vector.empty[AggregatedClusterResult] def receive = { - case result: AggregatedClusterResult ⇒ + case result: AggregatedClusterResult => history :+= result log.info("Cluster result history\n" + formatHistory) } @@ -345,16 +345,16 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { class PhiObserver extends Actor with ActorLogging { val cluster = Cluster(context.system) var reportTo: Option[ActorRef] = None - val emptyPhiByNode: Map[Address, PhiValue] = Map.empty[Address, PhiValue].withDefault(address ⇒ PhiValue(address, 0, 0, 0.0)) + val emptyPhiByNode: Map[Address, PhiValue] = Map.empty[Address, PhiValue].withDefault(address => PhiValue(address, 0, 0, 0.0)) var phiByNode = emptyPhiByNode var nodes = Set.empty[Address] def phi(address: Address): Double = cluster.failureDetector match { - case reg: DefaultFailureDetectorRegistry[Address] ⇒ reg.failureDetector(address) match { - case Some(fd: PhiAccrualFailureDetector) ⇒ fd.phi - case _ ⇒ 0.0 + case reg: DefaultFailureDetectorRegistry[Address] => reg.failureDetector(address) match { + case Some(fd: PhiAccrualFailureDetector) => fd.phi + case _ => 0.0 } - case _ ⇒ 0.0 + case _ => 0.0 } import context.dispatcher @@ -370,30 +370,30 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { } def receive = { - case PhiTick ⇒ - nodes foreach { node ⇒ + case PhiTick => + nodes foreach { node => val previous = phiByNode(node) val φ = phi(node) if (φ > 0 || cluster.failureDetector.isMonitoring(node)) { val aboveOne = if (!φ.isInfinite && φ > 1.0) 1 else 0 - phiByNode += node → PhiValue(node, previous.countAboveOne + aboveOne, previous.count + 1, + phiByNode += node -> PhiValue(node, previous.countAboveOne + aboveOne, previous.count + 1, math.max(previous.max, φ)) } } val phiSet = immutable.SortedSet.empty[PhiValue] ++ phiByNode.values reportTo foreach { _ ! PhiResult(cluster.selfAddress, phiSet) } - case state: CurrentClusterState ⇒ nodes = state.members.map(_.address) - case memberEvent: MemberEvent ⇒ nodes += memberEvent.member.address - case ReportTo(ref) ⇒ + case state: CurrentClusterState => nodes = state.members.map(_.address) + case memberEvent: MemberEvent => nodes += memberEvent.member.address + case ReportTo(ref) => reportTo foreach context.unwatch reportTo = ref reportTo foreach context.watch - case Terminated(ref) ⇒ + case Terminated(ref) => reportTo match { - case Some(`ref`) ⇒ reportTo = None - case _ ⇒ + case Some(`ref`) => reportTo = None + case _ => } - case Reset ⇒ + case Reset => phiByNode = emptyPhiByNode nodes = Set.empty[Address] cluster.unsubscribe(self) @@ -411,25 +411,25 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { override def postStop(): Unit = cluster.unsubscribe(self) def receive = { - case CurrentInternalStats(gossipStats, vclockStats) ⇒ + case CurrentInternalStats(gossipStats, vclockStats) => val diff = startStats match { - case None ⇒ { startStats = Some(gossipStats); gossipStats } - case Some(start) ⇒ gossipStats :- start + case None => { startStats = Some(gossipStats); gossipStats } + case Some(start) => gossipStats :- start } val res = StatsResult(cluster.selfAddress, CurrentInternalStats(diff, vclockStats)) reportTo foreach { _ ! res } - case ReportTo(ref) ⇒ + case ReportTo(ref) => reportTo foreach context.unwatch reportTo = ref reportTo foreach context.watch - case Terminated(ref) ⇒ + case Terminated(ref) => reportTo match { - case Some(`ref`) ⇒ reportTo = None - case _ ⇒ + case Some(`ref`) => reportTo = None + case _ => } - case Reset ⇒ + case Reset => startStats = None - case _: CurrentClusterState ⇒ // not interesting here + case _: CurrentClusterState => // not interesting here } } @@ -468,34 +468,34 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { } def receive = { - case Begin ⇒ + case Begin => startTime = System.nanoTime self ! SendBatch context.become(working) - case RetryTick ⇒ + case RetryTick => } def working: Receive = { - case Ack(id) ⇒ + case Ack(id) => outstanding -= id ackCounter += 1 if (outstanding.size == settings.workBatchSize / 2) if (batchInterval == Duration.Zero) self ! SendBatch else context.system.scheduler.scheduleOnce(batchInterval, self, SendBatch) - case SendBatch ⇒ sendJobs() - case RetryTick ⇒ resend() - case End ⇒ + case SendBatch => sendJobs() + case RetryTick => resend() + case End => done(sender()) context.become(ending(sender())) } def ending(replyTo: ActorRef): Receive = { - case Ack(id) ⇒ + case Ack(id) => outstanding -= id ackCounter += 1 done(replyTo) - case SendBatch ⇒ - case RetryTick ⇒ resend() + case SendBatch => + case RetryTick => resend() } def done(replyTo: ActorRef): Unit = @@ -506,7 +506,7 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { } def sendJobs(): Unit = { - 0 until settings.workBatchSize foreach { _ ⇒ + 0 until settings.workBatchSize foreach { _ => send(createJob()) } } @@ -518,14 +518,14 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { } def resend(): Unit = { - outstanding.values foreach { jobState ⇒ + outstanding.values foreach { jobState => if (jobState.deadline.isOverdue) send(jobState.job) } } def send(job: Job): Unit = { - outstanding += job.id → JobState(Deadline.now + retryTimeout, job) + outstanding += job.id -> JobState(Deadline.now + retryTimeout, job) sendCounter += 1 workers ! job } @@ -536,8 +536,8 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { */ class Worker extends Actor with ActorLogging { def receive = { - case SimpleJob(id, payload) ⇒ sender() ! Ack(id) - case TreeJob(id, payload, idx, levels, width) ⇒ + case SimpleJob(id, payload) => sender() ! Ack(id) + case TreeJob(id, payload, idx, levels, width) => // create the actors when first TreeJob message is received val totalActors = ((width * math.pow(width, levels) - 1) / (width - 1)).toInt log.debug( @@ -549,8 +549,8 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { } def treeWorker(tree: ActorRef): Receive = { - case SimpleJob(id, payload) ⇒ sender() ! Ack(id) - case TreeJob(id, payload, idx, _, _) ⇒ + case SimpleJob(id, payload) => sender() ! Ack(id) + case TreeJob(id, payload, idx, _, _) => tree forward ((idx, SimpleJob(id, payload))) } } @@ -559,16 +559,16 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { require(level >= 1) def createChild(): Actor = if (level == 1) new Leaf else new TreeNode(level - 1, width) val indexedChildren = - 0 until width map { i ⇒ context.actorOf(Props(createChild()).withDeploy(Deploy.local), name = i.toString) } toVector + 0 until width map { i => context.actorOf(Props(createChild()).withDeploy(Deploy.local), name = i.toString) } toVector def receive = { - case (idx: Int, job: SimpleJob) if idx < width ⇒ indexedChildren(idx) forward ((idx, job)) + case (idx: Int, job: SimpleJob) if idx < width => indexedChildren(idx) forward ((idx, job)) } } class Leaf extends Actor { def receive = { - case (_: Int, job: SimpleJob) ⇒ sender() ! Ack(job.id) + case (_: Int, job: SimpleJob) => sender() ! Ack(job.id) } } @@ -588,16 +588,16 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 1 minute) { - case _: Exception ⇒ + case _: Exception => restartCount += 1 Restart } def receive = { - case props: Props ⇒ context.actorOf(props) - case e: Exception ⇒ context.children foreach { _ ! e } - case GetChildrenCount ⇒ sender() ! ChildrenCount(context.children.size, restartCount) - case Reset ⇒ + case props: Props => context.actorOf(props) + case e: Exception => context.children foreach { _ ! e } + case GetChildrenCount => sender() ! ChildrenCount(context.children.size, restartCount) + case Reset => require( context.children.isEmpty, s"ResetChildrenCount not allowed when children exists, [${context.children.size}]") @@ -610,7 +610,7 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { */ class RemoteChild extends Actor { def receive = { - case e: Exception ⇒ throw e + case e: Exception => throw e } } @@ -784,17 +784,17 @@ abstract class StressSpec def awaitClusterResult(): Unit = { runOn(roles.head) { clusterResultAggregator match { - case Some(r) ⇒ + case Some(r) => watch(r) - expectMsgPF() { case Terminated(a) if a.path == r.path ⇒ true } - case None ⇒ // ok, already terminated + expectMsgPF() { case Terminated(a) if a.path == r.path => true } + case None => // ok, already terminated } } enterBarrier("cluster-result-done-" + step) } def joinOneByOne(numberOfNodes: Int): Unit = { - 0 until numberOfNodes foreach { _ ⇒ + 0 until numberOfNodes foreach { _ => joinOne() nbrUsedRoles += 1 step += 1 @@ -842,7 +842,7 @@ abstract class StressSpec } def removeOneByOne(numberOfNodes: Int, shutdown: Boolean): Unit = { - 0 until numberOfNodes foreach { _ ⇒ + 0 until numberOfNodes foreach { _ => removeOne(shutdown) nbrUsedRoles -= 1 step += 1 @@ -884,7 +884,7 @@ abstract class StressSpec runOn(roles.head) { val expectedPath = RootActorPath(removeAddress) / "user" / "watchee" expectMsgPF() { - case Terminated(a) if a.path == expectedPath ⇒ true + case Terminated(a) if a.path == expectedPath => true } } enterBarrier("watch-verified-" + step) @@ -905,7 +905,7 @@ abstract class StressSpec runOn(currentRoles: _*) { reportResult { runOn(roles.head) { - if (shutdown) removeRoles.foreach { r ⇒ + if (shutdown) removeRoles.foreach { r => if (infolog) log.info("Shutting down [{}]", address(r)) testConductor.exit(r, 0).await @@ -919,7 +919,7 @@ abstract class StressSpec enterBarrier("remove-several-" + step) } - def reportResult[T](thunk: ⇒ T): T = { + def reportResult[T](thunk: => T): T = { val startTime = System.nanoTime val startStats = clusterView.latestStats.gossipStats @@ -952,7 +952,7 @@ abstract class StressSpec reportResult { val nextAS = if (activeRoles contains myself) { - previousAS foreach { as ⇒ TestKit.shutdownActorSystem(as) } + previousAS foreach { as => TestKit.shutdownActorSystem(as) } val sys = ActorSystem(system.name, system.settings.config) muteLog(sys) Cluster(sys).joinSeedNodes(seedNodes.toIndexedSeq map address) @@ -981,7 +981,7 @@ abstract class StressSpec } } - loop(1, None, Set.empty) foreach { as ⇒ TestKit.shutdownActorSystem(as) } + loop(1, None, Set.empty) foreach { as => TestKit.shutdownActorSystem(as) } within(loopDuration) { runOn(usedRoles: _*) { awaitMembersUp(nbrUsedRoles, timeout = remainingOrDefault) @@ -1051,19 +1051,19 @@ abstract class StressSpec within(duration + 10.seconds) { val rounds = (duration.toMillis / oneIteration.toMillis).max(1).toInt val supervisor = system.actorOf(Props[Supervisor], "supervisor") - for (count ← 0 until rounds) { + for (count <- 0 until rounds) { createResultAggregator(title, expectedResults = nbrUsedRoles, includeInHistory = false) val (masterRoles, otherRoles) = roles.take(nbrUsedRoles).splitAt(3) runOn(masterRoles: _*) { reportResult { - roles.take(nbrUsedRoles) foreach { r ⇒ + roles.take(nbrUsedRoles) foreach { r => supervisor ! Props[RemoteChild].withDeploy(Deploy(scope = RemoteScope(address(r)))) } supervisor ! GetChildrenCount expectMsgType[ChildrenCount] should ===(ChildrenCount(nbrUsedRoles, 0)) - 1 to 5 foreach { _ ⇒ supervisor ! new RuntimeException("Simulated exception") } + 1 to 5 foreach { _ => supervisor ! new RuntimeException("Simulated exception") } awaitAssert { supervisor ! GetChildrenCount val c = expectMsgType[ChildrenCount] @@ -1177,13 +1177,13 @@ abstract class StressSpec if (exerciseActors) { runOn(roles.take(3): _*) { master match { - case Some(m) ⇒ + case Some(m) => m.tell(End, testActor) val workResult = awaitWorkResult(m) workResult.retryCount should ===(0) workResult.sendCount should be > (0L) workResult.ackCount should be > (0L) - case None ⇒ fail("master not running") + case None => fail("master not running") } } } @@ -1286,12 +1286,12 @@ abstract class StressSpec if (exerciseActors) { runOn(roles.take(3): _*) { master match { - case Some(m) ⇒ + case Some(m) => m.tell(End, testActor) val workResult = awaitWorkResult(m) workResult.sendCount should be > (0L) workResult.ackCount should be > (0L) - case None ⇒ fail("master not running") + case None => fail("master not running") } } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/SunnyWeatherSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/SunnyWeatherSpec.scala index 38096be14d..62a87c9510 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/SunnyWeatherSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/SunnyWeatherSpec.scala @@ -64,14 +64,14 @@ abstract class SunnyWeatherSpec extends MultiNodeSpec(SunnyWeatherMultiJvmSpec) val unexpected = new AtomicReference[SortedSet[Member]](SortedSet.empty) cluster.subscribe(system.actorOf(Props(new Actor { def receive = { - case event: MemberEvent ⇒ + case event: MemberEvent => // we don't expected any changes to the cluster unexpected.set(unexpected.get + event.member) - case _: CurrentClusterState ⇒ // ignore + case _: CurrentClusterState => // ignore } })), classOf[MemberEvent]) - for (n ← 1 to 30) { + for (n <- 1 to 30) { enterBarrier("period-" + n) unexpected.get should ===(SortedSet.empty) awaitMembersUp(roles.size) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/SurviveNetworkInstabilitySpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/SurviveNetworkInstabilitySpec.scala index 4c5e85d5e0..bdb051f96b 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/SurviveNetworkInstabilitySpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/SurviveNetworkInstabilitySpec.scala @@ -45,7 +45,7 @@ object SurviveNetworkInstabilityMultiJvmSpec extends MultiNodeConfig { class Echo extends Actor { def receive = { - case m ⇒ sender ! m + case m => sender ! m } } @@ -56,12 +56,12 @@ object SurviveNetworkInstabilityMultiJvmSpec extends MultiNodeConfig { var targets = Set.empty[ActorRef] def receive = { - case Targets(refs) ⇒ + case Targets(refs) => targets = refs sender() ! TargetsRegistered - case "boom" ⇒ + case "boom" => targets.foreach(context.watch) - case Terminated(_) ⇒ + case Terminated(_) => } } @@ -103,7 +103,7 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("reachable-ok") runOn(alive: _*) { - for (to ← alive) { + for (to <- alive) { val sel = system.actorSelection(node(to) / "user" / "echo") val msg = s"ping-$to" val p = TestProbe() @@ -157,7 +157,7 @@ abstract class SurviveNetworkInstabilitySpec "heal after one isolated node" taggedAs LongRunningTest in within(45.seconds) { val others = Vector(second, third, fourth, fifth) runOn(first) { - for (other ← others) { + for (other <- others) { testConductor.blackhole(first, other, Direction.Both).await } } @@ -171,7 +171,7 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("unreachable-3") runOn(first) { - for (other ← others) { + for (other <- others) { testConductor.passThrough(first, other, Direction.Both).await } } @@ -184,7 +184,7 @@ abstract class SurviveNetworkInstabilitySpec val island2 = Vector(third, fourth, fifth) runOn(first) { // split the cluster in two parts (first, second) / (third, fourth, fifth) - for (role1 ← island1; role2 ← island2) { + for (role1 <- island1; role2 <- island2) { testConductor.blackhole(role1, role2, Direction.Both).await } } @@ -200,7 +200,7 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("unreachable-4") runOn(first) { - for (role1 ← island1; role2 ← island2) { + for (role1 <- island1; role2 <- island2) { testConductor.passThrough(role1, role2, Direction.Both).await } } @@ -212,7 +212,7 @@ abstract class SurviveNetworkInstabilitySpec val joining = Vector(sixth, seventh) val others = Vector(second, third, fourth, fifth) runOn(first) { - for (role1 ← (joining :+ first); role2 ← others) { + for (role1 <- (joining :+ first); role2 <- others) { testConductor.blackhole(role1, role2, Direction.Both).await } } @@ -239,7 +239,7 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("more-unreachable-5") runOn(first) { - for (role1 ← (joining :+ first); role2 ← others) { + for (role1 <- (joining :+ first); role2 <- others) { testConductor.passThrough(role1, role2, Direction.Both).await } } @@ -275,7 +275,7 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("targets-registered") runOn(first) { - for (role ← others) + for (role <- others) testConductor.blackhole(role, second, Direction.Both).await } enterBarrier("blackhole-6") @@ -295,8 +295,8 @@ abstract class SurviveNetworkInstabilitySpec // not be downed, see issue #25632 Thread.sleep(2000) val secondUniqueAddress = cluster.state.members.find(_.address == address(second)) match { - case None ⇒ fail("Unexpected removal of quarantined node") - case Some(m) ⇒ + case None => fail("Unexpected removal of quarantined node") + case Some(m) => m.status should ===(MemberStatus.Up) // not Down m.uniqueAddress } @@ -327,7 +327,7 @@ abstract class SurviveNetworkInstabilitySpec val side1AfterJoin = side1 :+ eighth val side2 = Vector(fifth, sixth, seventh) runOn(first) { - for (role1 ← side1AfterJoin; role2 ← side2) { + for (role1 <- side1AfterJoin; role2 <- side2) { testConductor.blackhole(role1, role2, Direction.Both).await } } @@ -342,7 +342,7 @@ abstract class SurviveNetworkInstabilitySpec cluster.join(third) } runOn(fourth) { - for (role2 ← side2) { + for (role2 <- side2) { cluster.down(role2) } } @@ -356,13 +356,13 @@ abstract class SurviveNetworkInstabilitySpec // repeat the downing in case it was not successful, which may // happen if the removal was reverted due to gossip merge, see issue #18767 runOn(fourth) { - for (role2 ← side2) { + for (role2 <- side2) { cluster.down(role2) } } clusterView.members.map(_.address) should ===(expected) - clusterView.members.collectFirst { case m if m.address == address(eighth) ⇒ m.status } should ===( + clusterView.members.collectFirst { case m if m.address == address(eighth) => m.status } should ===( Some(MemberStatus.Up)) } } @@ -370,7 +370,7 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("side2-removed") runOn(first) { - for (role1 ← side1AfterJoin; role2 ← side2) { + for (role1 <- side1AfterJoin; role2 <- side2) { testConductor.passThrough(role1, role2, Direction.Both).await } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/TransitionSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/TransitionSpec.scala index b5ad510d1c..8ade73b93f 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/TransitionSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/TransitionSpec.scala @@ -47,7 +47,7 @@ abstract class TransitionSpec def memberStatus(address: Address): MemberStatus = { val statusOption = (clusterView.members union clusterView.unreachableMembers).collectFirst { - case m if m.address == address ⇒ m.status + case m if m.address == address => m.status } statusOption.getOrElse(Removed) } @@ -102,7 +102,7 @@ abstract class TransitionSpec awaitCond((Set(fromRole, toRole) diff seenLatestGossip).isEmpty) enterBarrier("after-gossip-" + gossipBarrierCounter) } - runOn(roles.filterNot(r ⇒ r == fromRole || r == toRole): _*) { + runOn(roles.filterNot(r => r == fromRole || r == toRole): _*) { enterBarrier("before-gossip-" + gossipBarrierCounter) enterBarrier("after-gossip-" + gossipBarrierCounter) } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/UnreachableNodeJoinsAgainSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/UnreachableNodeJoinsAgainSpec.scala index e45ef94565..e1caf377c2 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/UnreachableNodeJoinsAgainSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/UnreachableNodeJoinsAgainSpec.scala @@ -77,7 +77,7 @@ abstract class UnreachableNodeJoinsAgainSpec runOn(first) { // pull network for victim node from all nodes - allBut(victim).foreach { roleName ⇒ + allBut(victim).foreach { roleName => testConductor.blackhole(victim, roleName, Direction.Both).await } } @@ -146,7 +146,7 @@ abstract class UnreachableNodeJoinsAgainSpec runOn(first) { // put the network back in - allBut(victim).foreach { roleName ⇒ + allBut(victim).foreach { roleName => testConductor.passThrough(victim, roleName, Direction.Both).await } } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterConsistentHashingGroupSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterConsistentHashingGroupSpec.scala index 710a5d1e7d..0a808318d0 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterConsistentHashingGroupSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterConsistentHashingGroupSpec.scala @@ -22,8 +22,8 @@ object ClusterConsistentHashingGroupMultiJvmSpec extends MultiNodeConfig { class Destination extends Actor { var receivedMessages = Set.empty[Any] def receive = { - case Get ⇒ sender() ! Collected(receivedMessages) - case m ⇒ receivedMessages += m + case Get => sender() ! Collected(receivedMessages) + case m => receivedMessages += m } } @@ -48,8 +48,8 @@ abstract class ClusterConsistentHashingGroupSpec extends MultiNodeSpec(ClusterCo * Fills in self address for local ActorRef */ private def fullAddress(actorRef: ActorRef): Address = actorRef.path.address match { - case Address(_, _, None, None) ⇒ cluster.selfAddress - case a ⇒ a + case Address(_, _, None, None) => cluster.selfAddress + case a => a } def currentRoutees(router: ActorRef) = @@ -64,7 +64,7 @@ abstract class ClusterConsistentHashingGroupSpec extends MultiNodeSpec(ClusterCo "send to same destinations from different nodes" taggedAs LongRunningTest in { def hashMapping: ConsistentHashMapping = { - case s: String ⇒ s + case s: String => s } val paths = List("/user/dest") val router = system.actorOf( @@ -75,7 +75,7 @@ abstract class ClusterConsistentHashingGroupSpec extends MultiNodeSpec(ClusterCo // it may take some time until router receives cluster member events awaitAssert { currentRoutees(router).size should ===(3) } val keys = List("A", "B", "C", "D", "E", "F", "G") - for (_ ← 1 to 10; k ← keys) { router ! k } + for (_ <- 1 to 10; k <- keys) { router ! k } enterBarrier("messages-sent") router ! Broadcast(Get) val a = expectMsgType[Collected].messages diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterConsistentHashingRouterSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterConsistentHashingRouterSpec.scala index 8486d99b90..cacd639264 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterConsistentHashingRouterSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterConsistentHashingRouterSpec.scala @@ -27,7 +27,7 @@ object ClusterConsistentHashingRouterMultiJvmSpec extends MultiNodeConfig { class Echo extends Actor { def receive = { - case _ ⇒ sender() ! self + case _ => sender() ! self } } @@ -74,8 +74,8 @@ abstract class ClusterConsistentHashingRouterSpec extends MultiNodeSpec(ClusterC * Fills in self address for local ActorRef */ private def fullAddress(actorRef: ActorRef): Address = actorRef.path.address match { - case Address(_, _, None, None) ⇒ cluster.selfAddress - case a ⇒ a + case Address(_, _, None, None) => cluster.selfAddress + case a => a } "A cluster router with a consistent hashing pool" must { @@ -89,7 +89,7 @@ abstract class ClusterConsistentHashingRouterSpec extends MultiNodeSpec(ClusterC // it may take some time until router receives cluster member events awaitAssert { currentRoutees(router1).size should ===(4) } val routees = currentRoutees(router1) - routees.map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) }.toSet should ===(Set(address(first), address(second))) + routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(Set(address(first), address(second))) } enterBarrier("after-2") } @@ -112,7 +112,7 @@ abstract class ClusterConsistentHashingRouterSpec extends MultiNodeSpec(ClusterC // it may take some time until router receives cluster member events awaitAssert { currentRoutees(router1).size should ===(6) } val routees = currentRoutees(router1) - routees.map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) }.toSet should ===(roles.map(address).toSet) + routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet) } enterBarrier("after-3") @@ -129,7 +129,7 @@ abstract class ClusterConsistentHashingRouterSpec extends MultiNodeSpec(ClusterC // it may take some time until router receives cluster member events awaitAssert { currentRoutees(router2).size should ===(6) } val routees = currentRoutees(router2) - routees.map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) }.toSet should ===(roles.map(address).toSet) + routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet) } enterBarrier("after-4") @@ -138,7 +138,7 @@ abstract class ClusterConsistentHashingRouterSpec extends MultiNodeSpec(ClusterC "handle combination of configured router and programatically defined hashMapping" in { runOn(first) { def hashMapping: ConsistentHashMapping = { - case s: String ⇒ s + case s: String => s } val router3 = system.actorOf(ConsistentHashingPool(nrOfInstances = 0, hashMapping = hashMapping).props(Props[Echo]), "router3") @@ -152,7 +152,7 @@ abstract class ClusterConsistentHashingRouterSpec extends MultiNodeSpec(ClusterC "handle combination of configured router and programatically defined hashMapping and ClusterRouterConfig" in { runOn(first) { def hashMapping: ConsistentHashMapping = { - case s: String ⇒ s + case s: String => s } val router4 = system.actorOf( @@ -172,7 +172,7 @@ abstract class ClusterConsistentHashingRouterSpec extends MultiNodeSpec(ClusterC // it may take some time until router receives cluster member events awaitAssert { currentRoutees(router).size should ===(6) } val routees = currentRoutees(router) - routees.map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) }.toSet should ===(roles.map(address).toSet) + routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet) router ! "a" val destinationA = expectMsgType[ActorRef] diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterRoundRobinSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterRoundRobinSpec.scala index 775bd1dde2..86e16ad228 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterRoundRobinSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/ClusterRoundRobinSpec.scala @@ -33,7 +33,7 @@ object ClusterRoundRobinMultiJvmSpec extends MultiNodeConfig { def this() = this(PoolRoutee) def receive = { - case "hit" ⇒ sender() ! Reply(routeeType, self) + case "hit" => sender() ! Reply(routeeType, self) } } @@ -124,11 +124,11 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult lazy val router5 = system.actorOf(RoundRobinPool(nrOfInstances = 0).props(Props[SomeActor]), "router5") def receiveReplies(routeeType: RouteeType, expectedReplies: Int): Map[Address, Int] = { - val zero = Map.empty[Address, Int] ++ roles.map(address(_) → 0) + val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0) (receiveWhile(5 seconds, messages = expectedReplies) { - case Reply(`routeeType`, ref) ⇒ fullAddress(ref) + case Reply(`routeeType`, ref) => fullAddress(ref) }).foldLeft(zero) { - case (replyMap, address) ⇒ replyMap + (address → (replyMap(address) + 1)) + case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) } } @@ -136,8 +136,8 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult * Fills in self address for local ActorRef */ private def fullAddress(actorRef: ActorRef): Address = actorRef.path.address match { - case Address(_, _, None, None) ⇒ cluster.selfAddress - case a ⇒ a + case Address(_, _, None, None) => cluster.selfAddress + case a => a } def currentRoutees(router: ActorRef) = @@ -158,7 +158,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult awaitAssert(currentRoutees(router1).size should ===(4)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router1 ! "hit" } @@ -189,7 +189,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult } val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router4 ! "hit" } @@ -215,7 +215,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult awaitAssert(currentRoutees(router1).size should ===(8)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router1 ! "hit" } @@ -237,7 +237,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult awaitAssert(currentRoutees(router4).size should ===(8)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router4 ! "hit" } @@ -257,7 +257,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult awaitAssert(currentRoutees(router3).size should ===(3)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router3 ! "hit" } @@ -279,7 +279,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult awaitAssert(currentRoutees(router5).size should ===(2)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router5 ! "hit" } @@ -304,7 +304,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult awaitAssert(currentRoutees(router2).size should ===(3)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router2 ! "hit" } @@ -312,7 +312,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult // note that router2 has totalInstances = 3, maxInstancesPerNode = 1 val routees = currentRoutees(router2) - val routeeAddresses = routees map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) } + val routeeAddresses = routees map { case ActorRefRoutee(ref) => fullAddress(ref) } routeeAddresses.size should ===(3) replies.values.sum should ===(iterationCount) @@ -326,7 +326,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult // myservice is already running def routees = currentRoutees(router4) - def routeeAddresses = (routees map { case ActorSelectionRoutee(sel) ⇒ fullAddress(sel.anchor) }).toSet + def routeeAddresses = (routees map { case ActorSelectionRoutee(sel) => fullAddress(sel.anchor) }).toSet runOn(first) { // 4 nodes, 2 routees on each node @@ -351,13 +351,13 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult runOn(first) { def routees = currentRoutees(router2) - def routeeAddresses = (routees map { case ActorRefRoutee(ref) ⇒ fullAddress(ref) }).toSet + def routeeAddresses = (routees map { case ActorRefRoutee(ref) => fullAddress(ref) }).toSet - routees foreach { case ActorRefRoutee(ref) ⇒ watch(ref) } + routees foreach { case ActorRefRoutee(ref) => watch(ref) } val notUsedAddress = ((roles map address).toSet diff routeeAddresses).head val downAddress = routeeAddresses.find(_ != address(first)).get val downRouteeRef = routees.collectFirst { - case ActorRefRoutee(ref) if ref.path.address == downAddress ⇒ ref + case ActorRefRoutee(ref) if ref.path.address == downAddress => ref }.get cluster.down(downAddress) @@ -368,7 +368,7 @@ abstract class ClusterRoundRobinSpec extends MultiNodeSpec(ClusterRoundRobinMult } val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router2 ! "hit" } diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/UseRoleIgnoredSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/UseRoleIgnoredSpec.scala index b70583fc55..119a8375d5 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/UseRoleIgnoredSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/routing/UseRoleIgnoredSpec.scala @@ -30,7 +30,7 @@ object UseRoleIgnoredMultiJvmSpec extends MultiNodeConfig { def this() = this(PoolRoutee) def receive = { - case msg ⇒ + case msg => log.info("msg = {}", msg) sender() ! Reply(routeeType, self) } @@ -64,11 +64,11 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp import akka.cluster.routing.UseRoleIgnoredMultiJvmSpec._ def receiveReplies(routeeType: RouteeType, expectedReplies: Int): Map[Address, Int] = { - val zero = Map.empty[Address, Int] ++ roles.map(address(_) → 0) + val zero = Map.empty[Address, Int] ++ roles.map(address(_) -> 0) (receiveWhile(5 seconds, messages = expectedReplies) { - case Reply(`routeeType`, ref) ⇒ fullAddress(ref) + case Reply(`routeeType`, ref) => fullAddress(ref) }).foldLeft(zero) { - case (replyMap, address) ⇒ replyMap + (address → (replyMap(address) + 1)) + case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) } } @@ -76,8 +76,8 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp * Fills in self address for local ActorRef */ private def fullAddress(actorRef: ActorRef): Address = actorRef.path.address match { - case Address(_, _, None, None) ⇒ cluster.selfAddress - case a ⇒ a + case Address(_, _, None, None) => cluster.selfAddress + case a => a } def currentRoutees(router: ActorRef) = @@ -112,7 +112,7 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp awaitAssert(currentRoutees(router).size should ===(4)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router ! s"hit-$i" } @@ -142,7 +142,7 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp awaitAssert(currentRoutees(router).size should ===(4)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router ! s"hit-$i" } @@ -172,7 +172,7 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp awaitAssert(currentRoutees(router).size should ===(4)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router ! s"hit-$i" } @@ -202,7 +202,7 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp awaitAssert(currentRoutees(router).size should ===(4)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router ! s"hit-$i" } @@ -232,7 +232,7 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp awaitAssert(currentRoutees(router).size should ===(2)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router ! s"hit-$i" } @@ -262,7 +262,7 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp awaitAssert(currentRoutees(router).size should ===(2)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router ! s"hit-$i" } @@ -292,7 +292,7 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp awaitAssert(currentRoutees(router).size should ===(6)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router ! s"hit-$i" } @@ -322,7 +322,7 @@ abstract class UseRoleIgnoredSpec extends MultiNodeSpec(UseRoleIgnoredMultiJvmSp awaitAssert(currentRoutees(router).size should ===(6)) val iterationCount = 10 - for (i ← 0 until iterationCount) { + for (i <- 0 until iterationCount) { router ! s"hit-$i" } diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala index 5c2542c2fa..5940c861af 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ClusterDeployerSpec.scala @@ -39,7 +39,7 @@ object ClusterDeployerSpec { """, ConfigParseOptions.defaults) class RecipeActor extends Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } } } diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterDomainEventSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterDomainEventSpec.scala index c6f58b5c63..5fc9c2c185 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ClusterDomainEventSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ClusterDomainEventSpec.scala @@ -37,7 +37,7 @@ class ClusterDomainEventSpec extends WordSpec with Matchers { val selfDummyAddress = UniqueAddress(Address("akka.tcp", "sys", "selfDummy", 2552), 17L) private[cluster] def converge(gossip: Gossip): (Gossip, Set[UniqueAddress]) = - gossip.members.foldLeft((gossip, Set.empty[UniqueAddress])) { case ((gs, as), m) ⇒ (gs.seen(m.uniqueAddress), as + m.uniqueAddress) } + gossip.members.foldLeft((gossip, Set.empty[UniqueAddress])) { case ((gs, as), m) => (gs.seen(m.uniqueAddress), as + m.uniqueAddress) } private def state(g: Gossip): MembershipState = state(g, selfDummyAddress) @@ -105,7 +105,7 @@ class ClusterDomainEventSpec extends WordSpec with Matchers { .unreachable(dc2BMemberUp.uniqueAddress, dc2AMemberDown.uniqueAddress) val g2 = Gossip(members = SortedSet(aUp, bUp, dc2AMemberDown, dc2BMemberUp, dc3AMemberUp, dc3BMemberUp), overview = GossipOverview(reachability = reachability2)) - Set(aUp, bUp, dc2AMemberUp, dc2BMemberUp, dc3AMemberUp, dc3BMemberUp).foreach { member ⇒ + Set(aUp, bUp, dc2AMemberUp, dc2BMemberUp, dc3AMemberUp, dc3BMemberUp).foreach { member => val otherDc = if (member.dataCenter == ClusterSettings.DefaultDataCenter) Seq("dc2") else Seq() diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterHeartbeatSenderStateSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterHeartbeatSenderStateSpec.scala index 2ed551aebd..31be6735be 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ClusterHeartbeatSenderStateSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ClusterHeartbeatSenderStateSpec.scala @@ -26,8 +26,8 @@ object ClusterHeartbeatSenderStateSpec { def markNodeAsAvailable(): Unit = status = Up override def isAvailable: Boolean = status match { - case Unknown | Up ⇒ true - case Down ⇒ false + case Unknown | Up => true + case Down => false } override def isMonitoring: Boolean = status != Unknown @@ -51,7 +51,7 @@ class ClusterHeartbeatSenderStateSpec extends WordSpec with Matchers { private def emptyState(selfUniqueAddress: UniqueAddress) = ClusterHeartbeatSenderState( ring = HeartbeatNodeRing(selfUniqueAddress, Set(selfUniqueAddress), Set.empty, monitoredByNrOfMembers = 3), oldReceiversNowUnreachable = Set.empty[UniqueAddress], - failureDetector = new DefaultFailureDetectorRegistry[Address](() ⇒ new FailureDetectorStub)) + failureDetector = new DefaultFailureDetectorRegistry[Address](() => new FailureDetectorStub)) private def fd(state: ClusterHeartbeatSenderState, node: UniqueAddress): FailureDetectorStub = state.failureDetector.asInstanceOf[DefaultFailureDetectorRegistry[Address]].failureDetector(node.address). @@ -142,7 +142,7 @@ class ClusterHeartbeatSenderStateSpec extends WordSpec with Matchers { "behave correctly for random operations" in { val rnd = ThreadLocalRandom.current - val nodes = (1 to rnd.nextInt(10, 200)).map(n ⇒ + val nodes = (1 to rnd.nextInt(10, 200)).map(n => UniqueAddress(Address("akka.tcp", "sys", "n" + n, 2552), n.toLong)).toVector def rndNode() = nodes(rnd.nextInt(0, nodes.size)) val selfUniqueAddress = rndNode() @@ -151,12 +151,12 @@ class ClusterHeartbeatSenderStateSpec extends WordSpec with Matchers { val Remove = 1 val Unreachable = 2 val HeartbeatRsp = 3 - for (i ← 1 to 100000) { + for (i <- 1 to 100000) { val operation = rnd.nextInt(Add, HeartbeatRsp + 1) val node = rndNode() try { operation match { - case Add ⇒ + case Add => if (node != selfUniqueAddress && !state.ring.nodes.contains(node)) { val oldUnreachable = state.oldReceiversNowUnreachable state = state.addMember(node) @@ -166,7 +166,7 @@ class ClusterHeartbeatSenderStateSpec extends WordSpec with Matchers { state.failureDetector.isAvailable(node.address) should ===(true) } - case Remove ⇒ + case Remove => if (node != selfUniqueAddress && state.ring.nodes.contains(node)) { val oldUnreachable = state.oldReceiversNowUnreachable state = state.removeMember(node) @@ -181,7 +181,7 @@ class ClusterHeartbeatSenderStateSpec extends WordSpec with Matchers { state.activeReceivers should not contain (node) } - case Unreachable ⇒ + case Unreachable => if (node != selfUniqueAddress && state.activeReceivers(node)) { state.failureDetector.heartbeat(node.address) // make sure the fd is created fd(state, node).markNodeAsUnavailable() @@ -190,7 +190,7 @@ class ClusterHeartbeatSenderStateSpec extends WordSpec with Matchers { state = state.unreachableMember(node) } - case HeartbeatRsp ⇒ + case HeartbeatRsp => if (node != selfUniqueAddress && state.ring.nodes.contains(node)) { val oldUnreachable = state.oldReceiversNowUnreachable val oldReceivers = state.activeReceivers @@ -213,7 +213,7 @@ class ClusterHeartbeatSenderStateSpec extends WordSpec with Matchers { } } catch { - case e: Throwable ⇒ + case e: Throwable => println(s"Failure context: i=$i, node=$node, op=$operation, " + s"oldReceiversNowUnreachable=${state.oldReceiversNowUnreachable}, " + s"ringReceivers=${state.ring.myReceivers}, ringNodes=${state.ring.nodes}") diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala index 99a24137d3..e0b66178d0 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ClusterSpec.scala @@ -164,8 +164,8 @@ class ClusterSpec extends AkkaSpec(ClusterSpec.config) with ImplicitSender { probe.expectMsgType[MemberLeft] // MemberExited might not be published before MemberRemoved val removed = probe.fishForMessage() { - case _: MemberExited ⇒ false - case _: MemberRemoved ⇒ true + case _: MemberExited => false + case _: MemberRemoved => true }.asInstanceOf[MemberRemoved] removed.previousStatus should ===(MemberStatus.Exiting) } finally { @@ -194,8 +194,8 @@ class ClusterSpec extends AkkaSpec(ClusterSpec.config) with ImplicitSender { probe.expectMsgType[MemberLeft] // MemberExited might not be published before MemberRemoved val removed = probe.fishForMessage() { - case _: MemberExited ⇒ false - case _: MemberRemoved ⇒ true + case _: MemberExited => false + case _: MemberRemoved => true }.asInstanceOf[MemberRemoved] removed.previousStatus should ===(MemberStatus.Exiting) @@ -225,8 +225,8 @@ class ClusterSpec extends AkkaSpec(ClusterSpec.config) with ImplicitSender { probe.expectMsgType[MemberLeft] // MemberExited might not be published before MemberRemoved val removed = probe.fishForMessage() { - case _: MemberExited ⇒ false - case _: MemberRemoved ⇒ true + case _: MemberExited => false + case _: MemberRemoved => true }.asInstanceOf[MemberRemoved] removed.previousStatus should ===(MemberStatus.Exiting) } finally { @@ -252,8 +252,8 @@ class ClusterSpec extends AkkaSpec(ClusterSpec.config) with ImplicitSender { probe.expectMsgType[MemberLeft] // MemberExited might not be published before MemberRemoved val removed = probe.fishForMessage() { - case _: MemberExited ⇒ false - case _: MemberRemoved ⇒ true + case _: MemberExited => false + case _: MemberRemoved => true }.asInstanceOf[MemberRemoved] removed.previousStatus should ===(MemberStatus.Exiting) Await.result(sys2.whenTerminated, 10.seconds) @@ -291,7 +291,7 @@ class ClusterSpec extends AkkaSpec(ClusterSpec.config) with ImplicitSender { } "register multiple cluster JMX MBeans with akka.cluster.jmx.multi-mbeans-in-same-jvm = on" in { - def getConfig = (port: Int) ⇒ ConfigFactory.parseString( + def getConfig = (port: Int) => ConfigFactory.parseString( s""" akka.cluster.jmx.multi-mbeans-in-same-jvm = on akka.remote.netty.tcp.port = ${port} diff --git a/akka-cluster/src/test/scala/akka/cluster/ClusterTestKit.scala b/akka-cluster/src/test/scala/akka/cluster/ClusterTestKit.scala index 128e074000..586bfd3fa3 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ClusterTestKit.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ClusterTestKit.scala @@ -89,7 +89,7 @@ trait ClusterTestKit extends TestKitBase { def joinCluster(actorSystem: ActorSystem): Unit = { require(isRegistered(actorSystem), "Unknown actor system") - val addresses = actorSystems.map(s ⇒ Cluster(s).selfAddress) + val addresses = actorSystems.map(s => Cluster(s).selfAddress) val joiningNodeCluster = Cluster(actorSystem) joiningNodeCluster.joinSeedNodes(addresses) @@ -99,7 +99,7 @@ trait ClusterTestKit extends TestKitBase { actorSystems.contains(actorSystem) /** Shuts down all registered [[ActorSystem]]s */ - def shutdownAll(): Unit = actorSystems.foreach(sys ⇒ shutdown(sys)) + def shutdownAll(): Unit = actorSystems.foreach(sys => shutdown(sys)) /** * Force the passed [[ActorSystem]] to quit the cluster and shutdown. @@ -194,10 +194,10 @@ abstract class RollingUpgradeClusterSpec(config: Config) extends AkkaSpec(config val util = new ClusterTestUtil(system.name) - val config = (version: Config) ⇒ if (enforced) version else unenforced(version) + val config = (version: Config) => if (enforced) version else unenforced(version) try { - val nodes = for (_ ← 0 until clusterSize) yield { + val nodes = for (_ <- 0 until clusterSize) yield { val system = util.newActorSystem(config(baseConfig)) util.joinCluster(system) system @@ -206,7 +206,7 @@ abstract class RollingUpgradeClusterSpec(config: Config) extends AkkaSpec(config val rolling = Random.shuffle(nodes) - for (restarting ← rolling.tail) { + for (restarting <- rolling.tail) { val restarted = util.quitAndRestart(restarting, config(upgradeConfig)) util.joinCluster(restarted) awaitCond(if (shouldRejoin) util.isMemberUp(restarted) else util.isTerminated(restarted), timeout) diff --git a/akka-cluster/src/test/scala/akka/cluster/FailureDetectorPuppet.scala b/akka-cluster/src/test/scala/akka/cluster/FailureDetectorPuppet.scala index 38941aa5f1..6f936cb032 100644 --- a/akka-cluster/src/test/scala/akka/cluster/FailureDetectorPuppet.scala +++ b/akka-cluster/src/test/scala/akka/cluster/FailureDetectorPuppet.scala @@ -26,8 +26,8 @@ class FailureDetectorPuppet(config: Config, ev: EventStream) extends FailureDete def markNodeAsAvailable(): Unit = status.set(Up) override def isAvailable: Boolean = status.get match { - case Unknown | Up ⇒ true - case Down ⇒ false + case Unknown | Up => true + case Down => false } override def isMonitoring: Boolean = status.get != Unknown diff --git a/akka-cluster/src/test/scala/akka/cluster/GossipSpec.scala b/akka-cluster/src/test/scala/akka/cluster/GossipSpec.scala index ac2f364eed..4fa6f8de1d 100644 --- a/akka-cluster/src/test/scala/akka/cluster/GossipSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/GossipSpec.scala @@ -42,7 +42,7 @@ class GossipSpec extends WordSpec with Matchers { "A Gossip" must { "have correct test setup" in { - List(a1, a2, b1, b2, c1, c2, c3, d1, e1, e2, e3).foreach(m ⇒ + List(a1, a2, b1, b2, c1, c2, c3, d1, e1, e2, e3).foreach(m => m.dataCenter should ===(DefaultDataCenter)) } @@ -375,7 +375,7 @@ class GossipSpec extends WordSpec with Matchers { gdc2.tombstones.keys should contain(dc2d1.uniqueAddress) gdc2.members should not contain (dc2d1) - gdc2.overview.reachability.records.filter(r ⇒ r.subject == dc2d1.uniqueAddress || r.observer == dc2d1.uniqueAddress) should be(empty) + gdc2.overview.reachability.records.filter(r => r.subject == dc2d1.uniqueAddress || r.observer == dc2d1.uniqueAddress) should be(empty) gdc2.overview.reachability.versions.keys should not contain (dc2d1.uniqueAddress) // when we merge the two, it should not be reintroduced @@ -384,7 +384,7 @@ class GossipSpec extends WordSpec with Matchers { merged1.tombstones.keys should contain(dc2d1.uniqueAddress) merged1.members should not contain (dc2d1) - merged1.overview.reachability.records.filter(r ⇒ r.subject == dc2d1.uniqueAddress || r.observer == dc2d1.uniqueAddress) should be(empty) + merged1.overview.reachability.records.filter(r => r.subject == dc2d1.uniqueAddress || r.observer == dc2d1.uniqueAddress) should be(empty) merged1.overview.reachability.versions.keys should not contain (dc2d1.uniqueAddress) merged1.version.versions.keys should not contain (VectorClock.Node(vclockName(dc2d1.uniqueAddress))) } @@ -414,7 +414,7 @@ class GossipSpec extends WordSpec with Matchers { merged1.tombstones.keys should contain(dc2d1.uniqueAddress) merged1.tombstones.keys should not contain (dc2d3.uniqueAddress) - merged1.overview.reachability.records.filter(r ⇒ r.subject == dc2d1.uniqueAddress || r.observer == dc2d1.uniqueAddress) should be(empty) + merged1.overview.reachability.records.filter(r => r.subject == dc2d1.uniqueAddress || r.observer == dc2d1.uniqueAddress) should be(empty) merged1.overview.reachability.versions.keys should not contain (dc2d1.uniqueAddress) merged1.version.versions.keys should not contain (VectorClock.Node(vclockName(dc2d1.uniqueAddress))) } diff --git a/akka-cluster/src/test/scala/akka/cluster/HeartbeatNodeRingPerfSpec.scala b/akka-cluster/src/test/scala/akka/cluster/HeartbeatNodeRingPerfSpec.scala index 76a1b1389e..7be8da5274 100644 --- a/akka-cluster/src/test/scala/akka/cluster/HeartbeatNodeRingPerfSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/HeartbeatNodeRingPerfSpec.scala @@ -15,15 +15,15 @@ class HeartbeatNodeRingPerfSpec extends WordSpec with Matchers { val iterations = sys.props.get("akka.cluster.HeartbeatNodeRingPerfSpec.iterations").getOrElse("1000").toInt def createHeartbeatNodeRingOfSize(size: Int): HeartbeatNodeRing = { - val nodes = (1 to size).map(n ⇒ UniqueAddress(Address("akka.tcp", "sys", "node-" + n, 2552), n.toLong)) + val nodes = (1 to size).map(n => UniqueAddress(Address("akka.tcp", "sys", "node-" + n, 2552), n.toLong)) val selfAddress = nodes(size / 2) HeartbeatNodeRing(selfAddress, nodes.toSet, Set.empty, 5) } val heartbeatNodeRing = createHeartbeatNodeRingOfSize(nodesSize) - private def checkThunkForRing(ring: HeartbeatNodeRing, thunk: HeartbeatNodeRing ⇒ Unit, times: Int): Unit = - for (i ← 1 to times) thunk(ring) + private def checkThunkForRing(ring: HeartbeatNodeRing, thunk: HeartbeatNodeRing => Unit, times: Int): Unit = + for (i <- 1 to times) thunk(ring) private def myReceivers(ring: HeartbeatNodeRing): Unit = { val r = HeartbeatNodeRing(ring.selfAddress, ring.nodes, Set.empty, ring.monitoredByNrOfMembers) diff --git a/akka-cluster/src/test/scala/akka/cluster/HeartbeatNodeRingSpec.scala b/akka-cluster/src/test/scala/akka/cluster/HeartbeatNodeRingSpec.scala index c0608c892c..d999321d2a 100644 --- a/akka-cluster/src/test/scala/akka/cluster/HeartbeatNodeRingSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/HeartbeatNodeRingSpec.scala @@ -25,7 +25,7 @@ class HeartbeatNodeRingSpec extends WordSpec with Matchers { val ring = HeartbeatNodeRing(cc, nodes, Set.empty, 3) ring.myReceivers should ===(ring.receivers(cc)) - nodes foreach { n ⇒ + nodes foreach { n => val receivers = ring.receivers(n) receivers.size should ===(3) receivers should not contain (n) diff --git a/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatCheckerRollingUpdateSpec.scala b/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatCheckerRollingUpdateSpec.scala index b615091729..db34b2ec17 100644 --- a/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatCheckerRollingUpdateSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatCheckerRollingUpdateSpec.scala @@ -5,7 +5,7 @@ package akka.cluster import scala.concurrent.duration._ -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } import akka.testkit.LongRunningTest import com.typesafe.config.{ Config, ConfigFactory } diff --git a/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatCheckerSpec.scala b/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatCheckerSpec.scala index 5d1c6bd02f..5c1e2d729a 100644 --- a/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatCheckerSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatCheckerSpec.scala @@ -8,7 +8,7 @@ import akka.testkit.{ AkkaSpec, LongRunningTest } import com.typesafe.config.{ Config, ConfigFactory } import scala.concurrent.duration._ -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } object JoinConfigCompatCheckerSpec { diff --git a/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatPreDefinedChecksSpec.scala b/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatPreDefinedChecksSpec.scala index 78abd4383e..512b6775c2 100644 --- a/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatPreDefinedChecksSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/JoinConfigCompatPreDefinedChecksSpec.scala @@ -7,7 +7,7 @@ package akka.cluster import com.typesafe.config.{ Config, ConfigFactory } import org.scalatest.{ Matchers, WordSpec } -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } class JoinConfigCompatPreDefinedChecksSpec extends WordSpec with Matchers { diff --git a/akka-cluster/src/test/scala/akka/cluster/ReachabilityPerfSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ReachabilityPerfSpec.scala index 8373e7108b..e8b74e7cc7 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ReachabilityPerfSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ReachabilityPerfSpec.scala @@ -19,7 +19,7 @@ class ReachabilityPerfSpec extends WordSpec with Matchers { private def createReachabilityOfSize(base: Reachability, size: Int): Reachability = (1 to size).foldLeft(base) { - case (r, i) ⇒ + case (r, i) => val observer = UniqueAddress(address.copy(host = Some("node-" + i)), i.toLong) val j = if (i == size) 1 else i + 1 val subject = UniqueAddress(address.copy(host = Some("node-" + j)), j.toLong) @@ -30,8 +30,8 @@ class ReachabilityPerfSpec extends WordSpec with Matchers { val observers = base.versions.keySet.take(count) val subjects = Stream.continually(base.versions.keySet).flatten.iterator observers.foldLeft(base) { - case (r, o) ⇒ - (1 to 5).foldLeft(r) { case (r, _) ⇒ r.unreachable(o, subjects.next()) } + case (r, o) => + (1 to 5).foldLeft(r) { case (r, _) => r.unreachable(o, subjects.next()) } } } @@ -40,14 +40,14 @@ class ReachabilityPerfSpec extends WordSpec with Matchers { val reachability3 = addUnreachable(reachability1, nodesSize / 2) val allowed = reachability1.versions.keySet - private def checkThunkFor(r1: Reachability, r2: Reachability, thunk: (Reachability, Reachability) ⇒ Unit, times: Int): Unit = { - for (i ← 1 to times) { + private def checkThunkFor(r1: Reachability, r2: Reachability, thunk: (Reachability, Reachability) => Unit, times: Int): Unit = { + for (i <- 1 to times) { thunk(Reachability(r1.records, r1.versions), Reachability(r2.records, r2.versions)) } } - private def checkThunkFor(r1: Reachability, thunk: Reachability ⇒ Unit, times: Int): Unit = { - for (i ← 1 to times) { + private def checkThunkFor(r1: Reachability, thunk: Reachability => Unit, times: Int): Unit = { + for (i <- 1 to times) { thunk(Reachability(r1.records, r1.versions)) } } @@ -77,7 +77,7 @@ class ReachabilityPerfSpec extends WordSpec with Matchers { } private def recordsFrom(r1: Reachability): Unit = { - r1.allObservers.foreach { o ⇒ + r1.allObservers.foreach { o => r1.recordsFrom(o) should not be be(null) } } diff --git a/akka-cluster/src/test/scala/akka/cluster/ReachabilitySpec.scala b/akka-cluster/src/test/scala/akka/cluster/ReachabilitySpec.scala index 32bed8689f..31ab77e4b3 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ReachabilitySpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ReachabilitySpec.scala @@ -98,7 +98,7 @@ class ReachabilitySpec extends WordSpec with Matchers { Reachability.Record(nodeC, nodeB, Unreachable, 2), Reachability.Record(nodeA, nodeD, Unreachable, 3), Reachability.Record(nodeD, nodeB, Terminated, 4)) - val versions = Map(nodeA → 3L, nodeC → 3L, nodeD → 4L) + val versions = Map(nodeA -> 3L, nodeC -> 3L, nodeD -> 4L) val r = Reachability(records, versions) r.status(nodeA) should ===(Reachable) r.status(nodeB) should ===(Terminated) @@ -136,9 +136,9 @@ class ReachabilitySpec extends WordSpec with Matchers { r.allUnreachableFrom(nodeD) should ===(Set(nodeA, nodeB)) r.observersGroupedByUnreachable should ===(Map( - nodeA → Set(nodeB, nodeC, nodeD), - nodeB → Set(nodeD), - nodeE → Set(nodeA))) + nodeA -> Set(nodeB, nodeC, nodeD), + nodeB -> Set(nodeD), + nodeE -> Set(nodeA))) } "merge by picking latest version of each record" in { @@ -199,11 +199,11 @@ class ReachabilitySpec extends WordSpec with Matchers { } "merge versions correctly" in { - val r1 = Reachability(Vector.empty, Map(nodeA → 3L, nodeB → 5L, nodeC → 7L)) - val r2 = Reachability(Vector.empty, Map(nodeA → 6L, nodeB → 2L, nodeD → 1L)) + val r1 = Reachability(Vector.empty, Map(nodeA -> 3L, nodeB -> 5L, nodeC -> 7L)) + val r2 = Reachability(Vector.empty, Map(nodeA -> 6L, nodeB -> 2L, nodeD -> 1L)) val merged = r1.merge(Set(nodeA, nodeB, nodeC, nodeD, nodeE), r2) - val expected = Map(nodeA → 6L, nodeB → 5L, nodeC → 7L, nodeD → 1L) + val expected = Map(nodeA -> 6L, nodeB -> 5L, nodeC -> 7L, nodeD -> 1L) merged.versions should ===(expected) val merged2 = r2.merge(Set(nodeA, nodeB, nodeC, nodeD, nodeE), r1) @@ -241,7 +241,7 @@ class ReachabilitySpec extends WordSpec with Matchers { .unreachable(nodeB, nodeA) .unreachable(nodeB, nodeC) - val filtered1 = r.filterRecords(record ⇒ record.observer != nodeC) + val filtered1 = r.filterRecords(record => record.observer != nodeC) filtered1.isReachable(nodeB) should ===(true) filtered1.isReachable(nodeA) should ===(false) filtered1.allObservers should ===(Set(nodeB)) diff --git a/akka-cluster/src/test/scala/akka/cluster/ShutdownAfterJoinSeedNodesSpec.scala b/akka-cluster/src/test/scala/akka/cluster/ShutdownAfterJoinSeedNodesSpec.scala index b6c07c4734..f32f8ab2ca 100644 --- a/akka-cluster/src/test/scala/akka/cluster/ShutdownAfterJoinSeedNodesSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/ShutdownAfterJoinSeedNodesSpec.scala @@ -42,7 +42,7 @@ class ShutdownAfterJoinSeedNodesSpec extends AkkaSpec(ShutdownAfterJoinSeedNodes "Joining seed nodes" must { "be aborted after shutdown-after-unsuccessful-join-seed-nodes" taggedAs LongRunningTest in { - val seedNodes: immutable.IndexedSeq[Address] = Vector(seed1, seed2).map(s ⇒ Cluster(s).selfAddress) + val seedNodes: immutable.IndexedSeq[Address] = Vector(seed1, seed2).map(s => Cluster(s).selfAddress) shutdown(seed1) // crash so that others will not be able to join Cluster(seed2).joinSeedNodes(seedNodes) diff --git a/akka-cluster/src/test/scala/akka/cluster/StartupWithOneThreadSpec.scala b/akka-cluster/src/test/scala/akka/cluster/StartupWithOneThreadSpec.scala index c4acfb9738..232f467858 100644 --- a/akka-cluster/src/test/scala/akka/cluster/StartupWithOneThreadSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/StartupWithOneThreadSpec.scala @@ -33,7 +33,7 @@ object StartupWithOneThreadSpec { val cluster = Cluster(context.system) log.debug(s"started ${cluster.selfAddress} ${Thread.currentThread().getName}") def receive = { - case msg ⇒ sender() ! msg + case msg => sender() ! msg } }) } diff --git a/akka-cluster/src/test/scala/akka/cluster/VectorClockPerfSpec.scala b/akka-cluster/src/test/scala/akka/cluster/VectorClockPerfSpec.scala index 3aabc8c7c7..e63d7a5a58 100644 --- a/akka-cluster/src/test/scala/akka/cluster/VectorClockPerfSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/VectorClockPerfSpec.scala @@ -13,14 +13,14 @@ object VectorClockPerfSpec { def createVectorClockOfSize(size: Int): (VectorClock, SortedSet[Node]) = (1 to size).foldLeft((VectorClock(), SortedSet.empty[Node])) { - case ((vc, nodes), i) ⇒ + case ((vc, nodes), i) => val node = Node(i.toString) (vc :+ node, nodes + node) } def copyVectorClock(vc: VectorClock): VectorClock = { val versions = vc.versions.foldLeft(TreeMap.empty[Node, Long]) { - case (versions, (n, t)) ⇒ versions.updated(Node.fromHash(n), t) + case (versions, (n, t)) => versions.updated(Node.fromHash(n), t) } vc.copy(versions = versions) } @@ -46,10 +46,10 @@ class VectorClockPerfSpec extends WordSpec with Matchers { val vcAfterMiddle = vcBaseMiddle :+ firstNode val vcConcurrentMiddle = vcBaseMiddle :+ middleNode - def checkThunkFor(vc1: VectorClock, vc2: VectorClock, thunk: (VectorClock, VectorClock) ⇒ Unit, times: Int): Unit = { + def checkThunkFor(vc1: VectorClock, vc2: VectorClock, thunk: (VectorClock, VectorClock) => Unit, times: Int): Unit = { val vcc1 = copyVectorClock(vc1) val vcc2 = copyVectorClock(vc2) - for (i ← 1 to times) { + for (i <- 1 to times) { thunk(vcc1, vcc2) } } diff --git a/akka-cluster/src/test/scala/akka/cluster/protobuf/ClusterMessageSerializerSpec.scala b/akka-cluster/src/test/scala/akka/cluster/protobuf/ClusterMessageSerializerSpec.scala index 3097a71fd6..cfcb74e4fe 100644 --- a/akka-cluster/src/test/scala/akka/cluster/protobuf/ClusterMessageSerializerSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/protobuf/ClusterMessageSerializerSpec.scala @@ -27,11 +27,11 @@ class ClusterMessageSerializerSpec extends AkkaSpec( def checkSerialization(obj: AnyRef): Unit = { (obj, roundtrip(obj)) match { - case (env: GossipEnvelope, env2: GossipEnvelope) ⇒ + case (env: GossipEnvelope, env2: GossipEnvelope) => env2.from should ===(env.from) env2.to should ===(env.to) env2.gossip should ===(env.gossip) - case (_, ref) ⇒ + case (_, ref) => ref should ===(obj) } @@ -140,7 +140,7 @@ class ClusterMessageSerializerSpec extends AkkaSpec( val result = serializer.fromBinary(oldBytes, classOf[ClusterRouterPool]) result match { - case pool: ClusterRouterPool ⇒ + case pool: ClusterRouterPool => pool.settings.totalInstances should ===(123) pool.settings.maxInstancesPerNode should ===(345) pool.settings.allowLocalRoutees should ===(true) diff --git a/akka-cluster/src/test/scala/akka/cluster/routing/ClusterRouterSupervisorSpec.scala b/akka-cluster/src/test/scala/akka/cluster/routing/ClusterRouterSupervisorSpec.scala index 46d871253e..38986d668d 100644 --- a/akka-cluster/src/test/scala/akka/cluster/routing/ClusterRouterSupervisorSpec.scala +++ b/akka-cluster/src/test/scala/akka/cluster/routing/ClusterRouterSupervisorSpec.scala @@ -14,7 +14,7 @@ object ClusterRouterSupervisorSpec { class KillableActor(testActor: ActorRef) extends Actor { def receive = { - case "go away" ⇒ + case "go away" => throw new IllegalArgumentException("Goodbye then!") } @@ -36,7 +36,7 @@ class ClusterRouterSupervisorSpec extends AkkaSpec(""" val router = system.actorOf( ClusterRouterPool(RoundRobinPool(nrOfInstances = 1, supervisorStrategy = OneForOneStrategy(loggingEnabled = false) { - case _ ⇒ + case _ => testActor ! "supervised" SupervisorStrategy.Stop }), ClusterRouterPoolSettings( diff --git a/akka-contrib/src/main/scala/akka/contrib/circuitbreaker/CircuitBreakerProxy.scala b/akka-contrib/src/main/scala/akka/contrib/circuitbreaker/CircuitBreakerProxy.scala index 93deed29e1..ac7ed6ef56 100644 --- a/akka-contrib/src/main/scala/akka/contrib/circuitbreaker/CircuitBreakerProxy.scala +++ b/akka-contrib/src/main/scala/akka/contrib/circuitbreaker/CircuitBreakerProxy.scala @@ -47,8 +47,8 @@ object CircuitBreakerProxy { callTimeout: Timeout, resetTimeout: Timeout, circuitEventListener: Option[ActorRef], - failureDetector: Any ⇒ Boolean, - failureMap: CircuitOpenFailure ⇒ Any) = + failureDetector: Any => Boolean, + failureMap: CircuitOpenFailure => Any) = Props(new CircuitBreakerProxy(target, maxFailures, callTimeout, resetTimeout, circuitEventListener, failureDetector, failureMap)) sealed trait CircuitBreakerCommand @@ -74,15 +74,15 @@ object CircuitBreakerProxy { final case class CircuitBreakerPropsBuilder( maxFailures: Int, callTimeout: Timeout, resetTimeout: Timeout, circuitEventListener: Option[ActorRef] = None, - failureDetector: Any ⇒ Boolean = { _ ⇒ false }, - openCircuitFailureConverter: CircuitOpenFailure ⇒ Any = identity) { + failureDetector: Any => Boolean = { _ => false }, + openCircuitFailureConverter: CircuitOpenFailure => Any = identity) { def withMaxFailures(value: Int) = copy(maxFailures = value) def withCallTimeout(value: Timeout) = copy(callTimeout = value) def withResetTimeout(value: Timeout) = copy(resetTimeout = value) def withCircuitEventListener(value: Option[ActorRef]) = copy(circuitEventListener = value) - def withFailureDetector(value: Any ⇒ Boolean) = copy(failureDetector = value) - def withOpenCircuitFailureConverter(value: CircuitOpenFailure ⇒ Any) = copy(openCircuitFailureConverter = value) + def withFailureDetector(value: Any => Boolean) = copy(failureDetector = value) + def withOpenCircuitFailureConverter(value: CircuitOpenFailure => Any) = copy(openCircuitFailureConverter = value) /** * Creates the props for a [[akka.contrib.circuitbreaker.CircuitBreakerProxy]] proxying the given target @@ -109,31 +109,31 @@ final class CircuitBreakerProxy( callTimeout: Timeout, resetTimeout: Timeout, circuitEventListener: Option[ActorRef], - failureDetector: Any ⇒ Boolean, - failureMap: CircuitOpenFailure ⇒ Any) extends Actor with ActorLogging with FSM[CircuitBreakerState, CircuitBreakerStateData] { + failureDetector: Any => Boolean, + failureMap: CircuitOpenFailure => Any) extends Actor with ActorLogging with FSM[CircuitBreakerState, CircuitBreakerStateData] { import CircuitBreakerInternalEvents._ - import FSM.`→` + import FSM.`->` context watch target startWith(Closed, CircuitBreakerStateData(failureCount = 0)) def callSucceededHandling: StateFunction = { - case Event(CallSucceeded, state) ⇒ + case Event(CallSucceeded, state) => log.debug("Received call succeeded notification in state {} resetting counter", state) goto(Closed) using CircuitBreakerStateData(failureCount = 0, firstHalfOpenMessageSent = false) } def passthroughHandling: StateFunction = { - case Event(Passthrough(message), state) ⇒ + case Event(Passthrough(message), state) => log.debug("Received a passthrough message in state {}, forwarding the message to the target actor without altering current state", state) target ! message stay } def targetTerminationHandling: StateFunction = { - case Event(Terminated(`target`), state) ⇒ + case Event(Terminated(`target`), state) => log.debug("Target actor {} terminated while in state {}, terminating this proxy too", target, state) stop } @@ -142,12 +142,12 @@ final class CircuitBreakerProxy( when(Closed) { commonStateHandling orElse { - case Event(TellOnly(message), _) ⇒ + case Event(TellOnly(message), _) => log.debug("Closed: Sending message {} without expecting any response", message) target ! message stay - case Event(CallFailed, state) ⇒ + case Event(CallFailed, state) => log.debug("Received call failed notification in state {} incrementing counter", state) val newState = state.copy(failureCount = state.failureCount + 1) if (newState.failureCount < maxFailures) { @@ -156,7 +156,7 @@ final class CircuitBreakerProxy( goto(Open) using newState } - case Event(message, state) ⇒ + case Event(message, state) => log.debug("CLOSED: Sending message {} expecting a response within timeout {}", message, callTimeout) val currentSender = sender() forwardRequest(message, sender, state, log) @@ -167,19 +167,19 @@ final class CircuitBreakerProxy( when(Open, stateTimeout = resetTimeout.duration) { commonStateHandling orElse { - case Event(StateTimeout, state) ⇒ + case Event(StateTimeout, state) => log.debug("Timeout expired for state OPEN, going to half open") goto(HalfOpen) using state.copy(firstHalfOpenMessageSent = false) - case Event(CallFailed, state) ⇒ + case Event(CallFailed, state) => log.debug("Open: Call received a further call failed notification, probably from a previous timed out event, ignoring") stay - case Event(openNotification @ CircuitOpenFailure(_), _) ⇒ + case Event(openNotification @ CircuitOpenFailure(_), _) => log.warning("Unexpected circuit open notification {} sent to myself. Please report this as a bug.", openNotification) stay - case Event(message, state) ⇒ + case Event(message, state) => val failureNotification = failureMap(CircuitOpenFailure(message)) log.debug("OPEN: Failing request for message {}, sending failure notification {} to sender {}", message, failureNotification, sender) sender ! failureNotification @@ -190,24 +190,24 @@ final class CircuitBreakerProxy( when(HalfOpen) { commonStateHandling orElse { - case Event(TellOnly(message), _) ⇒ + case Event(TellOnly(message), _) => log.debug("HalfOpen: Dropping TellOnly request for message {}", message) stay - case Event(CallFailed, CircuitBreakerStateData(_, true)) ⇒ + case Event(CallFailed, CircuitBreakerStateData(_, true)) => log.debug("HalfOpen: First forwarded call failed returning to OPEN state") goto(Open) - case Event(CallFailed, CircuitBreakerStateData(_, false)) ⇒ + case Event(CallFailed, CircuitBreakerStateData(_, false)) => log.debug("HalfOpen: Call received a further call failed notification, probably from a previous timed out event, ignoring") stay - case Event(message, state @ CircuitBreakerStateData(_, false)) ⇒ + case Event(message, state @ CircuitBreakerStateData(_, false)) => log.debug("HalfOpen: First message {} received, forwarding it to target {}", message, target) forwardRequest(message, sender, state, log) stay using state.copy(firstHalfOpenMessageSent = true) - case Event(message, CircuitBreakerStateData(_, true)) ⇒ + case Event(message, CircuitBreakerStateData(_, true)) => val failureNotification = failureMap(CircuitOpenFailure(message)) log.debug("HALF-OPEN: Failing request for message {}, sending failure notification {} to sender {}", message, failureNotification, sender) sender ! failureNotification @@ -219,7 +219,7 @@ final class CircuitBreakerProxy( import context.dispatcher target.ask(message)(callTimeout).onComplete { - case Success(response) ⇒ + case Success(response) => log.debug("Request '{}' has been replied to with response {}, forwarding to original sender {}", message, currentSender) currentSender ! response @@ -241,7 +241,7 @@ final class CircuitBreakerProxy( self ! CallSucceeded } - case Failure(reason) ⇒ + case Failure(reason) => log.debug( "Request '{}' to target {} failed with exception {}, sending self-message to ask incrementing failure count (origin state was {})", message, target, reason, state) @@ -251,15 +251,15 @@ final class CircuitBreakerProxy( } onTransition { - case from → Closed ⇒ + case from -> Closed => log.debug("Moving from state {} to state CLOSED", from) circuitEventListener foreach { _ ! CircuitClosed(self) } - case from → HalfOpen ⇒ + case from -> HalfOpen => log.debug("Moving from state {} to state HALF OPEN", from) circuitEventListener foreach { _ ! CircuitHalfOpen(self) } - case from → Open ⇒ + case from -> Open => log.debug("Moving from state {} to state OPEN", from) circuitEventListener foreach { _ ! CircuitOpen(self) } } diff --git a/akka-contrib/src/main/scala/akka/contrib/circuitbreaker/askExtensions.scala b/akka-contrib/src/main/scala/akka/contrib/circuitbreaker/askExtensions.scala index aa89e7e959..868d174949 100644 --- a/akka-contrib/src/main/scala/akka/contrib/circuitbreaker/askExtensions.scala +++ b/akka-contrib/src/main/scala/akka/contrib/circuitbreaker/askExtensions.scala @@ -69,11 +69,11 @@ final class CircuitBreakerAwareFuture(val future: Future[Any]) extends AnyVal { @throws[OpenCircuitException] def failForOpenCircuit(implicit executionContext: ExecutionContext): Future[Any] = failForOpenCircuitWith(OpenCircuitException) - def failForOpenCircuitWith(throwing: ⇒ Throwable)(implicit executionContext: ExecutionContext): Future[Any] = { + def failForOpenCircuitWith(throwing: => Throwable)(implicit executionContext: ExecutionContext): Future[Any] = { future.flatMap { _ match { - case CircuitOpenFailure(_) ⇒ Future.failed(throwing) - case result ⇒ Future.successful(result) + case CircuitOpenFailure(_) => Future.failed(throwing) + case result => Future.successful(result) } } } diff --git a/akka-contrib/src/main/scala/akka/contrib/jul/JavaLogger.scala b/akka-contrib/src/main/scala/akka/contrib/jul/JavaLogger.scala index 0027d735b3..924522a1bd 100644 --- a/akka-contrib/src/main/scala/akka/contrib/jul/JavaLogger.scala +++ b/akka-contrib/src/main/scala/akka/contrib/jul/JavaLogger.scala @@ -38,11 +38,11 @@ trait JavaLogging { class JavaLogger extends Actor with RequiresMessageQueue[LoggerMessageQueueSemantics] { def receive = { - case event @ Error(cause, _, _, _) ⇒ log(logging.Level.SEVERE, cause, event) - case event: Warning ⇒ log(logging.Level.WARNING, null, event) - case event: Info ⇒ log(logging.Level.INFO, null, event) - case event: Debug ⇒ log(logging.Level.CONFIG, null, event) - case InitializeLogger(_) ⇒ sender() ! LoggerInitialized + case event @ Error(cause, _, _, _) => log(logging.Level.SEVERE, cause, event) + case event: Warning => log(logging.Level.WARNING, null, event) + case event: Info => log(logging.Level.INFO, null, event) + case event: Debug => log(logging.Level.CONFIG, null, event) + case InitializeLogger(_) => sender() ! LoggerInitialized } @inline @@ -107,7 +107,7 @@ trait JavaLoggingAdapter extends LoggingAdapter { private def updateSource(record: logging.LogRecord): Unit = { val stack = Thread.currentThread.getStackTrace val source = stack.find { - frame ⇒ + frame => val cname = frame.getClassName !cname.startsWith("akka.contrib.jul.") && !cname.startsWith("akka.event.LoggingAdapter") && diff --git a/akka-contrib/src/main/scala/akka/contrib/mailbox/PeekMailbox.scala b/akka-contrib/src/main/scala/akka/contrib/mailbox/PeekMailbox.scala index 16a5a4d633..fa312a5432 100644 --- a/akka-contrib/src/main/scala/akka/contrib/mailbox/PeekMailbox.scala +++ b/akka-contrib/src/main/scala/akka/contrib/mailbox/PeekMailbox.scala @@ -30,8 +30,8 @@ class PeekMailboxExtension(val system: ExtendedActorSystem) extends Extension { def ack()(implicit context: ActorContext): Unit = mailboxes.get(context.self) match { - case null ⇒ throw new IllegalArgumentException("Mailbox not registered for: " + context.self) - case mailbox ⇒ mailbox.ack() + case null => throw new IllegalArgumentException("Mailbox not registered for: " + context.self) + case mailbox => mailbox.ack() } } @@ -46,13 +46,13 @@ class PeekMailboxExtension(val system: ExtendedActorSystem) extends Extension { @deprecated("Use an explicit supervisor or proxy actor instead", "2.5.0") class PeekMailboxType(settings: ActorSystem.Settings, config: Config) extends MailboxType { override def create(owner: Option[ActorRef], system: Option[ActorSystem]) = (owner, system) match { - case (Some(o), Some(s)) ⇒ + case (Some(o), Some(s)) => val retries = config.getInt("max-retries") if (retries < 1) throw new akka.ConfigurationException("max-retries must be at least 1") val mailbox = new PeekMailbox(o, s, retries) PeekMailboxExtension(s).register(o, mailbox) mailbox - case _ ⇒ throw new Exception("no mailbox owner or system given") + case _ => throw new Exception("no mailbox owner or system given") } } @@ -78,16 +78,16 @@ class PeekMailbox(owner: ActorRef, system: ActorSystem, maxRetries: Int) // this logic does not work if maxRetries==0, but then you could also use a normal mailbox override def dequeue(): Envelope = tries match { - case -1 ⇒ + case -1 => queue.poll() - case 0 | Marker ⇒ + case 0 | Marker => val e = queue.peek() tries = if (e eq null) 0 else 1 e - case `maxRetries` ⇒ + case `maxRetries` => tries = Marker queue.poll() - case n ⇒ + case n => tries = n + 1 queue.peek() } diff --git a/akka-contrib/src/main/scala/akka/contrib/pattern/Aggregator.scala b/akka-contrib/src/main/scala/akka/contrib/pattern/Aggregator.scala index a654ad67d3..be24a289b6 100644 --- a/akka-contrib/src/main/scala/akka/contrib/pattern/Aggregator.scala +++ b/akka-contrib/src/main/scala/akka/contrib/pattern/Aggregator.scala @@ -12,7 +12,7 @@ import scala.annotation.tailrec */ @deprecated("Feel free to copy", "2.5.0") trait Aggregator { - this: Actor ⇒ + this: Actor => private var processing = false private val expectList = WorkList.empty[Actor.Receive] @@ -55,7 +55,7 @@ trait Aggregator { * Receive function for handling the aggregations. */ def receive: Actor.Receive = { - case msg if handleMessage(msg) ⇒ // already dealt with in handleMessage + case msg if handleMessage(msg) => // already dealt with in handleMessage } /** @@ -66,9 +66,9 @@ trait Aggregator { def handleMessage(msg: Any): Boolean = { processing = true try { - expectList process { fn ⇒ + expectList process { fn => var processed = true - fn.applyOrElse(msg, (_: Any) ⇒ processed = false) + fn.applyOrElse(msg, (_: Any) => processed = false) processed } } finally { @@ -155,7 +155,7 @@ class WorkList[T] { * @param processFn The processing function, returns true if processing succeeds. * @return true if an entry has been processed, false if no entries are processed successfully. */ - def process(processFn: T ⇒ Boolean): Boolean = { + def process(processFn: T => Boolean): Boolean = { @tailrec def process(parent: Entry[T], entry: Entry[T]): Boolean = { diff --git a/akka-contrib/src/main/scala/akka/contrib/pattern/ReceivePipeline.scala b/akka-contrib/src/main/scala/akka/contrib/pattern/ReceivePipeline.scala index e25f4c5610..4d1a8a066e 100644 --- a/akka-contrib/src/main/scala/akka/contrib/pattern/ReceivePipeline.scala +++ b/akka-contrib/src/main/scala/akka/contrib/pattern/ReceivePipeline.scala @@ -20,10 +20,10 @@ object ReceivePipeline { * * The block of code will be executed before similar blocks in outer interceptors. */ - def andAfter(after: ⇒ Unit): Delegation = InnerAndAfter(transformedMsg, (_ ⇒ after)) + def andAfter(after: => Unit): Delegation = InnerAndAfter(transformedMsg, (_ => after)) } - private[ReceivePipeline] case class InnerAndAfter(transformedMsg: Any, after: Unit ⇒ Unit) extends Delegation + private[ReceivePipeline] case class InnerAndAfter(transformedMsg: Any, after: Unit => Unit) extends Delegation /** * Interceptor return value that indicates that the message has been handled @@ -32,7 +32,7 @@ object ReceivePipeline { */ case object HandledCompletely extends Delegation - private def withDefault(interceptor: Interceptor): Interceptor = interceptor.orElse({ case msg ⇒ Inner(msg) }) + private def withDefault(interceptor: Interceptor): Interceptor = interceptor.orElse({ case msg => Inner(msg) }) type Interceptor = PartialFunction[Any, Delegation] @@ -40,7 +40,7 @@ object ReceivePipeline { private case object Done extends HandlerResult private case object Undefined extends HandlerResult - private type Handler = Any ⇒ HandlerResult + private type Handler = Any => HandlerResult } /** @@ -72,18 +72,18 @@ trait ReceivePipeline extends Actor { decoratorCache = None } - private def combinedDecorator: Receive ⇒ Receive = { receive ⇒ + private def combinedDecorator: Receive => Receive = { receive => // So that reconstructed Receive PF is undefined only when the actor's // receive is undefined for a transformed message that reaches it... val innerReceiveHandler: Handler = { - case msg ⇒ receive.lift(msg).map(_ ⇒ Done).getOrElse(Undefined) + case msg => receive.lift(msg).map(_ => Done).getOrElse(Undefined) } - val zipped = pipeline.foldRight(innerReceiveHandler) { (outerInterceptor, innerHandler) ⇒ + val zipped = pipeline.foldRight(innerReceiveHandler) { (outerInterceptor, innerHandler) => outerInterceptor.andThen { - case Inner(msg) ⇒ innerHandler(msg) - case InnerAndAfter(msg, after) ⇒ try innerHandler(msg) finally after(()) - case HandledCompletely ⇒ Done + case Inner(msg) => innerHandler(msg) + case InnerAndAfter(msg, after) => try innerHandler(msg) finally after(()) + case HandledCompletely => Done } } @@ -94,7 +94,7 @@ trait ReceivePipeline extends Actor { def isDefinedAt(m: Any): Boolean = evaluate(m) != Undefined def apply(m: Any): Unit = evaluate(m) - override def applyOrElse[A1 <: Any, B1 >: Unit](m: A1, default: A1 ⇒ B1): B1 = { + override def applyOrElse[A1 <: Any, B1 >: Unit](m: A1, default: A1 => B1): B1 = { val result = handler(m) if (result == Undefined) default(m) @@ -107,9 +107,9 @@ trait ReceivePipeline extends Actor { * INTERNAL API. */ override protected[akka] def aroundReceive(receive: Receive, msg: Any): Unit = { - def withCachedDecoration(decorator: Receive ⇒ Receive): Receive = decoratorCache match { - case Some((`receive`, cached)) ⇒ cached - case _ ⇒ + def withCachedDecoration(decorator: Receive => Receive): Receive = decoratorCache match { + case Some((`receive`, cached)) => cached + case _ => val decorated = decorator(receive) decoratorCache = Some((receive, decorated)) decorated diff --git a/akka-contrib/src/main/scala/akka/contrib/pattern/ReliableProxy.scala b/akka-contrib/src/main/scala/akka/contrib/pattern/ReliableProxy.scala index 0c544661e4..9b7c8ba9ec 100644 --- a/akka-contrib/src/main/scala/akka/contrib/pattern/ReliableProxy.scala +++ b/akka-contrib/src/main/scala/akka/contrib/pattern/ReliableProxy.scala @@ -52,7 +52,7 @@ object ReliableProxy { context.watch(target) def receive = { - case Message(msg, snd, serial) ⇒ + case Message(msg, snd, serial) => if (serial == lastSerial + 1) { target.tell(msg, snd) sender() ! Ack(serial) @@ -62,7 +62,7 @@ object ReliableProxy { } else { logDebug("Received message from {} with wrong serial: {}", snd, msg) } - case Terminated(`target`) ⇒ context stop self + case Terminated(`target`) => context stop self } } @@ -73,9 +73,9 @@ object ReliableProxy { def compare(a: Int, b: Int): Int = { val c = a - b c match { - case x if x < 0 ⇒ -1 - case x if x == 0 ⇒ 0 - case x if x > 0 ⇒ 1 + case x if x < 0 => -1 + case x if x == 0 => 0 + case x if x > 0 => 1 } } @@ -116,7 +116,7 @@ object ReliableProxy { /** * INTERNAL API */ -private[akka] trait ReliableProxyDebugLogging extends ActorLogging { this: Actor ⇒ +private[akka] trait ReliableProxyDebugLogging extends ActorLogging { this: Actor => val debug: Boolean = Try(context.system.settings.config.getBoolean("akka.reliable-proxy.debug")) getOrElse false @@ -229,7 +229,7 @@ import ReliableProxy._ class ReliableProxy(targetPath: ActorPath, retryAfter: FiniteDuration, reconnectAfter: Option[FiniteDuration], maxConnectAttempts: Option[Int]) extends Actor with LoggingFSM[State, Vector[Message]] with ReliableProxyDebugLogging { - import FSM.`→` + import FSM.`->` var tunnel: ActorRef = _ var currentSerial: Int = 0 @@ -268,7 +268,7 @@ class ReliableProxy(targetPath: ActorPath, retryAfter: FiniteDuration, } override def supervisorStrategy = OneForOneStrategy() { - case _ ⇒ SupervisorStrategy.Escalate + case _ => SupervisorStrategy.Escalate } override def postStop(): Unit = { @@ -280,50 +280,50 @@ class ReliableProxy(targetPath: ActorPath, retryAfter: FiniteDuration, startWith(initialState, Vector.empty) when(Idle) { - case Event(Terminated(_), _) ⇒ terminated() - case Event(Ack(_), _) ⇒ stay() - case Event(Unsent(msgs), _) ⇒ goto(Active) using resend(updateSerial(msgs)) - case Event(msg, _) ⇒ goto(Active) using Vector(send(msg, sender())) + case Event(Terminated(_), _) => terminated() + case Event(Ack(_), _) => stay() + case Event(Unsent(msgs), _) => goto(Active) using resend(updateSerial(msgs)) + case Event(msg, _) => goto(Active) using Vector(send(msg, sender())) } onTransition { - case _ → Active ⇒ scheduleTick() - case Active → Idle ⇒ cancelTimer(resendTimer) - case _ → Connecting ⇒ scheduleReconnectTick() + case _ -> Active => scheduleTick() + case Active -> Idle => cancelTimer(resendTimer) + case _ -> Connecting => scheduleReconnectTick() } when(Active) { - case Event(Terminated(_), _) ⇒ + case Event(Terminated(_), _) => terminated() - case Event(Ack(serial), queue) ⇒ - val q = queue dropWhile (m ⇒ compare(m.serial, serial) <= 0) + case Event(Ack(serial), queue) => + val q = queue dropWhile (m => compare(m.serial, serial) <= 0) if (compare(serial, lastAckSerial) > 0) lastAckSerial = serial scheduleTick() if (q.isEmpty) goto(Idle) using Vector.empty else stay using q - case Event(Tick, queue) ⇒ + case Event(Tick, queue) => logResend(queue.size) queue foreach { tunnel ! _ } scheduleTick() stay() - case Event(Unsent(msgs), queue) ⇒ + case Event(Unsent(msgs), queue) => stay using queue ++ resend(updateSerial(msgs)) - case Event(msg, queue) ⇒ + case Event(msg, queue) => stay using (queue :+ send(msg, sender())) } when(Connecting) { - case Event(Terminated(_), _) ⇒ + case Event(Terminated(_), _) => stay() - case Event(ActorIdentity(_, Some(actor)), queue) ⇒ + case Event(ActorIdentity(_, Some(actor)), queue) => val curr = currentTarget cancelTimer(reconnectTimer) createTunnel(actor) if (currentTarget != curr) gossip(TargetChanged(currentTarget)) if (queue.isEmpty) goto(Idle) else goto(Active) using resend(queue) - case Event(ActorIdentity(_, None), _) ⇒ + case Event(ActorIdentity(_, None), _) => stay() - case Event(ReconnectTick, _) ⇒ + case Event(ReconnectTick, _) => if (maxConnectAttempts exists (_ == attemptedReconnects)) { logDebug("Failed to reconnect after {}", attemptedReconnects) stop() @@ -334,9 +334,9 @@ class ReliableProxy(targetPath: ActorPath, retryAfter: FiniteDuration, attemptedReconnects += 1 stay() } - case Event(Unsent(msgs), queue) ⇒ + case Event(Unsent(msgs), queue) => stay using queue ++ updateSerial(msgs) - case Event(msg, queue) ⇒ + case Event(msg, queue) => stay using (queue :+ Message(msg, sender(), nextSerial())) } diff --git a/akka-contrib/src/main/scala/akka/contrib/throttle/TimerBasedThrottler.scala b/akka-contrib/src/main/scala/akka/contrib/throttle/TimerBasedThrottler.scala index 4c82716ed6..3ef3638cee 100644 --- a/akka-contrib/src/main/scala/akka/contrib/throttle/TimerBasedThrottler.scala +++ b/akka-contrib/src/main/scala/akka/contrib/throttle/TimerBasedThrottler.scala @@ -5,7 +5,7 @@ package akka.contrib.throttle import scala.concurrent.duration.{ Duration, FiniteDuration } -import scala.collection.immutable.{ Queue ⇒ Q } +import scala.collection.immutable.{ Queue => Q } import akka.actor.{ ActorRef, Actor, FSM } import Throttler._ import TimerBasedThrottler._ @@ -217,7 +217,7 @@ private[throttle] object TimerBasedThrottler { */ @deprecated("Use streams, see migration guide", "2.5.0") class TimerBasedThrottler(var rate: Rate) extends Actor with FSM[State, Data] { - import FSM.`→` + import FSM.`->` this.rate = normalizedRate(rate) @@ -226,27 +226,27 @@ class TimerBasedThrottler(var rate: Rate) extends Actor with FSM[State, Data] { // Idle: no messages, or target not set when(Idle) { // Set the rate - case Event(SetRate(newRate), d) ⇒ + case Event(SetRate(newRate), d) => this.rate = normalizedRate(newRate) stay using d.copy(callsLeftInThisPeriod = rate.numberOfCalls) // Set the target - case Event(SetTarget(t @ Some(_)), d) if !d.queue.isEmpty ⇒ + case Event(SetTarget(t @ Some(_)), d) if !d.queue.isEmpty => goto(Active) using deliverMessages(d.copy(target = t)) - case Event(SetTarget(t), d) ⇒ + case Event(SetTarget(t), d) => stay using d.copy(target = t) // Queuing - case Event(msg, d @ Data(None, _, queue)) ⇒ + case Event(msg, d @ Data(None, _, queue)) => stay using d.copy(queue = queue.enqueue(Message(msg, context.sender()))) - case Event(msg, d @ Data(Some(_), _, Seq())) ⇒ + case Event(msg, d @ Data(Some(_), _, Seq())) => goto(Active) using deliverMessages(d.copy(queue = Q(Message(msg, context.sender())))) // Note: The case Event(msg, t @ Data(Some(_), _, _, Seq(_*))) should never happen here. } when(Active) { // Set the rate - case Event(SetRate(newRate), d) ⇒ + case Event(SetRate(newRate), d) => this.rate = normalizedRate(newRate) // Note: this should be improved (see "Known issues" in class comments) stopTimer() @@ -254,38 +254,38 @@ class TimerBasedThrottler(var rate: Rate) extends Actor with FSM[State, Data] { stay using d.copy(callsLeftInThisPeriod = rate.numberOfCalls) // Set the target (when the new target is None) - case Event(SetTarget(None), d) ⇒ + case Event(SetTarget(None), d) => // Note: We do not yet switch to state `Inactive` because we need the timer to tick once more before stay using d.copy(target = None) // Set the target (when the new target is not None) - case Event(SetTarget(t @ Some(_)), d) ⇒ + case Event(SetTarget(t @ Some(_)), d) => stay using d.copy(target = t) // Tick after a `SetTarget(None)`: take the additional permits and go to `Idle` - case Event(Tick, d @ Data(None, _, _)) ⇒ + case Event(Tick, d @ Data(None, _, _)) => goto(Idle) using d.copy(callsLeftInThisPeriod = rate.numberOfCalls) // Period ends and we have no more messages: take the additional permits and go to `Idle` - case Event(Tick, d @ Data(_, _, Seq())) ⇒ + case Event(Tick, d @ Data(_, _, Seq())) => goto(Idle) using d.copy(callsLeftInThisPeriod = rate.numberOfCalls) // Period ends and we get more occasions to send messages - case Event(Tick, d @ Data(_, _, _)) ⇒ + case Event(Tick, d @ Data(_, _, _)) => stay using deliverMessages(d.copy(callsLeftInThisPeriod = rate.numberOfCalls)) // Queue a message (when we cannot send messages in the current period anymore) - case Event(msg, d @ Data(_, 0, queue)) ⇒ + case Event(msg, d @ Data(_, 0, queue)) => stay using d.copy(queue = queue.enqueue(Message(msg, context.sender()))) // Queue a message (when we can send some more messages in the current period) - case Event(msg, d @ Data(_, _, queue)) ⇒ + case Event(msg, d @ Data(_, _, queue)) => stay using deliverMessages(d.copy(queue = queue.enqueue(Message(msg, context.sender())))) } onTransition { - case Idle → Active ⇒ startTimer(rate) - case Active → Idle ⇒ stopTimer() + case Idle -> Active => startTimer(rate) + case Active -> Idle => stopTimer() } initialize() @@ -313,7 +313,7 @@ class TimerBasedThrottler(var rate: Rate) extends Actor with FSM[State, Data] { val queue = data.queue val nrOfMsgToSend = scala.math.min(queue.length, data.callsLeftInThisPeriod) - queue.take(nrOfMsgToSend).foreach(x ⇒ data.target.get.tell(x.message, x.sender)) + queue.take(nrOfMsgToSend).foreach(x => data.target.get.tell(x.message, x.sender)) data.copy(queue = queue.drop(nrOfMsgToSend), callsLeftInThisPeriod = data.callsLeftInThisPeriod - nrOfMsgToSend) } diff --git a/akka-contrib/src/multi-jvm/scala/akka/contrib/pattern/ReliableProxySpec.scala b/akka-contrib/src/multi-jvm/scala/akka/contrib/pattern/ReliableProxySpec.scala index 0f2393a0a0..8ac9c659e8 100644 --- a/akka-contrib/src/multi-jvm/scala/akka/contrib/pattern/ReliableProxySpec.scala +++ b/akka-contrib/src/multi-jvm/scala/akka/contrib/pattern/ReliableProxySpec.scala @@ -54,7 +54,7 @@ class ReliableProxySpec extends MultiNodeSpec(ReliableProxySpec) with STMultiNod def startTarget(): Unit = { target = system.actorOf(Props(new Actor { def receive = { - case x ⇒ testActor ! x + case x => testActor ! x } }).withDeploy(Deploy.local), "echo") } @@ -71,7 +71,7 @@ class ReliableProxySpec extends MultiNodeSpec(ReliableProxySpec) with STMultiNod def expectTransition(max: FiniteDuration, s1: State, s2: State) = expectMsg(max, FSM.Transition(proxy, s1, s2)) def sendN(n: Int) = (1 to n) foreach (proxy ! _) - def expectN(n: Int) = (1 to n) foreach { n ⇒ expectMsg(n); lastSender should ===(target) } + def expectN(n: Int) = (1 to n) foreach { n => expectMsg(n); lastSender should ===(target) } // avoid too long timeout for expectNoMsg when using dilated timeouts, because // blackhole will trigger failure detection @@ -365,7 +365,7 @@ class ReliableProxySpec extends MultiNodeSpec(ReliableProxySpec) with STMultiNod within(5 * 2.seconds) { val proxyTerm = expectMsgType[ProxyTerminated] // Validate that the unsent messages are 50 ints - val unsentInts = proxyTerm.outstanding.queue collect { case Message(i: Int, _, _) if i > 0 && i <= 50 ⇒ i } + val unsentInts = proxyTerm.outstanding.queue collect { case Message(i: Int, _, _) if i > 0 && i <= 50 => i } unsentInts should have size 50 expectTerminated(proxy) } diff --git a/akka-contrib/src/test/scala/akka/contrib/circuitbreaker/CircuitBreakerProxySpec.scala b/akka-contrib/src/test/scala/akka/contrib/circuitbreaker/CircuitBreakerProxySpec.scala index 8fca3072d7..94d0c0f350 100644 --- a/akka-contrib/src/test/scala/akka/contrib/circuitbreaker/CircuitBreakerProxySpec.scala +++ b/akka-contrib/src/test/scala/akka/contrib/circuitbreaker/CircuitBreakerProxySpec.scala @@ -161,7 +161,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { val circuitBreaker = defaultCircuitBreaker When("A number of consecutive request equal to the maxFailures configuration of the circuit breaker is failing") - (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index ⇒ + (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index => receiverRespondsWithFailureToRequest(s"request$index") } @@ -177,7 +177,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { val circuitBreaker = defaultCircuitBreaker When("A number of consecutive request equal to the maxFailures configuration of the circuit breaker is failing") - (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index ⇒ + (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index => receiverRespondsWithFailureToRequest(s"request$index") } @@ -192,11 +192,11 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { Given("A circuit breaker proxy pointing to a target actor built with a function to convert CircuitOpenFailure response into a String response") val circuitBreaker = system.actorOf( baseCircuitBreakerPropsBuilder - .copy(openCircuitFailureConverter = { failureMsg ⇒ s"NOT SENT: ${failureMsg.failedMsg}" }) + .copy(openCircuitFailureConverter = { failureMsg => s"NOT SENT: ${failureMsg.failedMsg}" }) .props(receiver.ref)) When("A number of consecutive request equal to the maxFailures configuration of the circuit breaker is failing") - (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index ⇒ + (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index => receiverRespondsWithFailureToRequest(s"request$index") } @@ -339,7 +339,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { val suicidalActor = actor( new Act { become { - case anyMessage ⇒ + case anyMessage => sender() ! "dying now" context stop self } @@ -405,7 +405,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { val circuitBreaker = defaultCircuitBreaker When("Circuit enters OPEN state") - (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index ⇒ + (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index => receiverRespondsWithFailureToRequest(s"request$index") } @@ -421,7 +421,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { val circuitBreaker = defaultCircuitBreaker When("Circuit enters OPEN state") - (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index ⇒ + (1 to baseCircuitBreakerPropsBuilder.maxFailures) foreach { index => receiverRespondsWithFailureToRequest(s"request$index") } @@ -457,7 +457,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { receiver.reply("response") Then("The response is available as result of the future returned by the askWithCircuitBreaker method") - whenReady(responseFuture) { response ⇒ + whenReady(responseFuture) { response => response should be("response") } } @@ -479,7 +479,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { receiver.expectNoMsg() And("The response is converted into a failure") - whenReady(responseFuture.failed) { failure ⇒ + whenReady(responseFuture.failed) { failure => failure shouldBe a[OpenCircuitException] } } @@ -506,7 +506,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { receiver.reply("response") Then("The response is available as result of the future returned by the askWithCircuitBreaker method") - whenReady(responseFuture) { response ⇒ + whenReady(responseFuture) { response => response should be("response") } } @@ -528,7 +528,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { receiver.expectNoMsg() And("The response is converted into a failure") - whenReady(responseFuture.failed) { failure ⇒ + whenReady(responseFuture.failed) { failure => failure shouldBe a[OpenCircuitException] } } @@ -552,7 +552,7 @@ class CircuitBreakerProxySpec extends AkkaSpec() with GivenWhenThen { receiver.expectNoMsg() And("The response is converted into a failure") - whenReady(responseFuture.failed) { failure ⇒ + whenReady(responseFuture.failed) { failure => failure shouldBe a[MyException] failure.getMessage() should be("Circuit is open") } diff --git a/akka-contrib/src/test/scala/akka/contrib/circuitbreaker/sample/CircuitBreaker.scala b/akka-contrib/src/test/scala/akka/contrib/circuitbreaker/sample/CircuitBreaker.scala index d9edf571f6..3164727292 100644 --- a/akka-contrib/src/test/scala/akka/contrib/circuitbreaker/sample/CircuitBreaker.scala +++ b/akka-contrib/src/test/scala/akka/contrib/circuitbreaker/sample/CircuitBreaker.scala @@ -34,10 +34,10 @@ class SimpleService extends Actor with ActorLogging { context.system.scheduler.schedule(1.second, 1.second, self, ResetCount) override def receive = { - case ResetCount ⇒ + case ResetCount => messageCount = 0 - case Request(content) ⇒ + case Request(content) => messageCount += 1 // simulate workload Thread.sleep(100 * messageCount) @@ -66,30 +66,30 @@ class CircuitBreaker(potentiallyFailingService: ActorRef) extends Actor with Act .copy( failureDetector = { _ match { - case Response(Left(_)) ⇒ true - case _ ⇒ false + case Response(Left(_)) => true + case _ => false } }) .props(potentiallyFailingService), "serviceCircuitBreaker") override def receive: Receive = { - case AskFor(requestToForward) ⇒ + case AskFor(requestToForward) => serviceCircuitBreaker ! Request(requestToForward) - case Right(Response(content)) ⇒ + case Right(Response(content)) => //handle response log.info("Got successful response {}", content) - case Response(Right(content)) ⇒ + case Response(Right(content)) => //handle response log.info("Got successful response {}", content) - case Response(Left(content)) ⇒ + case Response(Left(content)) => //handle response log.info("Got failed response {}", content) - case CircuitOpenFailure(failedMsg) ⇒ + case CircuitOpenFailure(failedMsg) => log.warning("Unable to send message {}", failedMsg) } } @@ -108,12 +108,12 @@ class CircuitBreakerAsk(potentiallyFailingService: ActorRef) extends Actor with .copy( failureDetector = { _ match { - case Response(Left(_)) ⇒ true - case _ ⇒ false + case Response(Left(_)) => true + case _ => false } }) .copy( - openCircuitFailureConverter = { failure ⇒ + openCircuitFailureConverter = { failure => Left(s"Circuit open when processing ${failure.failedMsg}") }) .props(potentiallyFailingService), @@ -122,17 +122,17 @@ class CircuitBreakerAsk(potentiallyFailingService: ActorRef) extends Actor with import context.dispatcher override def receive: Receive = { - case AskFor(requestToForward) ⇒ + case AskFor(requestToForward) => (serviceCircuitBreaker ? Request(requestToForward)).mapTo[Either[String, String]].onComplete { - case Success(Right(successResponse)) ⇒ + case Success(Right(successResponse)) => //handle response log.info("Got successful response {}", successResponse) - case Success(Left(failureResponse)) ⇒ + case Success(Left(failureResponse)) => //handle response log.info("Got successful response {}", failureResponse) - case Failure(exception) ⇒ + case Failure(exception) => //handle response log.info("Got successful response {}", exception) @@ -158,13 +158,13 @@ class CircuitBreakerAskWithFailure(potentiallyFailingService: ActorRef) extends import context.dispatcher override def receive: Receive = { - case AskFor(requestToForward) ⇒ + case AskFor(requestToForward) => (serviceCircuitBreaker ? Request(requestToForward)).failForOpenCircuit.mapTo[String].onComplete { - case Success(successResponse) ⇒ + case Success(successResponse) => //handle response log.info("Got successful response {}", successResponse) - case Failure(exception) ⇒ + case Failure(exception) => //handle response log.info("Got successful response {}", exception) @@ -189,13 +189,13 @@ class CircuitBreakerAskWithCircuitBreaker(potentiallyFailingService: ActorRef) e import context.dispatcher override def receive: Receive = { - case AskFor(requestToForward) ⇒ + case AskFor(requestToForward) => serviceCircuitBreaker.askWithCircuitBreaker(Request(requestToForward)).mapTo[String].onComplete { - case Success(successResponse) ⇒ + case Success(successResponse) => //handle response log.info("Got successful response {}", successResponse) - case Failure(exception) ⇒ + case Failure(exception) => //handle response log.info("Got successful response {}", exception) diff --git a/akka-contrib/src/test/scala/akka/contrib/jul/JavaLoggerSpec.scala b/akka-contrib/src/test/scala/akka/contrib/jul/JavaLoggerSpec.scala index 3ef88f97cb..c9890d20e3 100644 --- a/akka-contrib/src/test/scala/akka/contrib/jul/JavaLoggerSpec.scala +++ b/akka-contrib/src/test/scala/akka/contrib/jul/JavaLoggerSpec.scala @@ -19,9 +19,9 @@ object JavaLoggerSpec { class LogProducer extends Actor with ActorLogging { def receive = { - case e: Exception ⇒ + case e: Exception => log.error(e, e.getMessage) - case (s: String, x: Int) ⇒ + case (s: String, x: Int) => log.info(s, x) } } diff --git a/akka-contrib/src/test/scala/akka/contrib/mailbox/PeekMailboxSpec.scala b/akka-contrib/src/test/scala/akka/contrib/mailbox/PeekMailboxSpec.scala index 907699845d..1594ce6935 100644 --- a/akka-contrib/src/test/scala/akka/contrib/mailbox/PeekMailboxSpec.scala +++ b/akka-contrib/src/test/scala/akka/contrib/mailbox/PeekMailboxSpec.scala @@ -15,20 +15,20 @@ object PeekMailboxSpec { class PeekActor(tries: Int) extends Actor { var togo = tries def receive = { - case Check ⇒ + case Check => sender() ! Check PeekMailboxExtension.ack() - case DoubleAck ⇒ + case DoubleAck => PeekMailboxExtension.ack() PeekMailboxExtension.ack() - case msg ⇒ + case msg => sender() ! msg if (togo == 0) throw new RuntimeException("DONTWANNA") togo -= 1 PeekMailboxExtension.ack() } override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { - for (m ← msg if m == "DIE") context stop self // for testing the case of mailbox.cleanUp + for (m <- msg if m == "DIE") context stop self // for testing the case of mailbox.cleanUp } } } @@ -95,7 +95,7 @@ class PeekMailboxSpec extends AkkaSpec(""" //#demo class MyActor extends Actor { def receive = { - case msg ⇒ + case msg => println(msg) doStuff(msg) // may fail PeekMailboxExtension.ack() diff --git a/akka-contrib/src/test/scala/akka/contrib/pattern/AggregatorSpec.scala b/akka-contrib/src/test/scala/akka/contrib/pattern/AggregatorSpec.scala index 40feb23eb6..fc0d7b9abc 100644 --- a/akka-contrib/src/test/scala/akka/contrib/pattern/AggregatorSpec.scala +++ b/akka-contrib/src/test/scala/akka/contrib/pattern/AggregatorSpec.scala @@ -40,19 +40,19 @@ case object CantUnderstand class SavingsAccountProxy extends Actor { def receive = { - case GetAccountBalances(id: Long) ⇒ + case GetAccountBalances(id: Long) => sender() ! SavingsAccountBalances(Some(List((1, 150000), (2, 29000)))) } } class CheckingAccountProxy extends Actor { def receive = { - case GetAccountBalances(id: Long) ⇒ + case GetAccountBalances(id: Long) => sender() ! CheckingAccountBalances(Some(List((3, 15000)))) } } class MoneyMarketAccountProxy extends Actor { def receive = { - case GetAccountBalances(id: Long) ⇒ + case GetAccountBalances(id: Long) => sender() ! MoneyMarketAccountBalances(None) } } @@ -63,9 +63,9 @@ class AccountBalanceRetriever extends Actor with Aggregator { //#initial-expect expectOnce { - case GetCustomerAccountBalances(id, types) ⇒ + case GetCustomerAccountBalances(id, types) => new AccountAggregator(sender(), id, types) - case _ ⇒ + case _ => sender() ! CantUnderstand context.stop(self) } @@ -80,16 +80,16 @@ class AccountBalanceRetriever extends Actor with Aggregator { if (types.size > 0) types foreach { - case Checking ⇒ fetchCheckingAccountsBalance() - case Savings ⇒ fetchSavingsAccountsBalance() - case MoneyMarket ⇒ fetchMoneyMarketAccountsBalance() + case Checking => fetchCheckingAccountsBalance() + case Savings => fetchSavingsAccountsBalance() + case MoneyMarket => fetchMoneyMarketAccountsBalance() } else collectBalances() // Empty type list yields empty response context.system.scheduler.scheduleOnce(1.second, self, TimedOut) //#expect-timeout expect { - case TimedOut ⇒ collectBalances(force = true) + case TimedOut => collectBalances(force = true) } //#expect-timeout @@ -97,8 +97,8 @@ class AccountBalanceRetriever extends Actor with Aggregator { def fetchCheckingAccountsBalance(): Unit = { context.actorOf(Props[CheckingAccountProxy]) ! GetAccountBalances(id) expectOnce { - case CheckingAccountBalances(balances) ⇒ - results += (Checking → balances) + case CheckingAccountBalances(balances) => + results += (Checking -> balances) collectBalances() } } @@ -107,8 +107,8 @@ class AccountBalanceRetriever extends Actor with Aggregator { def fetchSavingsAccountsBalance(): Unit = { context.actorOf(Props[SavingsAccountProxy]) ! GetAccountBalances(id) expectOnce { - case SavingsAccountBalances(balances) ⇒ - results += (Savings → balances) + case SavingsAccountBalances(balances) => + results += (Savings -> balances) collectBalances() } } @@ -116,8 +116,8 @@ class AccountBalanceRetriever extends Actor with Aggregator { def fetchMoneyMarketAccountsBalance(): Unit = { context.actorOf(Props[MoneyMarketAccountProxy]) ! GetAccountBalances(id) expectOnce { - case MoneyMarketAccountBalances(balances) ⇒ - results += (MoneyMarket → balances) + case MoneyMarketAccountBalances(balances) => + results += (MoneyMarket -> balances) collectBalances() } } @@ -146,7 +146,7 @@ final case class FinalResponse(qualifiedValues: List[String]) class ChainingSample extends Actor with Aggregator { expectOnce { - case InitialRequest(name) ⇒ new MultipleResponseHandler(sender(), name) + case InitialRequest(name) => new MultipleResponseHandler(sender(), name) } class MultipleResponseHandler(originalSender: ActorRef, propName: String) { @@ -161,10 +161,10 @@ class ChainingSample extends Actor with Aggregator { //#unexpect-sample val handle = expect { - case Response(name, value) ⇒ + case Response(name, value) => values += value if (values.size > 3) processList() - case TimedOut ⇒ processList() + case TimedOut => processList() } def processList(): Unit = { @@ -173,7 +173,7 @@ class ChainingSample extends Actor with Aggregator { if (values.size > 0) { context.actorSelection("/user/evaluator") ! values.toList expectOnce { - case EvaluationResults(name, eval) ⇒ processFinal(eval) + case EvaluationResults(name, eval) => processFinal(eval) } } else processFinal(List.empty[Int]) } @@ -197,9 +197,9 @@ class AggregatorSpec extends TestKit(ActorSystem("AggregatorSpec")) with Implici test("Test request 1 account type") { system.actorOf(Props[AccountBalanceRetriever]) ! GetCustomerAccountBalances(1, Set(Savings)) receiveOne(10.seconds) match { - case result: List[_] ⇒ + case result: List[_] => result should have size 1 - case result ⇒ + case result => assert(false, s"Expect List, got ${result.getClass}") } } @@ -208,9 +208,9 @@ class AggregatorSpec extends TestKit(ActorSystem("AggregatorSpec")) with Implici system.actorOf(Props[AccountBalanceRetriever]) ! GetCustomerAccountBalances(1, Set(Checking, Savings, MoneyMarket)) receiveOne(10.seconds) match { - case result: List[_] ⇒ + case result: List[_] => result should have size 3 - case result ⇒ + case result => assert(false, s"Expect List, got ${result.getClass}") } } @@ -227,8 +227,8 @@ class WorkListSpec extends FunSuiteLike { test("Processing empty WorkList") { // ProcessAndRemove something in the middle val processed = workList process { - case TestEntry(9) ⇒ true - case _ ⇒ false + case TestEntry(9) => true + case _ => false } assert(!processed) } @@ -265,20 +265,20 @@ class WorkListSpec extends FunSuiteLike { // ProcessAndRemove something in the middle assert(workList process { - case TestEntry(2) ⇒ true - case _ ⇒ false + case TestEntry(2) => true + case _ => false }) // ProcessAndRemove the head assert(workList process { - case TestEntry(0) ⇒ true - case _ ⇒ false + case TestEntry(0) => true + case _ => false }) // ProcessAndRemove the tail assert(workList process { - case TestEntry(3) ⇒ true - case _ ⇒ false + case TestEntry(3) => true + case _ => false }) } @@ -291,8 +291,8 @@ class WorkListSpec extends FunSuiteLike { test("Process permanent entry") { assert(workList process { - case TestEntry(4) ⇒ true - case _ ⇒ false + case TestEntry(4) => true + case _ => false }) } @@ -310,16 +310,16 @@ class WorkListSpec extends FunSuiteLike { val processed = workList process { - case TestEntry(2) ⇒ true - case _ ⇒ false + case TestEntry(2) => true + case _ => false } assert(!processed) val processed2 = workList process { - case TestEntry(5) ⇒ true - case _ ⇒ false + case TestEntry(5) => true + case _ => false } assert(!processed2) @@ -328,10 +328,10 @@ class WorkListSpec extends FunSuiteLike { test("Append two lists") { workList.removeAll() - 0 to 4 foreach { id ⇒ workList.add(TestEntry(id), permanent = false) } + 0 to 4 foreach { id => workList.add(TestEntry(id), permanent = false) } val l2 = new WorkList[TestEntry] - 5 to 9 foreach { id ⇒ l2.add(TestEntry(id), permanent = true) } + 5 to 9 foreach { id => l2.add(TestEntry(id), permanent = true) } workList addAll l2 @@ -356,7 +356,7 @@ class WorkListSpec extends FunSuiteLike { val workList2 = WorkList.empty[PartialFunction[Any, Unit]] val fn1: PartialFunction[Any, Unit] = { - case s: String ⇒ + case s: String => val result1 = workList2 remove fn1 assert(result1 === true, "First remove must return true") val result2 = workList2 remove fn1 @@ -364,7 +364,7 @@ class WorkListSpec extends FunSuiteLike { } val fn2: PartialFunction[Any, Unit] = { - case s: String ⇒ + case s: String => workList2.add(fn1, permanent = true) } @@ -374,18 +374,18 @@ class WorkListSpec extends FunSuiteLike { assert(workList2.tail == workList2.head.next) // Processing inserted fn1, reentrant adding fn2 - workList2 process { fn ⇒ + workList2 process { fn => var processed = true - fn.applyOrElse("Foo", (_: Any) ⇒ processed = false) + fn.applyOrElse("Foo", (_: Any) => processed = false) processed } } test("Reentrant delete") { // Processing inserted fn2, should delete itself - workList2 process { fn ⇒ + workList2 process { fn => var processed = true - fn.applyOrElse("Foo", (_: Any) ⇒ processed = false) + fn.applyOrElse("Foo", (_: Any) => processed = false) processed } } diff --git a/akka-contrib/src/test/scala/akka/contrib/pattern/ReceivePipelineSpec.scala b/akka-contrib/src/test/scala/akka/contrib/pattern/ReceivePipelineSpec.scala index e50f2c5e59..f0d7021f24 100644 --- a/akka-contrib/src/test/scala/akka/contrib/pattern/ReceivePipelineSpec.scala +++ b/akka-contrib/src/test/scala/akka/contrib/pattern/ReceivePipelineSpec.scala @@ -18,25 +18,25 @@ object ReceivePipelineSpec { class ReplierActor extends Actor with ReceivePipeline { def receive: Actor.Receive = becomeAndReply def becomeAndReply: Actor.Receive = { - case "become" ⇒ context.become(justReply) - case m ⇒ sender ! m + case "become" => context.become(justReply) + case m => sender ! m } def justReply: Actor.Receive = { - case m ⇒ sender ! m + case m => sender ! m } } class IntReplierActor(max: Int) extends Actor with ReceivePipeline { def receive: Actor.Receive = { - case m: Int if (m <= max) ⇒ sender ! m + case m: Int if (m <= max) => sender ! m } } class TotallerActor extends Actor with ReceivePipeline { var total = 0 def receive: Actor.Receive = { - case m: Int ⇒ total += m - case "get" ⇒ sender ! total + case m: Int => total += m + case "get" => sender ! total } } @@ -45,56 +45,56 @@ object ReceivePipelineSpec { } trait ListBuilderInterceptor { - this: ReceivePipeline ⇒ + this: ReceivePipeline => pipelineOuter { - case n: Int ⇒ Inner(IntList((n until n + 3).toList)) + case n: Int => Inner(IntList((n until n + 3).toList)) } } trait AdderInterceptor { - this: ReceivePipeline ⇒ + this: ReceivePipeline => pipelineInner { - case n: Int ⇒ Inner(n + 10) - case IntList(l) ⇒ Inner(IntList(l.map(_ + 10))) - case "explicitly ignored" ⇒ HandledCompletely + case n: Int => Inner(n + 10) + case IntList(l) => Inner(IntList(l.map(_ + 10))) + case "explicitly ignored" => HandledCompletely } } trait ToStringInterceptor { - this: ReceivePipeline ⇒ + this: ReceivePipeline => pipelineInner { - case i: Int ⇒ Inner(i.toString) - case IntList(l) ⇒ Inner(l.toString) - case other: Iterable[_] ⇒ Inner(other.toString) + case i: Int => Inner(i.toString) + case IntList(l) => Inner(l.toString) + case other: Iterable[_] => Inner(other.toString) } } trait OddDoublerInterceptor { - this: ReceivePipeline ⇒ + this: ReceivePipeline => pipelineInner { - case i: Int if (i % 2 != 0) ⇒ Inner(i * 2) + case i: Int if (i % 2 != 0) => Inner(i * 2) } } trait EvenHalverInterceptor { - this: ReceivePipeline ⇒ + this: ReceivePipeline => pipelineInner { - case i: Int if (i % 2 == 0) ⇒ Inner(i / 2) + case i: Int if (i % 2 == 0) => Inner(i / 2) } } trait Timer { - this: ReceivePipeline ⇒ + this: ReceivePipeline => def notifyDuration(duration: Long): Unit pipelineInner { - case msg: Any ⇒ + case msg: Any => val start = 1L // = currentTimeMillis Inner(msg).andAfter { val end = 100L // = currentTimeMillis @@ -176,16 +176,16 @@ object PersistentReceivePipelineSpec { override def persistenceId: String = "p-1" def becomeAndReply: Actor.Receive = { - case "become" ⇒ context.become(justReply) - case m ⇒ sender ! m + case "become" => context.become(justReply) + case m => sender ! m } def justReply: Actor.Receive = { - case m ⇒ sender ! m + case m => sender ! m } override def receiveCommand: Receive = becomeAndReply override def receiveRecover: Receive = { - case _ ⇒ // ... + case _ => // ... } } @@ -350,11 +350,11 @@ object InActorSample extends App { class PipelinedActor extends Actor with ReceivePipeline { // Increment - pipelineInner { case i: Int ⇒ Inner(i + 1) } + pipelineInner { case i: Int => Inner(i + 1) } // Double - pipelineInner { case i: Int ⇒ Inner(i * 2) } + pipelineInner { case i: Int => Inner(i * 2) } - def receive: Receive = { case any ⇒ println(any) } + def receive: Receive = { case any => println(any) } } actor ! 5 // prints 12 = (5 + 1) * 2 @@ -366,14 +366,14 @@ object InActorSample extends App { //#in-actor-outer // Increment - pipelineInner { case i: Int ⇒ Inner(i + 1) } + pipelineInner { case i: Int => Inner(i + 1) } // Double - pipelineOuter { case i: Int ⇒ Inner(i * 2) } + pipelineOuter { case i: Int => Inner(i * 2) } // prints 11 = (5 * 2) + 1 //#in-actor-outer - def receive: Receive = { case any ⇒ println(any) } + def receive: Receive = { case any => println(any) } } withOuterActor ! 5 @@ -385,7 +385,7 @@ object InterceptorSamples { //#interceptor-sample1 val incrementInterceptor: Interceptor = { - case i: Int ⇒ Inner(i + 1) + case i: Int => Inner(i + 1) } //#interceptor-sample1 @@ -393,7 +393,7 @@ object InterceptorSamples { //#interceptor-sample2 val timerInterceptor: Interceptor = { - case e ⇒ + case e => val start = System.nanoTime Inner(e).andAfter { val end = System.nanoTime @@ -413,10 +413,10 @@ object MixinSample extends App { //#mixin-model val texts = Map( - "that.rug_EN" → "That rug really tied the room together.", - "your.opinion_EN" → "Yeah, well, you know, that's just, like, your opinion, man.", - "that.rug_ES" → "Esa alfombra realmente completaba la sala.", - "your.opinion_ES" → "Sí, bueno, ya sabes, eso es solo, como, tu opinion, amigo.") + "that.rug_EN" -> "That rug really tied the room together.", + "your.opinion_EN" -> "Yeah, well, you know, that's just, like, your opinion, man.", + "that.rug_ES" -> "Esa alfombra realmente completaba la sala.", + "your.opinion_ES" -> "Sí, bueno, ya sabes, eso es solo, como, tu opinion, amigo.") case class I18nText(locale: String, key: String) case class Message(author: Option[String], text: Any) @@ -424,19 +424,19 @@ object MixinSample extends App { //#mixin-interceptors trait I18nInterceptor { - this: ReceivePipeline ⇒ + this: ReceivePipeline => pipelineInner { - case m @ Message(_, I18nText(loc, key)) ⇒ + case m @ Message(_, I18nText(loc, key)) => Inner(m.copy(text = texts(s"${key}_$loc"))) } } trait AuditInterceptor { - this: ReceivePipeline ⇒ + this: ReceivePipeline => pipelineOuter { - case m @ Message(Some(author), text) ⇒ + case m @ Message(Some(author), text) => println(s"$author is about to say: $text") Inner(m) } @@ -450,7 +450,7 @@ object MixinSample extends App { with I18nInterceptor with AuditInterceptor { override def receive: Receive = { - case Message(author, text) ⇒ + case Message(author, text) => println(s"${author.getOrElse("Unknown")} says '$text'") } } @@ -476,10 +476,10 @@ object UnhandledSample extends App { case class PrivateMessage(userId: Option[Long], msg: Any) trait PrivateInterceptor { - this: ReceivePipeline ⇒ + this: ReceivePipeline => pipelineInner { - case PrivateMessage(Some(userId), msg) ⇒ + case PrivateMessage(Some(userId), msg) => if (isGranted(userId)) Inner(msg) else @@ -495,12 +495,12 @@ object AfterSamples { //#interceptor-after trait TimerInterceptor extends ActorLogging { - this: ReceivePipeline ⇒ + this: ReceivePipeline => def logTimeTaken(time: Long) = log.debug(s"Time taken: $time ns") pipelineOuter { - case e ⇒ + case e => val start = System.nanoTime Inner(e).andAfter { val end = System.nanoTime diff --git a/akka-contrib/src/test/scala/akka/contrib/pattern/ReliableProxyDocSpec.scala b/akka-contrib/src/test/scala/akka/contrib/pattern/ReliableProxyDocSpec.scala index 83a4d0f281..3e53e76b0b 100644 --- a/akka-contrib/src/test/scala/akka/contrib/pattern/ReliableProxyDocSpec.scala +++ b/akka-contrib/src/test/scala/akka/contrib/pattern/ReliableProxyDocSpec.scala @@ -18,7 +18,7 @@ object ReliableProxyDocSpec { val proxy = context.actorOf(ReliableProxy.props(targetPath, 100.millis)) def receive = { - case "hello" ⇒ proxy ! "world!" + case "hello" => proxy ! "world!" } } //#demo @@ -31,11 +31,11 @@ object ReliableProxyDocSpec { var client: ActorRef = _ def receive = { - case "go" ⇒ + case "go" => proxy ! 42 client = sender() - case FSM.CurrentState(`proxy`, initial) ⇒ - case FSM.Transition(`proxy`, from, to) ⇒ + case FSM.CurrentState(`proxy`, initial) => + case FSM.Transition(`proxy`, from, to) => if (to == ReliableProxy.Idle) client ! "done" } @@ -49,10 +49,10 @@ object ReliableProxyDocSpec { var client: Option[ActorRef] = None def receive = { - case "hello" ⇒ + case "hello" => proxy ! "world!" client = Some(sender()) - case Terminated(`proxy`) ⇒ + case Terminated(`proxy`) => client foreach { _ ! "terminated" } } } diff --git a/akka-contrib/src/test/scala/akka/contrib/throttle/TimerBasedThrottlerSpec.scala b/akka-contrib/src/test/scala/akka/contrib/throttle/TimerBasedThrottlerSpec.scala index bb4b6376e1..0a24e0375a 100644 --- a/akka-contrib/src/test/scala/akka/contrib/throttle/TimerBasedThrottlerSpec.scala +++ b/akka-contrib/src/test/scala/akka/contrib/throttle/TimerBasedThrottlerSpec.scala @@ -23,7 +23,7 @@ object TimerBasedThrottlerSpec { // A simple actor that prints whatever it receives class PrintActor extends Actor { def receive = { - case x ⇒ println(x) + case x => println(x) } } diff --git a/akka-discovery/src/main/scala/akka/discovery/Discovery.scala b/akka-discovery/src/main/scala/akka/discovery/Discovery.scala index eee3613024..8da83d8fa1 100644 --- a/akka-discovery/src/main/scala/akka/discovery/Discovery.scala +++ b/akka-discovery/src/main/scala/akka/discovery/Discovery.scala @@ -5,7 +5,7 @@ package akka.discovery import java.util.concurrent.ConcurrentHashMap -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import akka.actor._ import akka.annotation.InternalApi @@ -23,12 +23,12 @@ final class Discovery(implicit system: ExtendedActorSystem) extends Extension { private lazy val _defaultImplMethod = system.settings.config.getString("akka.discovery.method") match { - case "" ⇒ + case "" => throw new IllegalArgumentException( "No default service discovery implementation configured in " + "`akka.discovery.method`. Make sure to configure this setting to your preferred implementation such as " + "'akka-dns' in your application.conf (from the akka-discovery module).") - case method ⇒ method + case method => method } private lazy val defaultImpl = loadServiceDiscovery(_defaultImplMethod) @@ -65,13 +65,13 @@ final class Discovery(implicit system: ExtendedActorSystem) extends Extension { def create(clazzName: String): Try[ServiceDiscovery] = { dynamic - .createInstanceFor[ServiceDiscovery](clazzName, (classOf[ExtendedActorSystem] → system) :: Nil) + .createInstanceFor[ServiceDiscovery](clazzName, (classOf[ExtendedActorSystem] -> system) :: Nil) .recoverWith { - case _: ClassNotFoundException | _: NoSuchMethodException ⇒ - dynamic.createInstanceFor[ServiceDiscovery](clazzName, (classOf[ActorSystem] → system) :: Nil) + case _: ClassNotFoundException | _: NoSuchMethodException => + dynamic.createInstanceFor[ServiceDiscovery](clazzName, (classOf[ActorSystem] -> system) :: Nil) } .recoverWith { - case _: ClassNotFoundException | _: NoSuchMethodException ⇒ + case _: ClassNotFoundException | _: NoSuchMethodException => dynamic.createInstanceFor[ServiceDiscovery](clazzName, Nil) } } @@ -80,13 +80,13 @@ final class Discovery(implicit system: ExtendedActorSystem) extends Extension { val instanceTry = create(classNameFromConfig(configName)) instanceTry match { - case Failure(e @ (_: ClassNotFoundException | _: NoSuchMethodException)) ⇒ + case Failure(e @ (_: ClassNotFoundException | _: NoSuchMethodException)) => throw new IllegalArgumentException( s"Illegal [$configName] value or incompatible class! " + "The implementation class MUST extend akka.discovery.ServiceDiscovery and take an " + "ExtendedActorSystem as constructor argument.", e) - case Failure(e) ⇒ throw e - case Success(instance) ⇒ instance + case Failure(e) => throw e + case Success(instance) => instance } } @@ -111,7 +111,7 @@ object Discovery extends ExtensionId[Discovery] with ExtensionIdProvider { system.dynamicAccess.getClassFor("akka.discovery.SimpleServiceDiscovery").get throw new RuntimeException("Old version of Akka Discovery from Akka Management found on the classpath. Remove `com.lightbend.akka.discovery:akka-discovery` from the classpath..") } catch { - case _: ClassNotFoundException ⇒ // all good + case _: ClassNotFoundException => // all good } } diff --git a/akka-discovery/src/main/scala/akka/discovery/ServiceDiscovery.scala b/akka-discovery/src/main/scala/akka/discovery/ServiceDiscovery.scala index a1ed051837..3854e5f7e9 100644 --- a/akka-discovery/src/main/scala/akka/discovery/ServiceDiscovery.scala +++ b/akka-discovery/src/main/scala/akka/discovery/ServiceDiscovery.scala @@ -42,8 +42,8 @@ object ServiceDiscovery { override def toString: String = s"Resolved($serviceName,$addresses)" override def equals(obj: Any): Boolean = obj match { - case other: Resolved ⇒ serviceName == other.serviceName && addresses == other.addresses - case _ ⇒ false + case other: Resolved => serviceName == other.serviceName && addresses == other.addresses + case _ => false } override def hashCode(): Int = { @@ -61,7 +61,7 @@ object ServiceDiscovery { private implicit val inetAddressOrdering: Ordering[InetAddress] = Ordering.by[InetAddress, Iterable[Byte]](_.getAddress) - implicit val addressOrdering: Ordering[ResolvedTarget] = Ordering.by { t ⇒ + implicit val addressOrdering: Ordering[ResolvedTarget] = Ordering.by { t => (t.address, t.host, t.port) } @@ -101,8 +101,8 @@ object ServiceDiscovery { override def toString: String = s"ResolvedTarget($host,$port,$address)" override def equals(obj: Any): Boolean = obj match { - case other: ResolvedTarget ⇒ host == other.host && port == other.port && address == other.address - case _ ⇒ false + case other: ResolvedTarget => host == other.host && port == other.port && address == other.address + case _ => false } override def hashCode(): Int = { @@ -166,8 +166,8 @@ final class Lookup( override def toString: String = s"Lookup($serviceName,$portName,$protocol)" override def equals(obj: Any): Boolean = obj match { - case other: Lookup ⇒ serviceName == other.serviceName && portName == other.portName && protocol == other.protocol - case _ ⇒ false + case other: Lookup => serviceName == other.serviceName && portName == other.portName && protocol == other.protocol + case _ => false } override def hashCode(): Int = { @@ -225,11 +225,11 @@ case object Lookup { */ def parseSrv(str: String): Lookup = str match { - case SrvQuery(portName, protocol, serviceName) if validDomainName(serviceName) ⇒ + case SrvQuery(portName, protocol, serviceName) if validDomainName(serviceName) => Lookup(serviceName).withPortName(portName).withProtocol(protocol) - case null ⇒ throw new NullPointerException("Unable to create Lookup from passed SRV string. Passed value is 'null'") - case _ ⇒ throw new IllegalArgumentException(s"Unable to create Lookup from passed SRV string, invalid format: $str") + case null => throw new NullPointerException("Unable to create Lookup from passed SRV string. Passed value is 'null'") + case _ => throw new IllegalArgumentException(s"Unable to create Lookup from passed SRV string, invalid format: $str") } /** @@ -237,8 +237,8 @@ case object Lookup { */ def isValidSrv(srv: String): Boolean = srv match { - case SrvQuery(_, _, serviceName) ⇒ validDomainName(serviceName) - case _ ⇒ false + case SrvQuery(_, _, serviceName) => validDomainName(serviceName) + case _ => false } private def validDomainName(name: String): Boolean = diff --git a/akka-discovery/src/main/scala/akka/discovery/aggregate/AggregateServiceDiscovery.scala b/akka-discovery/src/main/scala/akka/discovery/aggregate/AggregateServiceDiscovery.scala index 69f8a3846a..8f1f594e72 100644 --- a/akka-discovery/src/main/scala/akka/discovery/aggregate/AggregateServiceDiscovery.scala +++ b/akka-discovery/src/main/scala/akka/discovery/aggregate/AggregateServiceDiscovery.scala @@ -53,7 +53,7 @@ private[akka] final class AggregateServiceDiscovery(system: ExtendedActorSystem) private val methods = { val serviceDiscovery = Discovery(system) - settings.discoveryMethods.map(mech ⇒ (mech, serviceDiscovery.loadServiceDiscovery(mech))) + settings.discoveryMethods.map(mech => (mech, serviceDiscovery.loadServiceDiscovery(mech))) } private implicit val ec = system.dispatcher @@ -65,15 +65,15 @@ private[akka] final class AggregateServiceDiscovery(system: ExtendedActorSystem) private def resolve(sds: Methods, query: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = { sds match { - case (method, next) :: Nil ⇒ + case (method, next) :: Nil => log.debug("Looking up [{}] with [{}]", query, method) next.lookup(query, resolveTimeout) - case (method, next) :: tail ⇒ + case (method, next) :: tail => log.debug("Looking up [{}] with [{}]", query, method) // If nothing comes back then try the next one next .lookup(query, resolveTimeout) - .flatMap { resolved ⇒ + .flatMap { resolved => if (resolved.addresses.isEmpty) { log.debug("Method[{}] returned no ResolvedTargets, trying next", query) resolve(tail, query, resolveTimeout) @@ -81,11 +81,11 @@ private[akka] final class AggregateServiceDiscovery(system: ExtendedActorSystem) Future.successful(resolved) } .recoverWith { - case NonFatal(t) ⇒ + case NonFatal(t) => log.error(t, "[{}] Service discovery failed. Trying next discovery method", method) resolve(tail, query, resolveTimeout) } - case Nil ⇒ + case Nil => // this is checked in `discoveryMethods`, but silence compiler warning throw new IllegalStateException("At least one discovery method should be specified") } diff --git a/akka-discovery/src/main/scala/akka/discovery/config/ConfigServiceDiscovery.scala b/akka-discovery/src/main/scala/akka/discovery/config/ConfigServiceDiscovery.scala index b67008d6e1..a13b7b5527 100644 --- a/akka-discovery/src/main/scala/akka/discovery/config/ConfigServiceDiscovery.scala +++ b/akka-discovery/src/main/scala/akka/discovery/config/ConfigServiceDiscovery.scala @@ -25,15 +25,15 @@ private object ConfigServicesParser { .root() .entrySet() .asScala - .map { en ⇒ + .map { en => (en.getKey, config.getConfig(en.getKey)) } .toMap byService.map { - case (serviceName, full) ⇒ + case (serviceName, full) => val endpoints = full.getConfigList("endpoints").asScala.toList - val resolvedTargets = endpoints.map { c ⇒ + val resolvedTargets = endpoints.map { c => val host = c.getString("host") val port = if (c.hasPath("port")) Some(c.getInt("port")) else None ResolvedTarget(host = host, port = port, address = None) diff --git a/akka-discovery/src/main/scala/akka/discovery/dns/DnsServiceDiscovery.scala b/akka-discovery/src/main/scala/akka/discovery/dns/DnsServiceDiscovery.scala index 1f7cf61541..038fed31f2 100644 --- a/akka-discovery/src/main/scala/akka/discovery/dns/DnsServiceDiscovery.scala +++ b/akka-discovery/src/main/scala/akka/discovery/dns/DnsServiceDiscovery.scala @@ -20,7 +20,7 @@ import scala.concurrent.duration.FiniteDuration import akka.discovery._ import akka.io.dns.DnsProtocol.{ Ip, Srv } import akka.io.dns.{ AAAARecord, ARecord, DnsProtocol, SRVRecord } -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } import scala.util.Failure import scala.util.Success @@ -37,23 +37,23 @@ private object DnsServiceDiscovery { def srvRecordsToResolved(srvRequest: String, resolved: DnsProtocol.Resolved): Resolved = { val ips: Map[String, im.Seq[InetAddress]] = resolved.additionalRecords.foldLeft(Map.empty[String, im.Seq[InetAddress]]) { - case (acc, a: ARecord) ⇒ + case (acc, a: ARecord) => acc.updated(a.name, a.ip +: acc.getOrElse(a.name, Nil)) - case (acc, a: AAAARecord) ⇒ + case (acc, a: AAAARecord) => acc.updated(a.name, a.ip +: acc.getOrElse(a.name, Nil)) - case (acc, _) ⇒ + case (acc, _) => acc } val addresses = resolved.records.flatMap { - case srv: SRVRecord ⇒ - val addresses = ips.getOrElse(srv.target, Nil).map(ip ⇒ ResolvedTarget(srv.target, Some(srv.port), Some(ip))) + case srv: SRVRecord => + val addresses = ips.getOrElse(srv.target, Nil).map(ip => ResolvedTarget(srv.target, Some(srv.port), Some(ip))) if (addresses.isEmpty) { im.Seq(ResolvedTarget(srv.target, Some(srv.port), None)) } else { addresses } - case _ ⇒ im.Seq.empty[ResolvedTarget] + case _ => im.Seq.empty[ResolvedTarget] } Resolved(srvRequest, addresses) @@ -87,11 +87,11 @@ private[akka] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Ser import system.dispatcher dns.ask(AsyncDnsManager.GetCache)(Timeout(30.seconds)).onComplete { - case Success(cache: AsyncDnsCache) ⇒ + case Success(cache: AsyncDnsCache) => asyncDnsCache = OptionVal.Some(cache) - case Success(other) ⇒ + case Success(other) => log.error("Expected AsyncDnsCache but got [{}]", other.getClass.getName) - case Failure(e) ⇒ + case Failure(e) => log.error(e, "Couldn't retrieve DNS cache: {}") } @@ -112,25 +112,25 @@ private[akka] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Ser def askResolve(): Future[Resolved] = { dns.ask(DnsProtocol.Resolve(srvRequest, mode))(resolveTimeout).map { - case resolved: DnsProtocol.Resolved ⇒ + case resolved: DnsProtocol.Resolved => log.debug("{} lookup result: {}", mode, resolved) srvRecordsToResolved(srvRequest, resolved) - case resolved ⇒ + case resolved => log.warning("Resolved UNEXPECTED (resolving to Nil): {}", resolved.getClass) Resolved(srvRequest, Nil) } } asyncDnsCache match { - case OptionVal.Some(cache) ⇒ + case OptionVal.Some(cache) => cache.get((srvRequest, mode)) match { - case Some(resolved) ⇒ + case Some(resolved) => log.debug("{} lookup cached: {}", mode, resolved) Future.successful(srvRecordsToResolved(srvRequest, resolved)) - case None ⇒ + case None => askResolve() } - case OptionVal.None ⇒ + case OptionVal.None => askResolve() } @@ -142,18 +142,18 @@ private[akka] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Ser def ipRecordsToResolved(resolved: DnsProtocol.Resolved): Resolved = { val addresses = resolved.records.collect { - case a: ARecord ⇒ ResolvedTarget(cleanIpString(a.ip.getHostAddress), None, Some(a.ip)) - case a: AAAARecord ⇒ ResolvedTarget(cleanIpString(a.ip.getHostAddress), None, Some(a.ip)) + case a: ARecord => ResolvedTarget(cleanIpString(a.ip.getHostAddress), None, Some(a.ip)) + case a: AAAARecord => ResolvedTarget(cleanIpString(a.ip.getHostAddress), None, Some(a.ip)) } Resolved(lookup.serviceName, addresses) } def askResolve(): Future[Resolved] = { dns.ask(DnsProtocol.Resolve(lookup.serviceName, mode))(resolveTimeout).map { - case resolved: DnsProtocol.Resolved ⇒ + case resolved: DnsProtocol.Resolved => log.debug("{} lookup result: {}", mode, resolved) ipRecordsToResolved(resolved) - case resolved ⇒ + case resolved => log.warning("Resolved UNEXPECTED (resolving to Nil): {}", resolved.getClass) Resolved(lookup.serviceName, Nil) @@ -161,15 +161,15 @@ private[akka] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Ser } asyncDnsCache match { - case OptionVal.Some(cache) ⇒ + case OptionVal.Some(cache) => cache.get((lookup.serviceName, mode)) match { - case Some(resolved) ⇒ + case Some(resolved) => log.debug("{} lookup cached: {}", mode, resolved) Future.successful(ipRecordsToResolved(resolved)) - case None ⇒ + case None => askResolve() } - case OptionVal.None ⇒ + case OptionVal.None => askResolve() } diff --git a/akka-discovery/src/test/scala/akka/discovery/LookupSpec.scala b/akka-discovery/src/test/scala/akka/discovery/LookupSpec.scala index eafe53eec9..4ea760c848 100644 --- a/akka-discovery/src/test/scala/akka/discovery/LookupSpec.scala +++ b/akka-discovery/src/test/scala/akka/discovery/LookupSpec.scala @@ -49,7 +49,7 @@ class LookupSpec extends WordSpec with Matchers with OptionValues { } "throw an IllegalArgumentException for any non-conforming SRV String" in { - noSrvLookups.foreach { str ⇒ + noSrvLookups.foreach { str => withClue(s"parsing '$str'") { assertThrows[IllegalArgumentException] { Lookup.parseSrv(str) @@ -59,7 +59,7 @@ class LookupSpec extends WordSpec with Matchers with OptionValues { } "throw an IllegalArgumentException for any SRV with invalid domain names" in { - srvWithInvalidDomainNames.foreach { str ⇒ + srvWithInvalidDomainNames.foreach { str => withClue(s"parsing '$str'") { assertThrows[IllegalArgumentException] { Lookup.parseSrv(str) @@ -77,7 +77,7 @@ class LookupSpec extends WordSpec with Matchers with OptionValues { } "return false for any non-conforming SRV String" in { - noSrvLookups.foreach { str ⇒ + noSrvLookups.foreach { str => withClue(s"checking '$str'") { Lookup.isValidSrv(str) shouldBe false } @@ -85,7 +85,7 @@ class LookupSpec extends WordSpec with Matchers with OptionValues { } "return false if domain part in SRV String is an invalid domain name" in { - srvWithInvalidDomainNames.foreach { str ⇒ + srvWithInvalidDomainNames.foreach { str => withClue(s"checking '$str'") { Lookup.isValidSrv(str) shouldBe false } diff --git a/akka-discovery/src/test/scala/akka/discovery/dns/DnsServiceDiscoverySpec.scala b/akka-discovery/src/test/scala/akka/discovery/dns/DnsServiceDiscoverySpec.scala index 7c8001d0d6..4ad0e5ad6e 100644 --- a/akka-discovery/src/test/scala/akka/discovery/dns/DnsServiceDiscoverySpec.scala +++ b/akka-discovery/src/test/scala/akka/discovery/dns/DnsServiceDiscoverySpec.scala @@ -12,7 +12,7 @@ import akka.io.dns.CachePolicy.Ttl import akka.io.dns.{ AAAARecord, ARecord, DnsProtocol, SRVRecord } import org.scalatest.{ Matchers, WordSpec } -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } import scala.concurrent.duration._ class DnsServiceDiscoverySpec extends WordSpec with Matchers { diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/DeltaPropagationSelector.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/DeltaPropagationSelector.scala index 29a0551eb3..49f140c492 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/DeltaPropagationSelector.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/DeltaPropagationSelector.scala @@ -35,21 +35,21 @@ import akka.util.ccompat._ def maxDeltaSize: Int def currentVersion(key: KeyId): Long = deltaCounter.get(key) match { - case Some(v) ⇒ v - case None ⇒ 0L + case Some(v) => v + case None => 0L } def update(key: KeyId, delta: ReplicatedData): Unit = { // bump the counter for each update val version = deltaCounter.get(key) match { - case Some(c) ⇒ c + 1 - case None ⇒ 1L + case Some(c) => c + 1 + case None => 1L } deltaCounter = deltaCounter.updated(key, version) val deltaEntriesForKey = deltaEntries.get(key) match { - case Some(m) ⇒ m - case None ⇒ TreeMap.empty[Long, ReplicatedData] + case Some(m) => m + case None => TreeMap.empty[Long, ReplicatedData] } deltaEntries = deltaEntries.updated(key, deltaEntriesForKey.updated(version, delta)) @@ -91,12 +91,12 @@ import akka.util.ccompat._ var result = Map.empty[Address, DeltaPropagation] var cache = Map.empty[(KeyId, Long, Long), ReplicatedData] - slice.foreach { node ⇒ + slice.foreach { node => // collect the deltas that have not already been sent to the node and merge // them into a delta group var deltas = Map.empty[KeyId, (ReplicatedData, Long, Long)] deltaEntries.foreach { - case (key, entries) ⇒ + case (key, entries) => val deltaSentToNodeForKey = deltaSentToNode.getOrElse(key, TreeMap.empty[Address, Long]) val j = deltaSentToNodeForKey.getOrElse(node, 0L) val deltaEntriesAfterJ = deltaEntriesAfter(entries, j) @@ -107,25 +107,25 @@ import akka.util.ccompat._ // so we cache the merged results val cacheKey = (key, fromSeqNr, toSeqNr) val deltaGroup = cache.get(cacheKey) match { - case None ⇒ + case None => val group = deltaEntriesAfterJ.valuesIterator.reduceLeft { - (d1, d2) ⇒ + (d1, d2) => val merged = d2 match { - case NoDeltaPlaceholder ⇒ NoDeltaPlaceholder - case _ ⇒ + case NoDeltaPlaceholder => NoDeltaPlaceholder + case _ => // this is fine also if d1 is a NoDeltaPlaceholder d1.merge(d2.asInstanceOf[d1.T]) } merged match { - case s: ReplicatedDeltaSize if s.deltaSize >= maxDeltaSize ⇒ + case s: ReplicatedDeltaSize if s.deltaSize >= maxDeltaSize => // discard too large deltas NoDeltaPlaceholder - case _ ⇒ merged + case _ => merged } } cache = cache.updated(cacheKey, group) group - case Some(group) ⇒ group + case Some(group) => group } deltas = deltas.updated(key, (deltaGroup, fromSeqNr, toSeqNr)) deltaSentToNode = deltaSentToNode.updated(key, deltaSentToNodeForKey.updated(node, deltaEntriesAfterJ.lastKey)) @@ -146,24 +146,24 @@ import akka.util.ccompat._ private def deltaEntriesAfter(entries: TreeMap[Long, ReplicatedData], version: Long): TreeMap[Long, ReplicatedData] = entries.rangeFrom(version) match { - case ntrs if ntrs.isEmpty ⇒ ntrs - case ntrs if ntrs.firstKey == version ⇒ ntrs.tail // exclude first, i.e. version j that was already sent - case ntrs ⇒ ntrs + case ntrs if ntrs.isEmpty => ntrs + case ntrs if ntrs.firstKey == version => ntrs.tail // exclude first, i.e. version j that was already sent + case ntrs => ntrs } def hasDeltaEntries(key: KeyId): Boolean = { deltaEntries.get(key) match { - case Some(m) ⇒ m.nonEmpty - case None ⇒ false + case Some(m) => m.nonEmpty + case None => false } } private def findSmallestVersionPropagatedToAllNodes(key: KeyId, all: Vector[Address]): Long = { deltaSentToNode.get(key) match { - case None ⇒ 0L - case Some(deltaSentToNodeForKey) ⇒ + case None => 0L + case Some(deltaSentToNodeForKey) => if (deltaSentToNodeForKey.isEmpty) 0L - else if (all.exists(node ⇒ !deltaSentToNodeForKey.contains(node))) 0L + else if (all.exists(node => !deltaSentToNodeForKey.contains(node))) 0L else deltaSentToNodeForKey.valuesIterator.min } } @@ -174,22 +174,22 @@ import akka.util.ccompat._ deltaEntries = Map.empty else { deltaEntries = deltaEntries.map { - case (key, entries) ⇒ + case (key, entries) => val minVersion = findSmallestVersionPropagatedToAllNodes(key, all) val deltaEntriesAfterMin = deltaEntriesAfter(entries, minVersion) // TODO perhaps also remove oldest when deltaCounter is too far ahead (e.g. 10 cycles) - key → deltaEntriesAfterMin + key -> deltaEntriesAfterMin } } } def cleanupRemovedNode(address: Address): Unit = { deltaSentToNode = deltaSentToNode.map { - case (key, deltaSentToNodeForKey) ⇒ - key → (deltaSentToNodeForKey - address) + case (key, deltaSentToNodeForKey) => + key -> (deltaSentToNodeForKey - address) } } } diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/DurableStore.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/DurableStore.scala index fc4eff30b0..0e1174d61b 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/DurableStore.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/DurableStore.scala @@ -91,8 +91,8 @@ object DurableStore { override def toString(): String = s"DurableDataEnvelope($data)" override def hashCode(): Int = data.hashCode override def equals(o: Any): Boolean = o match { - case other: DurableDataEnvelope ⇒ data == other.data - case _ ⇒ false + case other: DurableDataEnvelope => data == other.data + case _ => false } } } @@ -120,14 +120,14 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { val manifest = serializer.manifest(new DurableDataEnvelope(Replicator.Internal.DeletedData)) val writeBehindInterval = config.getString("lmdb.write-behind-interval").toLowerCase match { - case "off" ⇒ Duration.Zero - case _ ⇒ config.getDuration("lmdb.write-behind-interval", MILLISECONDS).millis + case "off" => Duration.Zero + case _ => config.getDuration("lmdb.write-behind-interval", MILLISECONDS).millis } val dir = config.getString("lmdb.dir") match { - case path if path.endsWith("ddata") ⇒ + case path if path.endsWith("ddata") => new File(s"$path-${context.system.name}-${self.path.parent.name}-${Cluster(context.system).selfAddress.port.get}") - case path ⇒ + case path => new File(path) } @@ -135,8 +135,8 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { private var _lmdb: OptionVal[Lmdb] = OptionVal.None private def lmdb(): Lmdb = _lmdb match { - case OptionVal.Some(l) ⇒ l - case OptionVal.None ⇒ + case OptionVal.Some(l) => l + case OptionVal.None => val t0 = System.nanoTime() log.info("Using durable data in LMDB directory [{}]", dir.getCanonicalPath) val env = { @@ -195,7 +195,7 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { def receive = init def init: Receive = { - case LoadAll ⇒ + case LoadAll => if (dir.exists && dir.list().length > 0) { val l = lmdb() val t0 = System.nanoTime() @@ -204,7 +204,7 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { val iter = l.db.iterate(tx) try { var n = 0 - val loadData = LoadData(iter.asScala.map { entry ⇒ + val loadData = LoadData(iter.asScala.map { entry => n += 1 val keyArray = new Array[Byte](entry.key.remaining) entry.key.get(keyArray) @@ -212,7 +212,7 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { val valArray = new Array[Byte](entry.`val`.remaining) entry.`val`.get(valArray) val envelope = serializer.fromBinary(valArray, manifest).asInstanceOf[DurableDataEnvelope] - key → envelope + key -> envelope }.toMap) if (loadData.data.nonEmpty) sender() ! loadData @@ -225,7 +225,7 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { Try(iter.close()) } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => throw new LoadFailed("failed to load durable distributed-data", e) } finally { Try(tx.close()) @@ -238,7 +238,7 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { } def active: Receive = { - case Store(key, data, reply) ⇒ + case Store(key, data, reply) => try { lmdb() // init if (writeBehindInterval.length == 0) { @@ -249,21 +249,21 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { pending.put(key, data) } reply match { - case Some(StoreReply(successMsg, _, replyTo)) ⇒ + case Some(StoreReply(successMsg, _, replyTo)) => replyTo ! successMsg - case None ⇒ + case None => } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "failed to store [{}]", key) reply match { - case Some(StoreReply(_, failureMsg, replyTo)) ⇒ + case Some(StoreReply(_, failureMsg, replyTo)) => replyTo ! failureMsg - case None ⇒ + case None => } } - case WriteBehind ⇒ + case WriteBehind => writeBehind() } @@ -275,8 +275,8 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { l.keyBuffer.put(key.getBytes(ByteString.UTF_8)).flip() l.valueBuffer.put(value).flip() tx match { - case OptionVal.None ⇒ l.db.put(l.keyBuffer, l.valueBuffer) - case OptionVal.Some(t) ⇒ l.db.put(t, l.keyBuffer, l.valueBuffer) + case OptionVal.None => l.db.put(l.keyBuffer, l.valueBuffer) + case OptionVal.Some(t) => l.db.put(t, l.keyBuffer, l.valueBuffer) } } finally { val l = lmdb() @@ -300,7 +300,7 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { log.debug("store and commit of [{}] entries took [{} ms]", pending.size, TimeUnit.NANOSECONDS.toMillis(System.nanoTime - t0)) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => import scala.collection.JavaConverters._ log.error(e, "failed to store [{}]", pending.keySet.asScala.mkString(",")) tx.abort() diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/FastMerge.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/FastMerge.scala index 0ad3bd4525..d151ac1130 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/FastMerge.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/FastMerge.scala @@ -22,7 +22,7 @@ import akka.annotation.InternalApi * i.e. if used outside the Replicator infrastructure, but the worst thing that can happen is that * a full merge is performed instead of the fast forward merge. */ -@InternalApi private[akka] trait FastMerge { self: ReplicatedData ⇒ +@InternalApi private[akka] trait FastMerge { self: ReplicatedData => private var ancestor: FastMerge = null diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/GCounter.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/GCounter.scala index e16190aa83..dbc55dd5ae 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/GCounter.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/GCounter.scala @@ -54,7 +54,7 @@ final class GCounter private[akka] ( /** * Scala API: Current total value of the counter. */ - def value: BigInt = state.values.foldLeft(Zero) { (acc, v) ⇒ acc + v } + def value: BigInt = state.values.foldLeft(Zero) { (acc, v) => acc + v } /** * Java API: Current total value of the counter. @@ -92,14 +92,14 @@ final class GCounter private[akka] ( if (n == 0) this else { val nextValue = state.get(key) match { - case Some(v) ⇒ v + n - case None ⇒ n + case Some(v) => v + n + case None => n } val newDelta = delta match { - case None ⇒ new GCounter(Map(key → nextValue)) - case Some(d) ⇒ new GCounter(d.state + (key → nextValue)) + case None => new GCounter(Map(key -> nextValue)) + case Some(d) => new GCounter(d.state + (key -> nextValue)) } - assignAncestor(new GCounter(state + (key → nextValue), Some(newDelta))) + assignAncestor(new GCounter(state + (key -> nextValue), Some(newDelta))) } } @@ -108,7 +108,7 @@ final class GCounter private[akka] ( else if (this.isAncestorOf(that)) that.clearAncestor() else { var merged = that.state - for ((key, thisValue) ← state) { + for ((key, thisValue) <- state) { val thatValue = merged.getOrElse(key, Zero) if (thisValue > thatValue) merged = merged.updated(key, thisValue) @@ -132,8 +132,8 @@ final class GCounter private[akka] ( override def prune(removedNode: UniqueAddress, collapseInto: UniqueAddress): GCounter = state.get(removedNode) match { - case Some(value) ⇒ new GCounter(state - removedNode).increment(collapseInto, value) - case None ⇒ this + case Some(value) => new GCounter(state - removedNode).increment(collapseInto, value) + case None => this } override def pruningCleanup(removedNode: UniqueAddress): GCounter = @@ -144,8 +144,8 @@ final class GCounter private[akka] ( override def toString: String = s"GCounter($value)" override def equals(o: Any): Boolean = o match { - case other: GCounter ⇒ state == other.state - case _ ⇒ false + case other: GCounter => state == other.state + case _ => false } override def hashCode: Int = state.hashCode diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/GSet.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/GSet.scala index baa6821bb8..63e06d760d 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/GSet.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/GSet.scala @@ -61,8 +61,8 @@ final case class GSet[A] private (elements: Set[A])(override val delta: Option[G */ def add(element: A): GSet[A] = { val newDelta = delta match { - case Some(e) ⇒ Some(new GSet(e.elements + element)(None)) - case None ⇒ Some(new GSet[A](Set.apply[A](element))(None)) + case Some(e) => Some(new GSet(e.elements + element)(None)) + case None => Some(new GSet[A](Set.apply[A](element))(None)) } assignAncestor(new GSet[A](elements + element)(newDelta)) } diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/Key.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/Key.scala index fd985b6587..3b66339da4 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/Key.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/Key.scala @@ -27,8 +27,8 @@ object Key { abstract class Key[+T <: ReplicatedData](val id: Key.KeyId) extends Serializable { override final def equals(o: Any): Boolean = o match { - case k: Key[_] ⇒ id == k.id - case _ ⇒ false + case k: Key[_] => id == k.id + case _ => false } override final def hashCode: Int = id.hashCode diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/LWWMap.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/LWWMap.scala index 7ebda10fe2..d20f0f50c7 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/LWWMap.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/LWWMap.scala @@ -66,7 +66,7 @@ final class LWWMap[A, B] private[akka] ( /** * Scala API: All entries of the map. */ - def entries: Map[A, B] = underlying.entries.map { case (k, r) ⇒ k → r.value } + def entries: Map[A, B] = underlying.entries.map { case (k, r) => k -> r.value } /** * Java API: All entries of the map. @@ -140,8 +140,8 @@ final class LWWMap[A, B] private[akka] ( */ @InternalApi private[akka] def put(node: UniqueAddress, key: A, value: B, clock: Clock[B]): LWWMap[A, B] = { val newRegister = underlying.get(key) match { - case Some(r) ⇒ r.withValue(node, value, clock) - case None ⇒ LWWRegister(node, value, clock) + case Some(r) => r.withValue(node, value, clock) + case None => LWWRegister(node, value, clock) } new LWWMap(underlying.put(node, key, newRegister)) } @@ -200,8 +200,8 @@ final class LWWMap[A, B] private[akka] ( override def toString: String = s"LWW$entries" //e.g. LWWMap(a -> 1, b -> 2) override def equals(o: Any): Boolean = o match { - case other: LWWMap[_, _] ⇒ underlying == other.underlying - case _ ⇒ false + case other: LWWMap[_, _] => underlying == other.underlying + case _ => false } override def hashCode: Int = underlying.hashCode diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/LWWRegister.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/LWWRegister.scala index 005c40e845..b98e28096b 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/LWWRegister.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/LWWRegister.scala @@ -204,9 +204,9 @@ final class LWWRegister[A] private[akka] ( override def toString: String = s"LWWRegister($value)" override def equals(o: Any): Boolean = o match { - case other: LWWRegister[_] ⇒ + case other: LWWRegister[_] => timestamp == other.timestamp && value == other.value && node == other.node - case _ ⇒ false + case _ => false } override def hashCode: Int = { diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORMap.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORMap.scala index 09de5232d1..8fba388c14 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORMap.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORMap.scala @@ -57,8 +57,8 @@ object ORMap { def zeroTag: ZeroTag override def zero: DeltaReplicatedData = zeroTag.zero override def merge(that: DeltaOp): DeltaOp = that match { - case other: AtomicDeltaOp[A, B] ⇒ DeltaGroup(Vector(this, other)) - case DeltaGroup(ops) ⇒ DeltaGroup(this +: ops) + case other: AtomicDeltaOp[A, B] => DeltaGroup(Vector(this, other)) + case DeltaGroup(ops) => DeltaGroup(this +: ops) } override def deltaSize: Int = 1 } @@ -67,21 +67,21 @@ object ORMap { /** INTERNAL API */ @InternalApi private[akka] final case class PutDeltaOp[A, B <: ReplicatedData](underlying: ORSet.DeltaOp, value: (A, B), zeroTag: ZeroTag) extends AtomicDeltaOp[A, B] { override def merge(that: DeltaOp): DeltaOp = that match { - case put: PutDeltaOp[A, B] if this.value._1 == put.value._1 ⇒ + case put: PutDeltaOp[A, B] if this.value._1 == put.value._1 => new PutDeltaOp[A, B](this.underlying.merge(put.underlying), put.value, zeroTag) - case update: UpdateDeltaOp[A, B] if update.values.size == 1 && update.values.contains(this.value._1) ⇒ + case update: UpdateDeltaOp[A, B] if update.values.size == 1 && update.values.contains(this.value._1) => val (key, elem1) = this.value val newValue = elem1 match { - case e1: DeltaReplicatedData ⇒ + case e1: DeltaReplicatedData => val e2 = update.values.head._2.asInstanceOf[e1.D] (key, e1.mergeDelta(e2).asInstanceOf[B]) - case _ ⇒ + case _ => val elem2 = update.values.head._2.asInstanceOf[elem1.T] (key, elem1.merge(elem2).asInstanceOf[B]) } new PutDeltaOp[A, B](this.underlying.merge(update.underlying), newValue, zeroTag) - case other: AtomicDeltaOp[A, B] ⇒ DeltaGroup(Vector(this, other)) - case DeltaGroup(ops) ⇒ DeltaGroup(this +: ops) + case other: AtomicDeltaOp[A, B] => DeltaGroup(Vector(this, other)) + case DeltaGroup(ops) => DeltaGroup(this +: ops) } } @@ -89,23 +89,23 @@ object ORMap { /** INTERNAL API */ @InternalApi private[akka] final case class UpdateDeltaOp[A, B <: ReplicatedData](underlying: ORSet.DeltaOp, values: Map[A, B], zeroTag: ZeroTag) extends AtomicDeltaOp[A, B] { override def merge(that: DeltaOp): DeltaOp = that match { - case update: UpdateDeltaOp[A, B] ⇒ + case update: UpdateDeltaOp[A, B] => new UpdateDeltaOp[A, B]( this.underlying.merge(update.underlying), update.values.foldLeft(this.values) { - (map, pair) ⇒ + (map, pair) => val (key, value) = pair if (this.values.contains(key)) { val elem1 = this.values(key) val elem2 = value.asInstanceOf[elem1.T] - map + (key → elem1.merge(elem2).asInstanceOf[B]) + map + (key -> elem1.merge(elem2).asInstanceOf[B]) } else map + pair }, zeroTag) - case put: PutDeltaOp[A, B] if this.values.size == 1 && this.values.contains(put.value._1) ⇒ + case put: PutDeltaOp[A, B] if this.values.size == 1 && this.values.contains(put.value._1) => new PutDeltaOp[A, B](this.underlying.merge(put.underlying), put.value, zeroTag) - case other: AtomicDeltaOp[A, B] ⇒ DeltaGroup(Vector(this, other)) - case DeltaGroup(ops) ⇒ DeltaGroup(this +: ops) + case other: AtomicDeltaOp[A, B] => DeltaGroup(Vector(this, other)) + case DeltaGroup(ops) => DeltaGroup(this +: ops) } } @@ -122,23 +122,23 @@ object ORMap { @InternalApi private[akka] final case class DeltaGroup[A, B <: ReplicatedData](ops: immutable.IndexedSeq[DeltaOp]) extends DeltaOp with ReplicatedDeltaSize { override def merge(that: DeltaOp): DeltaOp = that match { - case that: AtomicDeltaOp[A, B] ⇒ + case that: AtomicDeltaOp[A, B] => ops.last match { - case thisPut: PutDeltaOp[A, B] ⇒ + case thisPut: PutDeltaOp[A, B] => val merged = thisPut.merge(that) merged match { - case op: AtomicDeltaOp[A, B] ⇒ DeltaGroup(ops.dropRight(1) :+ op) - case DeltaGroup(thatOps) ⇒ DeltaGroup(ops.dropRight(1) ++ thatOps) + case op: AtomicDeltaOp[A, B] => DeltaGroup(ops.dropRight(1) :+ op) + case DeltaGroup(thatOps) => DeltaGroup(ops.dropRight(1) ++ thatOps) } - case thisUpdate: UpdateDeltaOp[A, B] ⇒ + case thisUpdate: UpdateDeltaOp[A, B] => val merged = thisUpdate.merge(that) merged match { - case op: AtomicDeltaOp[A, B] ⇒ DeltaGroup(ops.dropRight(1) :+ op) - case DeltaGroup(thatOps) ⇒ DeltaGroup(ops.dropRight(1) ++ thatOps) + case op: AtomicDeltaOp[A, B] => DeltaGroup(ops.dropRight(1) :+ op) + case DeltaGroup(thatOps) => DeltaGroup(ops.dropRight(1) ++ thatOps) } - case _ ⇒ DeltaGroup(ops :+ that) + case _ => DeltaGroup(ops :+ that) } - case DeltaGroup(thatOps) ⇒ DeltaGroup(ops ++ thatOps) + case DeltaGroup(thatOps) => DeltaGroup(ops ++ thatOps) } override def zero: DeltaReplicatedData = ops.headOption.fold(ORMap.empty[A, B].asInstanceOf[DeltaReplicatedData])(_.zero) @@ -187,7 +187,7 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( * Scala API: Get the value associated with the key if there is one, * else return the given default. */ - def getOrElse(key: A, default: ⇒ B): B = values.getOrElse(key, default) + def getOrElse(key: A, default: => B): B = values.getOrElse(key, default) def contains(key: A): Boolean = values.contains(key) @@ -239,7 +239,7 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( "undesired effects of merging will occur. Use `ORMultiMap` or `ORMap.updated` instead.") else { val newKeys = keys.resetDelta.add(node, key) - val putDeltaOp = PutDeltaOp(newKeys.delta.get, key → value, zeroTag) + val putDeltaOp = PutDeltaOp(newKeys.delta.get, key -> value, zeroTag) // put forcibly damages history, so we consciously propagate full value that will overwrite previous value new ORMap(newKeys, values.updated(key, value), zeroTag, Some(newDelta(putDeltaOp))) } @@ -250,11 +250,11 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( * If there is no current value for the `key` the `initial` value will be * passed to the `modify` function. */ - def updated(node: SelfUniqueAddress, key: A, initial: B)(modify: B ⇒ B): ORMap[A, B] = + def updated(node: SelfUniqueAddress, key: A, initial: B)(modify: B => B): ORMap[A, B] = updated(node.uniqueAddress, key, initial)(modify) @deprecated("Use `updated` that takes a `SelfUniqueAddress` parameter instead.", since = "2.5.20") - def updated(node: Cluster, key: A, initial: B)(modify: B ⇒ B): ORMap[A, B] = + def updated(node: Cluster, key: A, initial: B)(modify: B => B): ORMap[A, B] = updated(node.selfUniqueAddress, key, initial)(modify) /** @@ -266,7 +266,7 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( @Deprecated @deprecated("use update for the Java API as updated is ambiguous with the Scala API", "2.5.20") def updated(node: Cluster, key: A, initial: B, modify: java.util.function.Function[B, B]): ORMap[A, B] = - updated(node.selfUniqueAddress, key, initial)(value ⇒ modify.apply(value)) + updated(node.selfUniqueAddress, key, initial)(value => modify.apply(value)) /** * Java API: Replace a value by applying the `modify` function on the existing value. @@ -275,20 +275,20 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( * passed to the `modify` function. */ def update(node: SelfUniqueAddress, key: A, initial: B, modify: java.util.function.Function[B, B]): ORMap[A, B] = - updated(node.uniqueAddress, key, initial)(value ⇒ modify.apply(value)) + updated(node.uniqueAddress, key, initial)(value => modify.apply(value)) @Deprecated @deprecated("Use `update` that takes a `SelfUniqueAddress` parameter instead.", since = "2.5.20") def update(node: Cluster, key: A, initial: B, modify: java.util.function.Function[B, B]): ORMap[A, B] = - updated(node, key, initial)(value ⇒ modify.apply(value)) + updated(node, key, initial)(value => modify.apply(value)) /** * INTERNAL API */ - @InternalApi private[akka] def updated(node: UniqueAddress, key: A, initial: B, valueDeltas: Boolean = false)(modify: B ⇒ B): ORMap[A, B] = { + @InternalApi private[akka] def updated(node: UniqueAddress, key: A, initial: B, valueDeltas: Boolean = false)(modify: B => B): ORMap[A, B] = { val (oldValue, hasOldValue) = values.get(key) match { - case Some(old) ⇒ (old, true) - case _ ⇒ (initial, false) + case Some(old) => (old, true) + case _ => (initial, false) } // Optimization: for some types - like GSet, GCounter, PNCounter and ORSet - that are delta based // we can emit (and later merge) their deltas instead of full updates. @@ -297,17 +297,17 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( // before removing the key - like e.g. ORMultiMap.emptyWithValueDeltas does val newKeys = keys.resetDelta.add(node, key) oldValue match { - case _: DeltaReplicatedData if valueDeltas ⇒ + case _: DeltaReplicatedData if valueDeltas => val newValue = modify(oldValue.asInstanceOf[DeltaReplicatedData].resetDelta.asInstanceOf[B]) val newValueDelta = newValue.asInstanceOf[DeltaReplicatedData].delta val deltaOp = newValueDelta match { - case Some(d) if hasOldValue ⇒ UpdateDeltaOp(newKeys.delta.get, Map(key → d), zeroTag) - case _ ⇒ PutDeltaOp(newKeys.delta.get, key → newValue, zeroTag) + case Some(d) if hasOldValue => UpdateDeltaOp(newKeys.delta.get, Map(key -> d), zeroTag) + case _ => PutDeltaOp(newKeys.delta.get, key -> newValue, zeroTag) } new ORMap(newKeys, values.updated(key, newValue), zeroTag, Some(newDelta(deltaOp))) - case _ ⇒ + case _ => val newValue = modify(oldValue) - val deltaOp = PutDeltaOp(newKeys.delta.get, key → newValue, zeroTag) + val deltaOp = PutDeltaOp(newKeys.delta.get, key -> newValue, zeroTag) new ORMap(newKeys, values.updated(key, newValue), zeroTag, Some(newDelta(deltaOp))) } } @@ -357,9 +357,9 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( private def dryMerge(that: ORMap[A, B], mergedKeys: ORSet[A], valueKeysIterator: Iterator[A]): ORMap[A, B] = { var mergedValues = Map.empty[A, B] - valueKeysIterator.foreach { key ⇒ + valueKeysIterator.foreach { key => (this.values.get(key), that.values.get(key)) match { - case (Some(thisValue), Some(thatValue)) ⇒ + case (Some(thisValue), Some(thatValue)) => if (thisValue.getClass != thatValue.getClass) { val errMsg = s"Wrong type for merging [$key] in [${getClass.getName}], existing type " + s"[${thisValue.getClass.getName}], got [${thatValue.getClass.getName}]" @@ -368,15 +368,15 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( // TODO can we get rid of these (safe) casts? val mergedValue = thisValue.merge(thatValue.asInstanceOf[thisValue.T]).asInstanceOf[B] mergedValues = mergedValues.updated(key, mergedValue) - case (Some(thisValue), None) ⇒ + case (Some(thisValue), None) => if (mergedKeys.contains(key)) mergedValues = mergedValues.updated(key, thisValue) // else thisValue is a tombstone, but we don't want to carry it forward, as the other side does not have the element at all - case (None, Some(thatValue)) ⇒ + case (None, Some(thatValue)) => if (mergedKeys.contains(key)) mergedValues = mergedValues.updated(key, thatValue) // else thatValue is a tombstone, but we don't want to carry it forward, as the other side does not have the element at all - case (None, None) ⇒ throw new IllegalStateException(s"missing value for $key") + case (None, None) => throw new IllegalStateException(s"missing value for $key") } } new ORMap(mergedKeys, mergedValues, zeroTag = zeroTag) @@ -404,52 +404,52 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( private def dryMergeDelta(thatDelta: ORMap.DeltaOp, withValueDeltas: Boolean = false): ORMap[A, B] = { def mergeValue(lvalue: ReplicatedData, rvalue: ReplicatedData): B = (lvalue, rvalue) match { - case (v: DeltaReplicatedData, delta: ReplicatedDelta) ⇒ + case (v: DeltaReplicatedData, delta: ReplicatedDelta) => v.mergeDelta(delta.asInstanceOf[v.D]).asInstanceOf[B] - case _ ⇒ + case _ => lvalue.merge(rvalue.asInstanceOf[lvalue.T]).asInstanceOf[B] } var mergedKeys: ORSet[A] = this.keys - var (mergedValues, tombstonedVals): (Map[A, B], Map[A, B]) = this.values.partition { case (k, _) ⇒ this.keys.contains(k) } + var (mergedValues, tombstonedVals): (Map[A, B], Map[A, B]) = this.values.partition { case (k, _) => this.keys.contains(k) } val processDelta: PartialFunction[ORMap.DeltaOp, Unit] = { - case putOp: PutDeltaOp[A, B] ⇒ + case putOp: PutDeltaOp[A, B] => val keyDelta = putOp.underlying mergedKeys = mergedKeys.mergeDelta(keyDelta) mergedValues = mergedValues + putOp.value // put is destructive and propagates only full values of B! - case removeOp: RemoveDeltaOp[A, B] ⇒ + case removeOp: RemoveDeltaOp[A, B] => val removedKey = removeOp.underlying match { // if op is RemoveDeltaOp then it must have exactly one element in the elements - case op: ORSet.RemoveDeltaOp[_] ⇒ op.underlying.elements.head.asInstanceOf[A] - case _ ⇒ throw new IllegalArgumentException("ORMap.RemoveDeltaOp must contain ORSet.RemoveDeltaOp inside") + case op: ORSet.RemoveDeltaOp[_] => op.underlying.elements.head.asInstanceOf[A] + case _ => throw new IllegalArgumentException("ORMap.RemoveDeltaOp must contain ORSet.RemoveDeltaOp inside") } mergedValues = mergedValues - removedKey mergedKeys = mergedKeys.mergeDelta(removeOp.underlying) // please note that if RemoveDeltaOp is not preceded by update clearing the value // anomalies may result - case removeKeyOp: RemoveKeyDeltaOp[A, B] ⇒ + case removeKeyOp: RemoveKeyDeltaOp[A, B] => // removeKeyOp tombstones values for later use if (mergedValues.contains(removeKeyOp.removedKey)) { - tombstonedVals = tombstonedVals + (removeKeyOp.removedKey → mergedValues(removeKeyOp.removedKey)) + tombstonedVals = tombstonedVals + (removeKeyOp.removedKey -> mergedValues(removeKeyOp.removedKey)) } mergedValues = mergedValues - removeKeyOp.removedKey mergedKeys = mergedKeys.mergeDelta(removeKeyOp.underlying) - case updateOp: UpdateDeltaOp[A, _] ⇒ + case updateOp: UpdateDeltaOp[A, _] => mergedKeys = mergedKeys.mergeDelta(updateOp.underlying) updateOp.values.foreach { - case (key, value) ⇒ + case (key, value) => if (mergedKeys.contains(key)) { if (mergedValues.contains(key)) { - mergedValues = mergedValues + (key → mergeValue(mergedValues(key), value)) + mergedValues = mergedValues + (key -> mergeValue(mergedValues(key), value)) } else if (tombstonedVals.contains(key)) { - mergedValues = mergedValues + (key → mergeValue(tombstonedVals(key), value)) + mergedValues = mergedValues + (key -> mergeValue(tombstonedVals(key), value)) } else { value match { - case _: ReplicatedDelta ⇒ - mergedValues = mergedValues + (key → mergeValue(value.asInstanceOf[ReplicatedDelta].zero, value)) - case _ ⇒ - mergedValues = mergedValues + (key → value.asInstanceOf[B]) + case _: ReplicatedDelta => + mergedValues = mergedValues + (key -> mergeValue(value.asInstanceOf[ReplicatedDelta].zero, value)) + case _ => + mergedValues = mergedValues + (key -> value.asInstanceOf[B]) } } } @@ -457,10 +457,10 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( } val processNestedDelta: PartialFunction[ORMap.DeltaOp, Unit] = { - case ORMap.DeltaGroup(ops) ⇒ + case ORMap.DeltaGroup(ops) => ops.foreach { processDelta.orElse { - case ORMap.DeltaGroup(args) ⇒ + case ORMap.DeltaGroup(args) => throw new IllegalStateException("Cannot nest DeltaGroups") } } @@ -490,32 +490,32 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( } private def newDelta(deltaOp: ORMap.DeltaOp) = delta match { - case Some(d) ⇒ + case Some(d) => d.merge(deltaOp) - case None ⇒ + case None => deltaOp } override def modifiedByNodes: Set[UniqueAddress] = { keys.modifiedByNodes union values.foldLeft(Set.empty[UniqueAddress]) { - case (acc, (_, data: RemovedNodePruning)) ⇒ acc union data.modifiedByNodes - case (acc, _) ⇒ acc + case (acc, (_, data: RemovedNodePruning)) => acc union data.modifiedByNodes + case (acc, _) => acc } } override def needPruningFrom(removedNode: UniqueAddress): Boolean = { keys.needPruningFrom(removedNode) || values.exists { - case (_, data: RemovedNodePruning) ⇒ data.needPruningFrom(removedNode) - case _ ⇒ false + case (_, data: RemovedNodePruning) => data.needPruningFrom(removedNode) + case _ => false } } override def prune(removedNode: UniqueAddress, collapseInto: UniqueAddress): ORMap[A, B] = { val prunedKeys = keys.prune(removedNode, collapseInto) val prunedValues = values.foldLeft(values) { - case (acc, (key, data: RemovedNodePruning)) if data.needPruningFrom(removedNode) ⇒ + case (acc, (key, data: RemovedNodePruning)) if data.needPruningFrom(removedNode) => acc.updated(key, data.prune(removedNode, collapseInto).asInstanceOf[B]) - case (acc, _) ⇒ acc + case (acc, _) => acc } new ORMap(prunedKeys, prunedValues, zeroTag = zeroTag) } @@ -523,9 +523,9 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( override def pruningCleanup(removedNode: UniqueAddress): ORMap[A, B] = { val pruningCleanupedKeys = keys.pruningCleanup(removedNode) val pruningCleanupedValues = values.foldLeft(values) { - case (acc, (key, data: RemovedNodePruning)) if data.needPruningFrom(removedNode) ⇒ + case (acc, (key, data: RemovedNodePruning)) if data.needPruningFrom(removedNode) => acc.updated(key, data.pruningCleanup(removedNode).asInstanceOf[B]) - case (acc, _) ⇒ acc + case (acc, _) => acc } new ORMap(pruningCleanupedKeys, pruningCleanupedValues, zeroTag = zeroTag) } @@ -535,8 +535,8 @@ final class ORMap[A, B <: ReplicatedData] private[akka] ( override def toString: String = s"OR$entries" override def equals(o: Any): Boolean = o match { - case other: ORMap[_, _] ⇒ keys == other.keys && values == other.values - case _ ⇒ false + case other: ORMap[_, _] => keys == other.keys && values == other.values + case _ => false } override def hashCode: Int = { diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORMultiMap.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORMultiMap.scala index 3e5b39566b..9c2b6fc1c1 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORMultiMap.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORMultiMap.scala @@ -48,8 +48,8 @@ object ORMultiMap { * Extract the [[ORMultiMap#entries]] of an `ORMultiMap`. */ def unapply[A, B <: ReplicatedData](value: Any): Option[Map[A, Set[B]]] = value match { - case m: ORMultiMap[A, B] @unchecked ⇒ Some(m.entries) - case _ ⇒ None + case m: ORMultiMap[A, B] @unchecked => Some(m.entries) + case _ => None } } @@ -75,7 +75,7 @@ final class ORMultiMap[A, B] private[akka] ( if (withValueDeltas) { val newUnderlying = underlying.mergeRetainingDeletedValues(that.underlying) // Garbage collect the tombstones we no longer need, i.e. those that have Set() as a value. - val newValues = newUnderlying.values.filterNot { case (key, value) ⇒ !newUnderlying.keys.contains(key) && value.isEmpty } + val newValues = newUnderlying.values.filterNot { case (key, value) => !newUnderlying.keys.contains(key) && value.isEmpty } new ORMultiMap[A, B](new ORMap(newUnderlying.keys, newValues, newUnderlying.zeroTag, newUnderlying.delta), withValueDeltas) } else new ORMultiMap(underlying.merge(that.underlying), withValueDeltas) @@ -85,9 +85,9 @@ final class ORMultiMap[A, B] private[akka] ( * Scala API: All entries of a multimap where keys are strings and values are sets. */ def entries: Map[A, Set[B]] = if (withValueDeltas) - underlying.entries.collect { case (k, v) if underlying.keys.elements.contains(k) ⇒ k → v.elements } + underlying.entries.collect { case (k, v) if underlying.keys.elements.contains(k) => k -> v.elements } else - underlying.entries.map { case (k, v) ⇒ k → v.elements } + underlying.entries.map { case (k, v) => k -> v.elements } /** * Java API: All entries of a multimap where keys are strings and values are sets. @@ -96,9 +96,9 @@ final class ORMultiMap[A, B] private[akka] ( import scala.collection.JavaConverters._ val result = new java.util.HashMap[A, java.util.Set[B]] if (withValueDeltas) - underlying.entries.foreach { case (k, v) ⇒ if (underlying.keys.elements.contains(k)) result.put(k, v.elements.asJava) } + underlying.entries.foreach { case (k, v) => if (underlying.keys.elements.contains(k)) result.put(k, v.elements.asJava) } else - underlying.entries.foreach { case (k, v) ⇒ result.put(k, v.elements.asJava) } + underlying.entries.foreach { case (k, v) => result.put(k, v.elements.asJava) } result } @@ -115,7 +115,7 @@ final class ORMultiMap[A, B] private[akka] ( * Scala API: Get the set associated with the key if there is one, * else return the given default. */ - def getOrElse(key: A, default: ⇒ Set[B]): Set[B] = + def getOrElse(key: A, default: => Set[B]): Set[B] = get(key).getOrElse(default) def contains(key: A): Boolean = underlying.keys.elements.contains(key) @@ -170,8 +170,8 @@ final class ORMultiMap[A, B] private[akka] ( * INTERNAL API */ @InternalApi private[akka] def put(node: UniqueAddress, key: A, value: Set[B]): ORMultiMap[A, B] = { - val newUnderlying = underlying.updated(node, key, ORSet.empty[B], valueDeltas = withValueDeltas) { existing ⇒ - value.foldLeft(existing.clear(node)) { (s, element) ⇒ s.add(node, element) } + val newUnderlying = underlying.updated(node, key, ORSet.empty[B], valueDeltas = withValueDeltas) { existing => + value.foldLeft(existing.clear(node)) { (s, element) => s.add(node, element) } } new ORMultiMap(newUnderlying, withValueDeltas) } @@ -203,7 +203,7 @@ final class ORMultiMap[A, B] private[akka] ( */ @InternalApi private[akka] def remove(node: UniqueAddress, key: A): ORMultiMap[A, B] = { if (withValueDeltas) { - val u = underlying.updated(node, key, ORSet.empty[B], valueDeltas = true) { existing ⇒ existing.clear(node) } + val u = underlying.updated(node, key, ORSet.empty[B], valueDeltas = true) { existing => existing.clear(node) } new ORMultiMap(u.removeKey(node, key), withValueDeltas) } else { new ORMultiMap(underlying.remove(node, key), withValueDeltas) @@ -263,12 +263,12 @@ final class ORMultiMap[A, B] private[akka] ( val newUnderlying = { val u = underlying.updated(node, key, ORSet.empty[B], valueDeltas = withValueDeltas)(_.remove(node, element)) u.get(key) match { - case Some(s) if s.isEmpty ⇒ + case Some(s) if s.isEmpty => if (withValueDeltas) u.removeKey(node, key) else u.remove(node, key) - case _ ⇒ u + case _ => u } } new ORMultiMap(newUnderlying, withValueDeltas) @@ -307,7 +307,7 @@ final class ORMultiMap[A, B] private[akka] ( if (withValueDeltas) { val newUnderlying = underlying.mergeDeltaRetainingDeletedValues(thatDelta) // Garbage collect the tombstones we no longer need, i.e. those that have Set() as a value. - val newValues = newUnderlying.values.filterNot { case (key, value) ⇒ !newUnderlying.keys.contains(key) && value.isEmpty } + val newValues = newUnderlying.values.filterNot { case (key, value) => !newUnderlying.keys.contains(key) && value.isEmpty } new ORMultiMap[A, B](new ORMap(newUnderlying.keys, newValues, newUnderlying.zeroTag, newUnderlying.delta), withValueDeltas) } else new ORMultiMap(underlying.mergeDelta(thatDelta), withValueDeltas) @@ -329,8 +329,8 @@ final class ORMultiMap[A, B] private[akka] ( override def toString: String = s"ORMulti$entries" override def equals(o: Any): Boolean = o match { - case other: ORMultiMap[_, _] ⇒ underlying == other.underlying - case _ ⇒ false + case other: ORMultiMap[_, _] => underlying == other.underlying + case _ => false } override def hashCode: Int = underlying.hashCode diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORSet.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORSet.scala index 262b9c75dd..ea37217016 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORSet.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/ORSet.scala @@ -30,8 +30,8 @@ object ORSet { * Extract the [[ORSet#elements]] of an `ORSet`. */ def unapply(a: ReplicatedData): Option[Set[Any]] = a match { - case s: ORSet[Any] @unchecked ⇒ Some(s.elements) - case _ ⇒ None + case s: ORSet[Any] @unchecked => Some(s.elements) + case _ => None } /** @@ -56,13 +56,13 @@ object ORSet { @InternalApi private[akka] final case class AddDeltaOp[A](underlying: ORSet[A]) extends AtomicDeltaOp[A] { override def merge(that: DeltaOp): DeltaOp = that match { - case AddDeltaOp(u) ⇒ + case AddDeltaOp(u) => // Note that we only merge deltas originating from the same node AddDeltaOp(new ORSet( concatElementsMap(u.elementsMap.asInstanceOf[Map[A, Dot]]), underlying.vvector.merge(u.vvector))) - case _: AtomicDeltaOp[A] ⇒ DeltaGroup(Vector(this, that)) - case DeltaGroup(ops) ⇒ DeltaGroup(this +: ops) + case _: AtomicDeltaOp[A] => DeltaGroup(Vector(this, that)) + case DeltaGroup(ops) => DeltaGroup(this +: ops) } private def concatElementsMap(thatMap: Map[A, Dot]): Map[A, Dot] = { @@ -80,16 +80,16 @@ object ORSet { throw new IllegalArgumentException(s"RemoveDeltaOp should contain one removed element, but was $underlying") override def merge(that: DeltaOp): DeltaOp = that match { - case _: AtomicDeltaOp[A] ⇒ DeltaGroup(Vector(this, that)) // keep it simple for removals - case DeltaGroup(ops) ⇒ DeltaGroup(this +: ops) + case _: AtomicDeltaOp[A] => DeltaGroup(Vector(this, that)) // keep it simple for removals + case DeltaGroup(ops) => DeltaGroup(this +: ops) } } /** INTERNAL API: Used for `clear` but could be used for other cases also */ @InternalApi private[akka] final case class FullStateDeltaOp[A](underlying: ORSet[A]) extends AtomicDeltaOp[A] { override def merge(that: DeltaOp): DeltaOp = that match { - case _: AtomicDeltaOp[A] ⇒ DeltaGroup(Vector(this, that)) - case DeltaGroup(ops) ⇒ DeltaGroup(this +: ops) + case _: AtomicDeltaOp[A] => DeltaGroup(Vector(this, that)) + case DeltaGroup(ops) => DeltaGroup(this +: ops) } } @@ -99,14 +99,14 @@ object ORSet { @InternalApi private[akka] final case class DeltaGroup[A](ops: immutable.IndexedSeq[DeltaOp]) extends DeltaOp with ReplicatedDeltaSize { override def merge(that: DeltaOp): DeltaOp = that match { - case thatAdd: AddDeltaOp[A] ⇒ + case thatAdd: AddDeltaOp[A] => // merge AddDeltaOp into last AddDeltaOp in the group, if possible ops.last match { - case thisAdd: AddDeltaOp[A] ⇒ DeltaGroup(ops.dropRight(1) :+ thisAdd.merge(thatAdd)) - case _ ⇒ DeltaGroup(ops :+ thatAdd) + case thisAdd: AddDeltaOp[A] => DeltaGroup(ops.dropRight(1) :+ thisAdd.merge(thatAdd)) + case _ => DeltaGroup(ops :+ thatAdd) } - case DeltaGroup(thatOps) ⇒ DeltaGroup(ops ++ thatOps) - case _ ⇒ DeltaGroup(ops :+ that) + case DeltaGroup(thatOps) => DeltaGroup(ops ++ thatOps) + case _ => DeltaGroup(ops :+ that) } override def zero: ORSet[A] = ORSet.empty @@ -127,8 +127,8 @@ object ORSet { @tailrec def dropDots(remaining: List[(UniqueAddress, Long)], acc: List[(UniqueAddress, Long)]): List[(UniqueAddress, Long)] = remaining match { - case Nil ⇒ acc - case (d @ (node, v1)) :: rest ⇒ + case Nil => acc + case (d @ (node, v1)) :: rest => val v2 = vvector.versionAt(node) if (v2 >= v1) // dot is dominated by version vector, drop it @@ -141,12 +141,12 @@ object ORSet { VersionVector.empty else { dot match { - case OneVersionVector(node, v1) ⇒ + case OneVersionVector(node, v1) => // if dot is dominated by version vector, drop it if (vvector.versionAt(node) >= v1) VersionVector.empty else dot - case ManyVersionVector(vs) ⇒ + case ManyVersionVector(vs) => val remaining = vs.toList val newDots = dropDots(remaining, Nil) VersionVector(newDots) @@ -163,11 +163,11 @@ object ORSet { private def mergeCommonKeys[A](commonKeys: Iterator[A], lhs: ORSet[A], rhs: ORSet[A]): Map[A, ORSet.Dot] = { commonKeys.foldLeft(Map.empty[A, ORSet.Dot]) { - case (acc, k) ⇒ + case (acc, k) => val lhsDots = lhs.elementsMap(k) val rhsDots = rhs.elementsMap(k) (lhsDots, rhsDots) match { - case (OneVersionVector(n1, v1), OneVersionVector(n2, v2)) ⇒ + case (OneVersionVector(n1, v1), OneVersionVector(n2, v2)) => if (n1 == n2 && v1 == v2) // one single common dot acc.updated(k, lhsDots) @@ -180,9 +180,9 @@ object ORSet { if (merged.isEmpty) acc else acc.updated(k, merged) } - case (ManyVersionVector(lhsVs), ManyVersionVector(rhsVs)) ⇒ + case (ManyVersionVector(lhsVs), ManyVersionVector(rhsVs)) => val commonDots = lhsVs.filter { - case (thisDotNode, v) ⇒ rhsVs.get(thisDotNode).exists(_ == v) + case (thisDotNode, v) => rhsVs.get(thisDotNode).exists(_ == v) } val commonDotsKeys = commonDots.keys val lhsUniqueDots = lhsVs -- commonDotsKeys @@ -193,9 +193,9 @@ object ORSet { // Perfectly possible that an item in both sets should be dropped if (merged.isEmpty) acc else acc.updated(k, merged) - case (ManyVersionVector(lhsVs), OneVersionVector(n2, v2)) ⇒ + case (ManyVersionVector(lhsVs), OneVersionVector(n2, v2)) => val commonDots = lhsVs.filter { - case (n1, v1) ⇒ v1 == v2 && n1 == n2 + case (n1, v1) => v1 == v2 && n1 == n2 } val commonDotsKeys = commonDots.keys val lhsUniqueDots = lhsVs -- commonDotsKeys @@ -206,9 +206,9 @@ object ORSet { // Perfectly possible that an item in both sets should be dropped if (merged.isEmpty) acc else acc.updated(k, merged) - case (OneVersionVector(n1, v1), ManyVersionVector(rhsVs)) ⇒ + case (OneVersionVector(n1, v1), ManyVersionVector(rhsVs)) => val commonDots = rhsVs.filter { - case (n2, v2) ⇒ v1 == v2 && n1 == n2 + case (n2, v2) => v1 == v2 && n1 == n2 } val commonDotsKeys = commonDots.keys val lhsUnique = if (commonDotsKeys.isEmpty) lhsDots else VersionVector.empty @@ -235,7 +235,7 @@ object ORSet { private def mergeDisjointKeys[A](keys: Iterator[A], elementsMap: Map[A, ORSet.Dot], vvector: VersionVector, accumulator: Map[A, ORSet.Dot]): Map[A, ORSet.Dot] = { keys.foldLeft(accumulator) { - case (acc, k) ⇒ + case (acc, k) => val dots = elementsMap(k) if (vvector > dots || vvector == dots) acc @@ -327,12 +327,12 @@ final class ORSet[A] private[akka] ( val newVvector = vvector + node val newDot = VersionVector(node, newVvector.versionAt(node)) val newDelta = delta match { - case None ⇒ - ORSet.AddDeltaOp(new ORSet(Map(element → newDot), newDot)) - case Some(existing: ORSet.AddDeltaOp[A]) ⇒ - existing.merge(ORSet.AddDeltaOp(new ORSet(Map(element → newDot), newDot))) - case Some(d) ⇒ - d.merge(ORSet.AddDeltaOp(new ORSet(Map(element → newDot), newDot))) + case None => + ORSet.AddDeltaOp(new ORSet(Map(element -> newDot), newDot)) + case Some(existing: ORSet.AddDeltaOp[A]) => + existing.merge(ORSet.AddDeltaOp(new ORSet(Map(element -> newDot), newDot))) + case Some(d) => + d.merge(ORSet.AddDeltaOp(new ORSet(Map(element -> newDot), newDot))) } assignAncestor(new ORSet(elementsMap.updated(element, newDot), newVvector, Some(newDelta))) } @@ -366,10 +366,10 @@ final class ORSet[A] private[akka] ( */ @InternalApi private[akka] def remove(node: UniqueAddress, element: A): ORSet[A] = { val deltaDot = VersionVector(node, vvector.versionAt(node)) - val rmOp = ORSet.RemoveDeltaOp(new ORSet(Map(element → deltaDot), vvector)) + val rmOp = ORSet.RemoveDeltaOp(new ORSet(Map(element -> deltaDot), vvector)) val newDelta = delta match { - case None ⇒ rmOp - case Some(d) ⇒ d.merge(rmOp) + case None => rmOp + case Some(d) => d.merge(rmOp) } assignAncestor(copy(elementsMap = elementsMap - element, delta = Some(newDelta))) } @@ -391,8 +391,8 @@ final class ORSet[A] private[akka] ( val newFullState = new ORSet[A](elementsMap = Map.empty, vvector) val clearOp = ORSet.FullStateDeltaOp(newFullState) val newDelta = delta match { - case None ⇒ clearOp - case Some(d) ⇒ d.merge(clearOp) + case None => clearOp + case Some(d) => d.merge(clearOp) } assignAncestor(newFullState.copy(delta = Some(newDelta))) } @@ -426,7 +426,7 @@ final class ORSet[A] private[akka] ( val entries00 = ORSet.mergeCommonKeys(commonKeys, this, that) val entries0 = if (addDeltaOp) - entries00 ++ this.elementsMap.filter { case (elem, _) ⇒ !that.elementsMap.contains(elem) } + entries00 ++ this.elementsMap.filter { case (elem, _) => !that.elementsMap.contains(elem) } else { val thisUniqueKeys = this.elementsMap.keysIterator.filterNot(that.elementsMap.contains) ORSet.mergeDisjointKeys(thisUniqueKeys, this.elementsMap, that.vvector, entries00) @@ -441,15 +441,15 @@ final class ORSet[A] private[akka] ( override def mergeDelta(thatDelta: ORSet.DeltaOp): ORSet[A] = { thatDelta match { - case d: ORSet.AddDeltaOp[A] ⇒ dryMerge(d.underlying, addDeltaOp = true) - case d: ORSet.RemoveDeltaOp[A] ⇒ mergeRemoveDelta(d) - case d: ORSet.FullStateDeltaOp[A] ⇒ dryMerge(d.underlying, addDeltaOp = false) - case ORSet.DeltaGroup(ops) ⇒ + case d: ORSet.AddDeltaOp[A] => dryMerge(d.underlying, addDeltaOp = true) + case d: ORSet.RemoveDeltaOp[A] => mergeRemoveDelta(d) + case d: ORSet.FullStateDeltaOp[A] => dryMerge(d.underlying, addDeltaOp = false) + case ORSet.DeltaGroup(ops) => ops.foldLeft(this) { - case (acc, op: ORSet.AddDeltaOp[A]) ⇒ acc.dryMerge(op.underlying, addDeltaOp = true) - case (acc, op: ORSet.RemoveDeltaOp[A]) ⇒ acc.mergeRemoveDelta(op) - case (acc, op: ORSet.FullStateDeltaOp[A]) ⇒ acc.dryMerge(op.underlying, addDeltaOp = false) - case (acc, op: ORSet.DeltaGroup[A]) ⇒ + case (acc, op: ORSet.AddDeltaOp[A]) => acc.dryMerge(op.underlying, addDeltaOp = true) + case (acc, op: ORSet.RemoveDeltaOp[A]) => acc.mergeRemoveDelta(op) + case (acc, op: ORSet.FullStateDeltaOp[A]) => acc.dryMerge(op.underlying, addDeltaOp = false) + case (acc, op: ORSet.DeltaGroup[A]) => throw new IllegalArgumentException("ORSet.DeltaGroup should not be nested") } } @@ -459,23 +459,23 @@ final class ORSet[A] private[akka] ( val that = thatDelta.underlying val (elem, thatDot) = that.elementsMap.head def deleteDots = that.vvector.versionsIterator - def deleteDotsNodes = deleteDots.map { case (dotNode, _) ⇒ dotNode } + def deleteDotsNodes = deleteDots.map { case (dotNode, _) => dotNode } val newElementsMap = { val thisDotOption = this.elementsMap.get(elem) val deleteDotsAreGreater = deleteDots.forall { - case (dotNode, dotV) ⇒ + case (dotNode, dotV) => thisDotOption match { - case Some(thisDot) ⇒ thisDot.versionAt(dotNode) <= dotV - case None ⇒ false + case Some(thisDot) => thisDot.versionAt(dotNode) <= dotV + case None => false } } if (deleteDotsAreGreater) { thisDotOption match { - case Some(thisDot) ⇒ - if (thisDot.versionsIterator.forall { case (thisDotNode, _) ⇒ deleteDotsNodes.contains(thisDotNode) }) + case Some(thisDot) => + if (thisDot.versionsIterator.forall { case (thisDotNode, _) => deleteDotsNodes.contains(thisDotNode) }) elementsMap - elem else elementsMap - case None ⇒ + case None => elementsMap } } else @@ -499,7 +499,7 @@ final class ORSet[A] private[akka] ( override def prune(removedNode: UniqueAddress, collapseInto: UniqueAddress): ORSet[A] = { val pruned = elementsMap.foldLeft(Map.empty[A, ORSet.Dot]) { - case (acc, (elem, dot)) ⇒ + case (acc, (elem, dot)) => if (dot.needPruningFrom(removedNode)) acc.updated(elem, dot.prune(removedNode, collapseInto)) else acc } @@ -509,14 +509,14 @@ final class ORSet[A] private[akka] ( // re-add elements that were pruned, to bump dots to right vvector val newSet = new ORSet(elementsMap = elementsMap ++ pruned, vvector = vvector.prune(removedNode, collapseInto)) pruned.keys.foldLeft(newSet) { - case (s, elem) ⇒ s.add(collapseInto, elem) + case (s, elem) => s.add(collapseInto, elem) } } } override def pruningCleanup(removedNode: UniqueAddress): ORSet[A] = { val updated = elementsMap.foldLeft(elementsMap) { - case (acc, (elem, dot)) ⇒ + case (acc, (elem, dot)) => if (dot.needPruningFrom(removedNode)) acc.updated(elem, dot.pruningCleanup(removedNode)) else acc } @@ -532,8 +532,8 @@ final class ORSet[A] private[akka] ( override def toString: String = s"OR$elements" override def equals(o: Any): Boolean = o match { - case other: ORSet[_] ⇒ vvector == other.vvector && elementsMap == other.elementsMap - case _ ⇒ false + case other: ORSet[_] => vvector == other.vvector && elementsMap == other.elementsMap + case _ => false } override def hashCode: Int = { diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/PNCounter.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/PNCounter.scala index 7d734c9e4a..09c4ea98d5 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/PNCounter.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/PNCounter.scala @@ -177,12 +177,12 @@ final class PNCounter private[akka] ( override def delta: Option[PNCounter] = { val incrementsDelta = increments.delta match { - case Some(d) ⇒ d - case None ⇒ GCounter.empty + case Some(d) => d + case None => GCounter.empty } val decrementsDelta = decrements.delta match { - case Some(d) ⇒ d - case None ⇒ GCounter.empty + case Some(d) => d + case None => GCounter.empty } Some(new PNCounter(incrementsDelta, decrementsDelta)) } @@ -219,9 +219,9 @@ final class PNCounter private[akka] ( override def toString: String = s"PNCounter($value)" override def equals(o: Any): Boolean = o match { - case other: PNCounter ⇒ + case other: PNCounter => increments == other.increments && decrements == other.decrements - case _ ⇒ false + case _ => false } override def hashCode: Int = { diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/PNCounterMap.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/PNCounterMap.scala index b584d3802c..6da2766fd4 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/PNCounterMap.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/PNCounterMap.scala @@ -47,12 +47,12 @@ final class PNCounterMap[A] private[akka] ( type D = ORMap.DeltaOp /** Scala API */ - def entries: Map[A, BigInt] = underlying.entries.map { case (k, c) ⇒ k → c.value } + def entries: Map[A, BigInt] = underlying.entries.map { case (k, c) => k -> c.value } /** Java API */ def getEntries: java.util.Map[A, BigInteger] = { import scala.collection.JavaConverters._ - underlying.entries.map { case (k, c) ⇒ k → c.value.bigInteger }.asJava + underlying.entries.map { case (k, c) => k -> c.value.bigInteger }.asJava } /** @@ -186,8 +186,8 @@ final class PNCounterMap[A] private[akka] ( override def toString: String = s"PNCounter$entries" override def equals(o: Any): Boolean = o match { - case other: PNCounterMap[A] ⇒ underlying == other.underlying - case _ ⇒ false + case other: PNCounterMap[A] => underlying == other.underlying + case _ => false } override def hashCode: Int = underlying.hashCode diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/PruningState.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/PruningState.scala index 2090be3bc7..632f3cffbf 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/PruningState.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/PruningState.scala @@ -32,10 +32,10 @@ import akka.annotation.InternalApi def merge(that: PruningState): PruningState = (this, that) match { - case (p1: PruningPerformed, p2: PruningPerformed) ⇒ if (p1.obsoleteTime >= p2.obsoleteTime) this else that - case (_: PruningPerformed, _) ⇒ this - case (_, _: PruningPerformed) ⇒ that - case (PruningInitialized(thisOwner, thisSeen), PruningInitialized(thatOwner, thatSeen)) ⇒ + case (p1: PruningPerformed, p2: PruningPerformed) => if (p1.obsoleteTime >= p2.obsoleteTime) this else that + case (_: PruningPerformed, _) => this + case (_, _: PruningPerformed) => that + case (PruningInitialized(thisOwner, thisSeen), PruningInitialized(thatOwner, thatSeen)) => if (thisOwner == thatOwner) PruningInitialized(thisOwner, thisSeen union thatSeen) else if (Member.addressOrdering.compare(thisOwner.address, thatOwner.address) > 0) diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/Replicator.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/Replicator.scala index 03f687a3b7..484db818e0 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/Replicator.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/Replicator.scala @@ -33,7 +33,7 @@ import akka.cluster.UniqueAddress import akka.serialization.SerializationExtension import akka.util.ByteString import com.typesafe.config.Config -import java.util.function.{ Function ⇒ JFunction } +import java.util.function.{ Function => JFunction } import akka.dispatch.Dispatchers import akka.actor.DeadLetterSuppression import akka.cluster.ddata.Key.KeyR @@ -70,13 +70,13 @@ object ReplicatorSettings { */ def apply(config: Config): ReplicatorSettings = { val dispatcher = config.getString("use-dispatcher") match { - case "" ⇒ Dispatchers.DefaultDispatcherId - case id ⇒ id + case "" => Dispatchers.DefaultDispatcherId + case id => id } val pruningInterval = toRootLowerCase(config.getString("pruning-interval")) match { - case "off" | "false" ⇒ Duration.Zero - case _ ⇒ config.getDuration("pruning-interval", MILLISECONDS).millis + case "off" | "false" => Duration.Zero + case _ => config.getDuration("pruning-interval", MILLISECONDS).millis } import scala.collection.JavaConverters._ @@ -108,7 +108,7 @@ object ReplicatorSettings { */ @InternalApi private[akka] def name(system: ActorSystem, modifier: Option[String]): String = { val name = system.settings.config.getString("akka.cluster.distributed-data.name") - modifier.map(s ⇒ s + name.take(1).toUpperCase + name.drop(1)).getOrElse(name) + modifier.map(s => s + name.take(1).toUpperCase + name.drop(1)).getOrElse(name) } } @@ -221,8 +221,8 @@ final class ReplicatorSettings( def withDispatcher(dispatcher: String): ReplicatorSettings = { val d = dispatcher match { - case "" ⇒ Dispatchers.DefaultDispatcherId - case id ⇒ id + case "" => Dispatchers.DefaultDispatcherId + case id => id } copy(dispatcher = d) } @@ -504,12 +504,12 @@ object Replicator { */ def apply[A <: ReplicatedData]( key: Key[A], initial: A, writeConsistency: WriteConsistency, - request: Option[Any] = None)(modify: A ⇒ A): Update[A] = + request: Option[Any] = None)(modify: A => A): Update[A] = Update(key, writeConsistency, request)(modifyWithInitial(initial, modify)) - private def modifyWithInitial[A <: ReplicatedData](initial: A, modify: A ⇒ A): Option[A] ⇒ A = { - case Some(data) ⇒ modify(data) - case None ⇒ modify(initial) + private def modifyWithInitial[A <: ReplicatedData](initial: A, modify: A => A): Option[A] => A = { + case Some(data) => modify(data) + case None => modify(initial) } } /** @@ -529,7 +529,7 @@ object Replicator { * for example not access `sender()` reference of an enclosing actor. */ final case class Update[A <: ReplicatedData](key: Key[A], writeConsistency: WriteConsistency, - request: Option[Any])(val modify: Option[A] ⇒ A) + request: Option[Any])(val modify: Option[A] => A) extends Command[A] with NoSerializationVerificationNeeded { /** @@ -541,7 +541,7 @@ object Replicator { */ def this( key: Key[A], initial: A, writeConsistency: WriteConsistency, modify: JFunction[A, A]) = - this(key, writeConsistency, None)(Update.modifyWithInitial(initial, data ⇒ modify.apply(data))) + this(key, writeConsistency, None)(Update.modifyWithInitial(initial, data => modify.apply(data))) /** * Java API: Modify value of local `Replicator` and replicate with given `writeConsistency`. @@ -556,7 +556,7 @@ object Replicator { */ def this( key: Key[A], initial: A, writeConsistency: WriteConsistency, request: Optional[Any], modify: JFunction[A, A]) = - this(key, writeConsistency, Option(request.orElse(null)))(Update.modifyWithInitial(initial, data ⇒ modify.apply(data))) + this(key, writeConsistency, Option(request.orElse(null)))(Update.modifyWithInitial(initial, data => modify.apply(data))) } @@ -720,8 +720,8 @@ object Replicator { def needPruningFrom(removedNode: UniqueAddress): Boolean = data match { - case r: RemovedNodePruning ⇒ r.needPruningFrom(removedNode) - case _ ⇒ false + case r: RemovedNodePruning => r.needPruningFrom(removedNode) + case _ => false } def initRemovedNodePruning(removed: UniqueAddress, owner: UniqueAddress): DataEnvelope = { @@ -732,18 +732,18 @@ object Replicator { def prune(from: UniqueAddress, pruningPerformed: PruningPerformed): DataEnvelope = { data match { - case dataWithRemovedNodePruning: RemovedNodePruning ⇒ + case dataWithRemovedNodePruning: RemovedNodePruning => require(pruning.contains(from)) pruning(from) match { - case PruningInitialized(owner, _) ⇒ + case PruningInitialized(owner, _) => val prunedData = dataWithRemovedNodePruning.prune(from, owner) copy(data = prunedData, pruning = pruning.updated(from, pruningPerformed), deltaVersions = cleanedDeltaVersions(from)) - case _ ⇒ + case _ => this } - case _ ⇒ this + case _ => this } } @@ -752,11 +752,11 @@ object Replicator { else { val mergedPruning = pruning.foldLeft(other.pruning) { - case (acc, (key, thisValue)) ⇒ + case (acc, (key, thisValue)) => acc.get(key) match { - case None ⇒ + case None => acc.updated(key, thisValue) - case Some(thatValue) ⇒ + case Some(thatValue) => acc.updated(key, thisValue merge thatValue) } } @@ -765,16 +765,16 @@ object Replicator { else { val currentTime = System.currentTimeMillis() mergedPruning.filter { - case (_, p: PruningPerformed) ⇒ !p.isObsolete(currentTime) - case _ ⇒ true + case (_, p: PruningPerformed) => !p.isObsolete(currentTime) + case _ => true } } } // cleanup and merge deltaVersions val removedNodes = filteredMergedPruning.keys - val cleanedDV = removedNodes.foldLeft(deltaVersions) { (acc, node) ⇒ acc.pruningCleanup(node) } - val cleanedOtherDV = removedNodes.foldLeft(other.deltaVersions) { (acc, node) ⇒ acc.pruningCleanup(node) } + val cleanedDV = removedNodes.foldLeft(deltaVersions) { (acc, node) => acc.pruningCleanup(node) } + val cleanedOtherDV = removedNodes.foldLeft(other.deltaVersions) { (acc, node) => acc.pruningCleanup(node) } val mergedDeltaVersions = cleanedDV.merge(cleanedOtherDV) // cleanup both sides before merging, `merge(otherData: ReplicatedData)` will cleanup other.data @@ -789,11 +789,11 @@ object Replicator { else { val mergedData = cleaned(otherData, pruning) match { - case d: ReplicatedDelta ⇒ data match { - case drd: DeltaReplicatedData ⇒ drd.mergeDelta(d.asInstanceOf[drd.D]) - case _ ⇒ throw new IllegalArgumentException("Expected DeltaReplicatedData") + case d: ReplicatedDelta => data match { + case drd: DeltaReplicatedData => drd.mergeDelta(d.asInstanceOf[drd.D]) + case _ => throw new IllegalArgumentException("Expected DeltaReplicatedData") } - case c ⇒ data.merge(c.asInstanceOf[data.T]) + case c => data.merge(c.asInstanceOf[data.T]) } if (data.getClass != mergedData.getClass) throw new IllegalArgumentException( @@ -803,15 +803,15 @@ object Replicator { } private def cleaned(c: ReplicatedData, p: Map[UniqueAddress, PruningState]): ReplicatedData = p.foldLeft(c) { - case (c: RemovedNodePruning, (removed, _: PruningPerformed)) ⇒ + case (c: RemovedNodePruning, (removed, _: PruningPerformed)) => if (c.needPruningFrom(removed)) c.pruningCleanup(removed) else c - case (c, _) ⇒ c + case (c, _) => c } def addSeen(node: Address): DataEnvelope = { var changed = false val newRemovedNodePruning = pruning.map { - case (removed, pruningState) ⇒ + case (removed, pruningState) => val newPruningState = pruningState.addSeen(node) changed = (newPruningState ne pruningState) || changed (removed, newPruningState) @@ -831,7 +831,7 @@ object Replicator { final case class Status(digests: Map[KeyId, Digest], chunk: Int, totChunks: Int) extends ReplicatorMessage { override def toString: String = (digests.map { - case (key, bytes) ⇒ key + " -> " + bytes.map(byte ⇒ f"$byte%02x").mkString("") + case (key, bytes) => key + " -> " + bytes.map(byte => f"$byte%02x").mkString("") }).mkString("Status(", ", ", ")") } final case class Gossip(updatedData: Map[KeyId, DataEnvelope], sendBack: Boolean) extends ReplicatorMessage @@ -1085,12 +1085,12 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog val hasDurableKeys = settings.durableKeys.nonEmpty val durable = settings.durableKeys.filterNot(_.endsWith("*")) - val durableWildcards = settings.durableKeys.collect { case k if k.endsWith("*") ⇒ k.dropRight(1) } + val durableWildcards = settings.durableKeys.collect { case k if k.endsWith("*") => k.dropRight(1) } val durableStore: ActorRef = if (hasDurableKeys) { val props = settings.durableStoreProps match { - case Right(p) ⇒ p - case Left((s, c)) ⇒ + case Right(p) => p + case Left((s, c)) => val clazz = context.system.asInstanceOf[ExtendedActorSystem].dynamicAccess.getClassFor[Actor](s).get Props(clazz, c).withDispatcher(c.getString("use-dispatcher")) } @@ -1111,10 +1111,10 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog // Important to include the pruning state in the deltas. For example if the delta is based // on an entry that has been pruned but that has not yet been performed on the target node. DeltaPropagation(selfUniqueAddress, reply = false, deltas.iterator.collect { - case (key, (d, fromSeqNr, toSeqNr)) if d != NoDeltaPlaceholder ⇒ + case (key, (d, fromSeqNr, toSeqNr)) if d != NoDeltaPlaceholder => getData(key) match { - case Some(envelope) ⇒ key → Delta(envelope.copy(data = d), fromSeqNr, toSeqNr) - case None ⇒ key → Delta(DataEnvelope(d), fromSeqNr, toSeqNr) + case Some(envelope) => key -> Delta(envelope.copy(data = d), fromSeqNr, toSeqNr) + case None => key -> Delta(DataEnvelope(d), fromSeqNr, toSeqNr) } }.toMap) } @@ -1200,7 +1200,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def fromDurableStore: Boolean = sender() == durableStore && sender() != context.system.deadLetters OneForOneStrategy()( ({ - case e @ (_: DurableStore.LoadFailed | _: ActorInitializationException) if fromDurableStore ⇒ + case e @ (_: DurableStore.LoadFailed | _: ActorInitializationException) if fromDurableStore => log.error(e, "Stopping distributed-data Replicator due to load or startup failure in durable store, caused by: {}", if (e.getCause eq null) "" else e.getCause.getMessage) context.stop(self) SupervisorStrategy.Stop @@ -1220,7 +1220,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def unstashAll(): Unit = { val originalReplyTo = replyTo stash.foreach { - case (msg, snd) ⇒ + case (msg, snd) => replyTo = snd normalReceive.applyOrElse(msg, unhandled) } @@ -1229,18 +1229,18 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog } { - case LoadData(data) ⇒ + case LoadData(data) => count += data.size data.foreach { - case (key, d) ⇒ + case (key, d) => write(key, d.dataEnvelope) match { - case Some(newEnvelope) ⇒ + case Some(newEnvelope) => if (newEnvelope ne d.dataEnvelope) durableStore ! Store(key, new DurableDataEnvelope(newEnvelope), None) - case None ⇒ + case None => } } - case LoadAllCompleted ⇒ + case LoadAllCompleted => log.debug( "Loading {} entries from durable store took {} ms, stashed {}", count, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime), stash.size) @@ -1248,51 +1248,51 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog unstashAll() self ! FlushChanges - case GetReplicaCount ⇒ + case GetReplicaCount => // 0 until durable data has been loaded, used by test replyTo ! ReplicaCount(0) - case RemovedNodePruningTick | FlushChanges | GossipTick ⇒ + case RemovedNodePruningTick | FlushChanges | GossipTick => // ignore scheduled ticks when loading durable data - case TestFullStateGossip(enabled) ⇒ + case TestFullStateGossip(enabled) => fullStateGossipEnabled = enabled - case m @ (_: Read | _: Write | _: Status | _: Gossip) ⇒ + case m @ (_: Read | _: Write | _: Status | _: Gossip) => // ignore gossip and replication when loading durable data log.debug("ignoring message [{}] when loading durable data", m.getClass.getName) - case msg: ClusterDomainEvent ⇒ normalReceive.applyOrElse(msg, unhandled) - case msg ⇒ - stash :+= (msg → replyTo) + case msg: ClusterDomainEvent => normalReceive.applyOrElse(msg, unhandled) + case msg => + stash :+= (msg -> replyTo) } } // MUST use replyTo instead of sender() and forward from normalReceive, because of the stash in load val normalReceive: Receive = { - case Get(key, consistency, req) ⇒ receiveGet(key, consistency, req) - case u @ Update(key, writeC, req) ⇒ receiveUpdate(key, u.modify, writeC, req) - case Read(key) ⇒ receiveRead(key) - case Write(key, envelope) ⇒ receiveWrite(key, envelope) - case ReadRepair(key, envelope) ⇒ receiveReadRepair(key, envelope) - case DeltaPropagation(from, reply, deltas) ⇒ receiveDeltaPropagation(from, reply, deltas) - case FlushChanges ⇒ receiveFlushChanges() - case DeltaPropagationTick ⇒ receiveDeltaPropagationTick() - case GossipTick ⇒ receiveGossipTick() - case ClockTick ⇒ receiveClockTick() - case Status(otherDigests, chunk, totChunks) ⇒ receiveStatus(otherDigests, chunk, totChunks) - case Gossip(updatedData, sendBack) ⇒ receiveGossip(updatedData, sendBack) - case Subscribe(key, subscriber) ⇒ receiveSubscribe(key, subscriber) - case Unsubscribe(key, subscriber) ⇒ receiveUnsubscribe(key, subscriber) - case Terminated(ref) ⇒ receiveTerminated(ref) - case MemberWeaklyUp(m) ⇒ receiveWeaklyUpMemberUp(m) - case MemberUp(m) ⇒ receiveMemberUp(m) - case MemberRemoved(m, _) ⇒ receiveMemberRemoved(m) - case evt: MemberEvent ⇒ receiveOtherMemberEvent(evt.member) - case UnreachableMember(m) ⇒ receiveUnreachable(m) - case ReachableMember(m) ⇒ receiveReachable(m) - case GetKeyIds ⇒ receiveGetKeyIds() - case Delete(key, consistency, req) ⇒ receiveDelete(key, consistency, req) - case RemovedNodePruningTick ⇒ receiveRemovedNodePruningTick() - case GetReplicaCount ⇒ receiveGetReplicaCount() - case TestFullStateGossip(enabled) ⇒ fullStateGossipEnabled = enabled + case Get(key, consistency, req) => receiveGet(key, consistency, req) + case u @ Update(key, writeC, req) => receiveUpdate(key, u.modify, writeC, req) + case Read(key) => receiveRead(key) + case Write(key, envelope) => receiveWrite(key, envelope) + case ReadRepair(key, envelope) => receiveReadRepair(key, envelope) + case DeltaPropagation(from, reply, deltas) => receiveDeltaPropagation(from, reply, deltas) + case FlushChanges => receiveFlushChanges() + case DeltaPropagationTick => receiveDeltaPropagationTick() + case GossipTick => receiveGossipTick() + case ClockTick => receiveClockTick() + case Status(otherDigests, chunk, totChunks) => receiveStatus(otherDigests, chunk, totChunks) + case Gossip(updatedData, sendBack) => receiveGossip(updatedData, sendBack) + case Subscribe(key, subscriber) => receiveSubscribe(key, subscriber) + case Unsubscribe(key, subscriber) => receiveUnsubscribe(key, subscriber) + case Terminated(ref) => receiveTerminated(ref) + case MemberWeaklyUp(m) => receiveWeaklyUpMemberUp(m) + case MemberUp(m) => receiveMemberUp(m) + case MemberRemoved(m, _) => receiveMemberRemoved(m) + case evt: MemberEvent => receiveOtherMemberEvent(evt.member) + case UnreachableMember(m) => receiveUnreachable(m) + case ReachableMember(m) => receiveReachable(m) + case GetKeyIds => receiveGetKeyIds() + case Delete(key, consistency, req) => receiveDelete(key, consistency, req) + case RemovedNodePruningTick => receiveRemovedNodePruningTick() + case GetReplicaCount => receiveGetReplicaCount() + case TestFullStateGossip(enabled) => fullStateGossipEnabled = enabled } def receiveGet(key: KeyR, consistency: ReadConsistency, req: Option[Any]): Unit = { @@ -1300,9 +1300,9 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog log.debug("Received Get for key [{}]", key) if (isLocalGet(consistency)) { val reply = localValue match { - case Some(DataEnvelope(DeletedData, _, _)) ⇒ DataDeleted(key, req) - case Some(DataEnvelope(data, _, _)) ⇒ GetSuccess(key, req)(data) - case None ⇒ NotFound(key, req) + case Some(DataEnvelope(DeletedData, _, _)) => DataDeleted(key, req) + case Some(DataEnvelope(data, _, _)) => GetSuccess(key, req)(data) + case None => NotFound(key, req) } replyTo ! reply } else @@ -1312,9 +1312,9 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def isLocalGet(readConsistency: ReadConsistency): Boolean = readConsistency match { - case ReadLocal ⇒ true - case _: ReadMajority | _: ReadAll ⇒ nodes.isEmpty - case _ ⇒ false + case ReadLocal => true + case _: ReadMajority | _: ReadAll => nodes.isEmpty + case _ => false } def receiveRead(key: KeyId): Unit = { @@ -1323,41 +1323,41 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def isLocalSender(): Boolean = !replyTo.path.address.hasGlobalScope - def receiveUpdate(key: KeyR, modify: Option[ReplicatedData] ⇒ ReplicatedData, + def receiveUpdate(key: KeyR, modify: Option[ReplicatedData] => ReplicatedData, writeConsistency: WriteConsistency, req: Option[Any]): Unit = { val localValue = getData(key.id) def deltaOrPlaceholder(d: DeltaReplicatedData): Option[ReplicatedDelta] = { d.delta match { - case s @ Some(_) ⇒ s - case None ⇒ Some(NoDeltaPlaceholder) + case s @ Some(_) => s + case None => Some(NoDeltaPlaceholder) } } Try { localValue match { - case Some(DataEnvelope(DeletedData, _, _)) ⇒ throw new DataDeleted(key, req) - case Some(envelope @ DataEnvelope(existing, _, _)) ⇒ + case Some(DataEnvelope(DeletedData, _, _)) => throw new DataDeleted(key, req) + case Some(envelope @ DataEnvelope(existing, _, _)) => modify(Some(existing)) match { - case d: DeltaReplicatedData if deltaCrdtEnabled ⇒ + case d: DeltaReplicatedData if deltaCrdtEnabled => (envelope.merge(d.resetDelta.asInstanceOf[existing.T]), deltaOrPlaceholder(d)) - case d ⇒ + case d => (envelope.merge(d.asInstanceOf[existing.T]), None) } - case None ⇒ modify(None) match { - case d: DeltaReplicatedData if deltaCrdtEnabled ⇒ + case None => modify(None) match { + case d: DeltaReplicatedData if deltaCrdtEnabled => (DataEnvelope(d.resetDelta), deltaOrPlaceholder(d)) - case d ⇒ (DataEnvelope(d), None) + case d => (DataEnvelope(d), None) } } } match { - case Success((envelope, delta)) ⇒ + case Success((envelope, delta)) => log.debug("Received Update for key [{}]", key) // handle the delta delta match { - case Some(d) ⇒ deltaPropagationSelector.update(key.id, d) - case None ⇒ // not DeltaReplicatedData + case Some(d) => deltaPropagationSelector.update(key.id, d) + case None => // not DeltaReplicatedData } // note that it's important to do deltaPropagationSelector.update before setData, @@ -1373,12 +1373,12 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog replyTo ! UpdateSuccess(key, req) } else { val (writeEnvelope, writeDelta) = delta match { - case Some(NoDeltaPlaceholder) ⇒ (newEnvelope, None) - case Some(d: RequiresCausalDeliveryOfDeltas) ⇒ + case Some(NoDeltaPlaceholder) => (newEnvelope, None) + case Some(d: RequiresCausalDeliveryOfDeltas) => val v = deltaPropagationSelector.currentVersion(key.id) (newEnvelope, Some(Delta(newEnvelope.copy(data = d), v, v))) - case Some(d) ⇒ (newEnvelope.copy(data = d), None) - case None ⇒ (newEnvelope, None) + case Some(d) => (newEnvelope.copy(data = d), None) + case None => (newEnvelope, None) } val writeAggregator = context.actorOf(WriteAggregator.props(key, writeEnvelope, writeDelta, writeConsistency, @@ -1389,10 +1389,10 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog Some(StoreReply(UpdateSuccess(key, req), StoreFailure(key, req), writeAggregator))) } } - case Failure(e: DataDeleted[_]) ⇒ + case Failure(e: DataDeleted[_]) => log.debug("Received Update for deleted key [{}]", key) replyTo ! e - case Failure(e) ⇒ + case Failure(e) => log.debug("Received Update for key [{}], failed: {}", key, e.getMessage) replyTo ! ModifyFailure(key, "Update failed: " + e.getMessage, e, req) } @@ -1403,9 +1403,9 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def isLocalUpdate(writeConsistency: WriteConsistency): Boolean = writeConsistency match { - case WriteLocal ⇒ true - case _: WriteMajority | _: WriteAll ⇒ nodes.isEmpty - case _ ⇒ false + case WriteLocal => true + case _: WriteMajority | _: WriteAll => nodes.isEmpty + case _ => false } def receiveWrite(key: KeyId, envelope: DataEnvelope): Unit = @@ -1413,13 +1413,13 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def writeAndStore(key: KeyId, writeEnvelope: DataEnvelope, reply: Boolean): Unit = { write(key, writeEnvelope) match { - case Some(newEnvelope) ⇒ + case Some(newEnvelope) => if (isDurable(key)) { val storeReply = if (reply) Some(StoreReply(WriteAck, WriteNack, replyTo)) else None durableStore ! Store(key, new DurableDataEnvelope(newEnvelope), storeReply) } else if (reply) replyTo ! WriteAck - case None ⇒ + case None => if (reply) replyTo ! WriteNack } @@ -1427,27 +1427,27 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def write(key: KeyId, writeEnvelope: DataEnvelope): Option[DataEnvelope] = { getData(key) match { - case someEnvelope @ Some(envelope) if envelope eq writeEnvelope ⇒ someEnvelope - case Some(DataEnvelope(DeletedData, _, _)) ⇒ Some(DeletedEnvelope) // already deleted - case Some(envelope @ DataEnvelope(existing, _, _)) ⇒ + case someEnvelope @ Some(envelope) if envelope eq writeEnvelope => someEnvelope + case Some(DataEnvelope(DeletedData, _, _)) => Some(DeletedEnvelope) // already deleted + case Some(envelope @ DataEnvelope(existing, _, _)) => try { // DataEnvelope will mergeDelta when needed val merged = envelope.merge(writeEnvelope).addSeen(selfAddress) Some(setData(key, merged)) } catch { - case e: IllegalArgumentException ⇒ + case e: IllegalArgumentException => log.warning( "Couldn't merge [{}], due to: {}", key, e.getMessage) None } - case None ⇒ + case None => // no existing data for the key val writeEnvelope2 = writeEnvelope.data match { - case d: ReplicatedDelta ⇒ + case d: ReplicatedDelta => val z = d.zero writeEnvelope.copy(data = z.mergeDelta(d.asInstanceOf[z.D])) - case _ ⇒ + case _ => writeEnvelope } @@ -1463,17 +1463,17 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def receiveGetKeyIds(): Unit = { val keys: Set[KeyId] = dataEntries.iterator.collect { - case (key, (DataEnvelope(data, _, _), _)) if data != DeletedData ⇒ key + case (key, (DataEnvelope(data, _, _), _)) if data != DeletedData => key }.to(immutable.Set) replyTo ! GetKeyIdsResult(keys) } def receiveDelete(key: KeyR, consistency: WriteConsistency, req: Option[Any]): Unit = { getData(key.id) match { - case Some(DataEnvelope(DeletedData, _, _)) ⇒ + case Some(DataEnvelope(DeletedData, _, _)) => // already deleted replyTo ! DataDeleted(key, req) - case _ ⇒ + case _ => setData(key.id, DeletedEnvelope) val durable = isDurable(key.id) if (isLocalUpdate(consistency)) { @@ -1524,12 +1524,12 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def getDigest(key: KeyId): Digest = { dataEntries.get(key) match { - case Some((envelope, LazyDigest)) ⇒ + case Some((envelope, LazyDigest)) => val d = digest(envelope) dataEntries = dataEntries.updated(key, (envelope, d)) d - case Some((_, digest)) ⇒ digest - case None ⇒ NotFoundDigest + case Some((_, digest)) => digest + case None => NotFoundDigest } } @@ -1540,18 +1540,18 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog ByteString.fromArray(MessageDigest.getInstance("SHA-1").digest(bytes)) } - def getData(key: KeyId): Option[DataEnvelope] = dataEntries.get(key).map { case (envelope, _) ⇒ envelope } + def getData(key: KeyId): Option[DataEnvelope] = dataEntries.get(key).map { case (envelope, _) => envelope } def getDeltaSeqNr(key: KeyId, fromNode: UniqueAddress): Long = dataEntries.get(key) match { - case Some((DataEnvelope(_, _, deltaVersions), _)) ⇒ deltaVersions.versionAt(fromNode) - case None ⇒ 0L + case Some((DataEnvelope(_, _, deltaVersions), _)) => deltaVersions.versionAt(fromNode) + case None => 0L } def isNodeRemoved(node: UniqueAddress, keys: Iterable[KeyId]): Boolean = { - removedNodes.contains(node) || (keys.exists(key ⇒ dataEntries.get(key) match { - case Some((DataEnvelope(_, pruning, _), _)) ⇒ pruning.contains(node) - case None ⇒ false + removedNodes.contains(node) || (keys.exists(key => dataEntries.get(key) match { + case Some((DataEnvelope(_, pruning, _), _)) => pruning.contains(node) + case None => false })) } @@ -1559,22 +1559,22 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def notify(keyId: KeyId, subs: mutable.Set[ActorRef]): Unit = { val key = subscriptionKeys(keyId) getData(keyId) match { - case Some(envelope) ⇒ + case Some(envelope) => val msg = if (envelope.data == DeletedData) Deleted(key) else Changed(key)(envelope.data) subs.foreach { _ ! msg } - case None ⇒ + case None => } } if (subscribers.nonEmpty) { - for (key ← changed; if subscribers.contains(key); subs ← subscribers.get(key)) + for (key <- changed; if subscribers.contains(key); subs <- subscribers.get(key)) notify(key, subs) } // Changed event is sent to new subscribers even though the key has not changed, // i.e. send current value if (newSubscribers.nonEmpty) { - for ((key, subs) ← newSubscribers) { + for ((key, subs) <- newSubscribers) { notify(key, subs) subs.foreach { subscribers.addBinding(key, _) } } @@ -1586,7 +1586,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def receiveDeltaPropagationTick(): Unit = { deltaPropagationSelector.collectPropagations().foreach { - case (node, deltaPropagation) ⇒ + case (node, deltaPropagation) => // TODO split it to several DeltaPropagation if too many entries if (deltaPropagation.deltas.nonEmpty) replica(node) ! deltaPropagation @@ -1602,7 +1602,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog val isDebugEnabled = log.isDebugEnabled if (isDebugEnabled) log.debug("Received DeltaPropagation from [{}], containing [{}]", fromNode.address, - deltas.collect { case (key, Delta(_, fromSeqNr, toSeqNr)) ⇒ s"$key $fromSeqNr-$toSeqNr" }.mkString(", ")) + deltas.collect { case (key, Delta(_, fromSeqNr, toSeqNr)) => s"$key $fromSeqNr-$toSeqNr" }.mkString(", ")) if (isNodeRemoved(fromNode, deltas.keys)) { // Late message from a removed node. @@ -1611,7 +1611,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog "Skipping DeltaPropagation from [{}] because that node has been removed", fromNode.address) } else { deltas.foreach { - case (key, Delta(envelope @ DataEnvelope(_: RequiresCausalDeliveryOfDeltas, _, _), fromSeqNr, toSeqNr)) ⇒ + case (key, Delta(envelope @ DataEnvelope(_: RequiresCausalDeliveryOfDeltas, _, _), fromSeqNr, toSeqNr)) => val currentSeqNr = getDeltaSeqNr(key, fromNode) if (currentSeqNr >= toSeqNr) { if (isDebugEnabled) log.debug( @@ -1630,13 +1630,13 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog val newEnvelope = envelope.copy(deltaVersions = VersionVector(fromNode, toSeqNr)) writeAndStore(key, newEnvelope, reply) } - case (key, Delta(envelope, _, _)) ⇒ + case (key, Delta(envelope, _, _)) => // causal delivery of deltas not needed, just apply it writeAndStore(key, envelope, reply) } } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // catching in case we need to support rolling upgrades that are // mixing nodes with incompatible delta-CRDT types log.warning("Couldn't process DeltaPropagation from [{}] due to {}", fromNode, e) @@ -1654,11 +1654,11 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def gossipTo(address: Address): Unit = { val to = replica(address) if (dataEntries.size <= maxDeltaElements) { - val status = Status(dataEntries.map { case (key, (_, _)) ⇒ (key, getDigest(key)) }, chunk = 0, totChunks = 1) + val status = Status(dataEntries.map { case (key, (_, _)) => (key, getDigest(key)) }, chunk = 0, totChunks = 1) to ! status } else { val totChunks = dataEntries.size / maxDeltaElements - for (_ ← 1 to math.min(totChunks, 10)) { + for (_ <- 1 to math.min(totChunks, 10)) { if (totChunks == statusTotChunks) statusCount += 1 else { @@ -1667,7 +1667,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog } val chunk = (statusCount % totChunks).toInt val status = Status(dataEntries.collect { - case (key, (_, _)) if math.abs(key.hashCode % totChunks) == chunk ⇒ (key, getDigest(key)) + case (key, (_, _)) if math.abs(key.hashCode % totChunks) == chunk => (key, getDigest(key)) }, chunk, totChunks) to ! status } @@ -1690,25 +1690,25 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog d != NotFoundDigest && d != otherDigest } val otherDifferentKeys = otherDigests.collect { - case (key, otherDigest) if isOtherDifferent(key, otherDigest) ⇒ key + case (key, otherDigest) if isOtherDifferent(key, otherDigest) => key } val otherKeys = otherDigests.keySet val myKeys = if (totChunks == 1) dataEntries.keySet - else dataEntries.keysIterator.filter(key ⇒ math.abs(key.hashCode % totChunks) == chunk).toSet + else dataEntries.keysIterator.filter(key => math.abs(key.hashCode % totChunks) == chunk).toSet val otherMissingKeys = myKeys diff otherKeys val keys = (otherDifferentKeys ++ otherMissingKeys).take(maxDeltaElements) if (keys.nonEmpty) { if (log.isDebugEnabled) log.debug("Sending gossip to [{}], containing [{}]", replyTo.path.address, keys.mkString(", ")) - val g = Gossip(keys.iterator.map(k ⇒ k → getData(k).get).toMap, sendBack = otherDifferentKeys.nonEmpty) + val g = Gossip(keys.iterator.map(k => k -> getData(k).get).toMap, sendBack = otherDifferentKeys.nonEmpty) replyTo ! g } val myMissingKeys = otherKeys diff myKeys if (myMissingKeys.nonEmpty) { if (log.isDebugEnabled) log.debug("Sending gossip status to [{}], requesting missing [{}]", replyTo.path.address, myMissingKeys.mkString(", ")) - val status = Status(myMissingKeys.iterator.map(k ⇒ k → NotFoundDigest).toMap, chunk, totChunks) + val status = Status(myMissingKeys.iterator.map(k => k -> NotFoundDigest).toMap, chunk, totChunks) replyTo ! status } } @@ -1718,14 +1718,14 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog log.debug("Received gossip from [{}], containing [{}]", replyTo.path.address, updatedData.keys.mkString(", ")) var replyData = Map.empty[KeyId, DataEnvelope] updatedData.foreach { - case (key, envelope) ⇒ + case (key, envelope) => val hadData = dataEntries.contains(key) writeAndStore(key, envelope, reply = false) if (sendBack) getData(key) match { - case Some(d) ⇒ + case Some(d) => if (hadData || d.pruning.nonEmpty) replyData = replyData.updated(key, d) - case None ⇒ + case None => } } if (sendBack && replyData.nonEmpty) @@ -1749,20 +1749,20 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog } def hasSubscriber(subscriber: ActorRef): Boolean = - (subscribers.exists { case (k, s) ⇒ s.contains(subscriber) }) || - (newSubscribers.exists { case (k, s) ⇒ s.contains(subscriber) }) + (subscribers.exists { case (k, s) => s.contains(subscriber) }) || + (newSubscribers.exists { case (k, s) => s.contains(subscriber) }) def receiveTerminated(ref: ActorRef): Unit = { if (ref == durableStore) { log.error("Stopping distributed-data Replicator because durable store terminated") context.stop(self) } else { - val keys1 = subscribers.collect { case (k, s) if s.contains(ref) ⇒ k } - keys1.foreach { key ⇒ subscribers.removeBinding(key, ref) } - val keys2 = newSubscribers.collect { case (k, s) if s.contains(ref) ⇒ k } - keys2.foreach { key ⇒ newSubscribers.removeBinding(key, ref) } + val keys1 = subscribers.collect { case (k, s) if s.contains(ref) => k } + keys1.foreach { key => subscribers.removeBinding(key, ref) } + val keys2 = newSubscribers.collect { case (k, s) if s.contains(ref) => k } + keys2.foreach { key => newSubscribers.removeBinding(key, ref) } - (keys1 ++ keys2).foreach { key ⇒ + (keys1 ++ keys2).foreach { key => if (!subscribers.contains(key) && !newSubscribers.contains(key)) subscriptionKeys -= key } @@ -1833,13 +1833,13 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog val knownNodes = nodes union weaklyUpNodes union removedNodes.keySet.map(_.address) val newRemovedNodes = dataEntries.foldLeft(Set.empty[UniqueAddress]) { - case (acc, (_, (envelope @ DataEnvelope(data: RemovedNodePruning, _, _), _))) ⇒ - acc union data.modifiedByNodes.filterNot(n ⇒ n == selfUniqueAddress || knownNodes(n.address)) - case (acc, _) ⇒ + case (acc, (_, (envelope @ DataEnvelope(data: RemovedNodePruning, _, _), _))) => + acc union data.modifiedByNodes.filterNot(n => n == selfUniqueAddress || knownNodes(n.address)) + case (acc, _) => acc } - newRemovedNodes.foreach { n ⇒ + newRemovedNodes.foreach { n => log.debug("Adding removed node [{}] from data", n) removedNodes = removedNodes.updated(n, allReachableClockTime) } @@ -1848,11 +1848,11 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def initRemovedNodePruning(): Unit = { // initiate pruning for removed nodes val removedSet: Set[UniqueAddress] = removedNodes.iterator.collect { - case (r, t) if ((allReachableClockTime - t) > maxPruningDisseminationNanos) ⇒ r + case (r, t) if ((allReachableClockTime - t) > maxPruningDisseminationNanos) => r }.to(immutable.Set) if (removedSet.nonEmpty) { - for ((key, (envelope, _)) ← dataEntries; removed ← removedSet) { + for ((key, (envelope, _)) <- dataEntries; removed <- removedSet) { def init(): Unit = { val newEnvelope = envelope.initRemovedNodePruning(removed, selfUniqueAddress) @@ -1862,13 +1862,13 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog if (envelope.needPruningFrom(removed)) { envelope.data match { - case dataWithRemovedNodePruning: RemovedNodePruning ⇒ + case dataWithRemovedNodePruning: RemovedNodePruning => envelope.pruning.get(removed) match { - case None ⇒ init() - case Some(PruningInitialized(owner, _)) if owner != selfUniqueAddress ⇒ init() - case _ ⇒ // already in progress + case None => init() + case Some(PruningInitialized(owner, _)) if owner != selfUniqueAddress => init() + case _ => // already in progress } - case _ ⇒ + case _ => } } } @@ -1881,36 +1881,36 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog val pruningPerformed = PruningPerformed(System.currentTimeMillis() + pruningMarkerTimeToLive.toMillis) val durablePruningPerformed = PruningPerformed(System.currentTimeMillis() + durablePruningMarkerTimeToLive.toMillis) dataEntries.foreach { - case (key, (envelope @ DataEnvelope(data: RemovedNodePruning, pruning, _), _)) ⇒ + case (key, (envelope @ DataEnvelope(data: RemovedNodePruning, pruning, _), _)) => pruning.foreach { case (removed, PruningInitialized(owner, seen)) if owner == selfUniqueAddress - && (allNodes.isEmpty || allNodes.forall(seen)) ⇒ + && (allNodes.isEmpty || allNodes.forall(seen)) => val newEnvelope = envelope.prune(removed, if (isDurable(key)) durablePruningPerformed else pruningPerformed) log.debug("Perform pruning of [{}] from [{}] to [{}]", key, removed, selfUniqueAddress) setData(key, newEnvelope) if ((newEnvelope.data ne data) && isDurable(key)) durableStore ! Store(key, new DurableDataEnvelope(newEnvelope), None) - case _ ⇒ + case _ => } - case _ ⇒ // deleted, or pruning not needed + case _ => // deleted, or pruning not needed } } def deleteObsoletePruningPerformed(): Unit = { val currentTime = System.currentTimeMillis() dataEntries.foreach { - case (key, (envelope @ DataEnvelope(_: RemovedNodePruning, pruning, _), _)) ⇒ + case (key, (envelope @ DataEnvelope(_: RemovedNodePruning, pruning, _), _)) => val newEnvelope = pruning.foldLeft(envelope) { - case (acc, (removed, p: PruningPerformed)) if p.isObsolete(currentTime) ⇒ + case (acc, (removed, p: PruningPerformed)) if p.isObsolete(currentTime) => log.debug("Removing obsolete pruning marker for [{}] in [{}]", removed, key) removedNodes -= removed acc.copy(pruning = acc.pruning - removed) - case (acc, _) ⇒ acc + case (acc, _) => acc } if (newEnvelope ne envelope) setData(key, newEnvelope) - case _ ⇒ // deleted, or pruning not needed + case _ => // deleted, or pruning not needed } } @@ -2026,20 +2026,20 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog override def timeout: FiniteDuration = consistency.timeout override val doneWhenRemainingSize = consistency match { - case WriteTo(n, _) ⇒ nodes.size - (n - 1) - case _: WriteAll ⇒ 0 - case WriteMajority(_, minCap) ⇒ + case WriteTo(n, _) => nodes.size - (n - 1) + case _: WriteAll => 0 + case WriteMajority(_, minCap) => val N = nodes.size + 1 val w = calculateMajorityWithMinCap(minCap, N) N - w - case WriteLocal ⇒ + case WriteLocal => throw new IllegalArgumentException("WriteLocal not supported by WriteAggregator") } val writeMsg = Write(key.id, envelope) val deltaMsg = delta match { - case None ⇒ None - case Some(d) ⇒ Some(DeltaPropagation(selfUniqueAddress, reply = true, Map(key.id → d))) + case None => None + case Some(d) => Some(DeltaPropagation(selfUniqueAddress, reply = true, Map(key.id -> d))) } var gotLocalStoreReply = !durable @@ -2047,16 +2047,16 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog private val (primaryNodes, secondaryNodes) = { val requiresCausalDeliveryOfDeltas = delta match { - case None ⇒ false - case Some(d) ⇒ d.dataEnvelope.data.isInstanceOf[RequiresCausalDeliveryOfDeltas] + case None => false + case Some(d) => d.dataEnvelope.data.isInstanceOf[RequiresCausalDeliveryOfDeltas] } primaryAndSecondaryNodes(requiresCausalDeliveryOfDeltas) } override def preStart(): Unit = { val msg = deltaMsg match { - case Some(d) ⇒ d - case None ⇒ writeMsg + case Some(d) => d + case None => writeMsg } primaryNodes.foreach { replica(_) ! msg } @@ -2064,37 +2064,37 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog } def receive: Receive = { - case WriteAck ⇒ + case WriteAck => remaining -= senderAddress() if (isDone) reply(isTimeout = false) - case WriteNack ⇒ + case WriteNack => gotWriteNackFrom += senderAddress() if (isDone) reply(isTimeout = false) - case DeltaNack ⇒ + case DeltaNack => // Deltas must be applied in order and we can't keep track of ordering of // simultaneous updates so there is a chance that the delta could not be applied. // Try again with the full state sender() ! writeMsg - case _: Replicator.UpdateSuccess[_] ⇒ + case _: Replicator.UpdateSuccess[_] => gotLocalStoreReply = true if (isDone) reply(isTimeout = false) - case f: Replicator.StoreFailure[_] ⇒ + case f: Replicator.StoreFailure[_] => gotLocalStoreReply = true gotWriteNackFrom += selfUniqueAddress.address if (isDone) reply(isTimeout = false) - case SendToSecondary ⇒ + case SendToSecondary => deltaMsg match { - case None ⇒ - case Some(d) ⇒ + case None => + case Some(d) => // Deltas must be applied in order and we can't keep track of ordering of // simultaneous updates so there is a chance that the delta could not be applied. // Try again with the full state to the primary nodes that have not acked. primaryNodes.toSet.intersect(remaining).foreach { replica(_) ! writeMsg } } secondaryNodes.foreach { replica(_) ! writeMsg } - case ReceiveTimeout ⇒ + case ReceiveTimeout => reply(isTimeout = true) } @@ -2162,13 +2162,13 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog var result = localValue override val doneWhenRemainingSize = consistency match { - case ReadFrom(n, _) ⇒ nodes.size - (n - 1) - case _: ReadAll ⇒ 0 - case ReadMajority(_, minCap) ⇒ + case ReadFrom(n, _) => nodes.size - (n - 1) + case _: ReadAll => 0 + case ReadMajority(_, minCap) => val N = nodes.size + 1 val r = calculateMajorityWithMinCap(minCap, N) N - r - case ReadLocal ⇒ + case ReadLocal => throw new IllegalArgumentException("ReadLocal not supported by ReadAggregator") } @@ -2188,47 +2188,47 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog } def receive = { - case ReadResult(envelope) ⇒ + case ReadResult(envelope) => result = (result, envelope) match { - case (Some(a), Some(b)) ⇒ Some(a.merge(b)) - case (r @ Some(_), None) ⇒ r - case (None, r @ Some(_)) ⇒ r - case (None, None) ⇒ None + case (Some(a), Some(b)) => Some(a.merge(b)) + case (r @ Some(_), None) => r + case (None, r @ Some(_)) => r + case (None, None) => None } remaining -= sender().path.address if (remaining.size == doneWhenRemainingSize) reply(ok = true) - case SendToSecondary ⇒ + case SendToSecondary => secondaryNodes.foreach { replica(_) ! readMsg } - case ReceiveTimeout ⇒ reply(ok = false) + case ReceiveTimeout => reply(ok = false) } def reply(ok: Boolean): Unit = (ok, result) match { - case (true, Some(envelope)) ⇒ + case (true, Some(envelope)) => context.parent ! ReadRepair(key.id, envelope) // read-repair happens before GetSuccess context.become(waitReadRepairAck(envelope)) - case (true, None) ⇒ + case (true, None) => replyTo.tell(NotFound(key, req), context.parent) context.stop(self) - case (false, _) ⇒ + case (false, _) => replyTo.tell(GetFailure(key, req), context.parent) context.stop(self) } def waitReadRepairAck(envelope: Replicator.Internal.DataEnvelope): Receive = { - case ReadRepairAck ⇒ + case ReadRepairAck => val replyMsg = if (envelope.data == DeletedData) DataDeleted(key, req) else GetSuccess(key, req)(envelope.data) replyTo.tell(replyMsg, context.parent) context.stop(self) - case _: ReadResult ⇒ + case _: ReadResult => //collect late replies remaining -= sender().path.address - case SendToSecondary ⇒ - case ReceiveTimeout ⇒ + case SendToSecondary => + case ReceiveTimeout => } } diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/VersionVector.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/VersionVector.scala index 0f0f158761..b3a6532e2f 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/VersionVector.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/VersionVector.scala @@ -269,7 +269,7 @@ final case class OneVersionVector private[akka] (node: UniqueAddress, version: L @InternalApi private[akka] override def increment(n: UniqueAddress): VersionVector = { val v = Timestamp.counter.getAndIncrement() if (n == node) copy(version = v) - else ManyVersionVector(TreeMap(node → version, n → v)) + else ManyVersionVector(TreeMap(node -> version, n -> v)) } /** INTERNAL API */ @@ -287,10 +287,10 @@ final case class OneVersionVector private[akka] (node: UniqueAddress, version: L override def merge(that: VersionVector): VersionVector = { that match { - case OneVersionVector(n2, v2) ⇒ + case OneVersionVector(n2, v2) => if (node == n2) if (version >= v2) this else OneVersionVector(n2, v2) - else ManyVersionVector(TreeMap(node → version, n2 → v2)) - case ManyVersionVector(vs2) ⇒ + else ManyVersionVector(TreeMap(node -> version, n2 -> v2)) + case ManyVersionVector(vs2) => val v2 = vs2.getOrElse(node, Timestamp.Zero) val mergedVersions = if (v2 >= version) vs2 @@ -332,8 +332,8 @@ final case class ManyVersionVector(versions: TreeMap[UniqueAddress, Long]) exten /** INTERNAL API */ @InternalApi private[akka] override def versionAt(node: UniqueAddress): Long = versions.get(node) match { - case Some(v) ⇒ v - case None ⇒ Timestamp.Zero + case Some(v) => v + case None => Timestamp.Zero } /** INTERNAL API */ @@ -348,15 +348,15 @@ final case class ManyVersionVector(versions: TreeMap[UniqueAddress, Long]) exten if (that.isEmpty) this else if (this.isEmpty) that else that match { - case ManyVersionVector(vs2) ⇒ + case ManyVersionVector(vs2) => var mergedVersions = vs2 - for ((node, time) ← versions) { + for ((node, time) <- versions) { val mergedVersionsCurrentTime = mergedVersions.getOrElse(node, Timestamp.Zero) if (time > mergedVersionsCurrentTime) mergedVersions = mergedVersions.updated(node, time) } VersionVector(mergedVersions) - case OneVersionVector(n2, v2) ⇒ + case OneVersionVector(n2, v2) => val v1 = versions.getOrElse(n2, Timestamp.Zero) val mergedVersions = if (v1 >= v2) versions @@ -379,5 +379,5 @@ final case class ManyVersionVector(versions: TreeMap[UniqueAddress, Long]) exten else this override def toString: String = - versions.map { case ((n, v)) ⇒ n + " -> " + v }.mkString("VersionVector(", ", ", ")") + versions.map { case ((n, v)) => n + " -> " + v }.mkString("VersionVector(", ", ", ")") } diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/ReplicatedDataSerializer.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/ReplicatedDataSerializer.scala index cf1629e7e1..e4e396d3c1 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/ReplicatedDataSerializer.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/ReplicatedDataSerializer.scala @@ -4,7 +4,7 @@ package akka.cluster.ddata.protobuf -import java.{ util, lang ⇒ jl } +import java.{ util, lang => jl } import java.util.ArrayList import java.util.Collections import java.util.Comparator @@ -17,8 +17,8 @@ import scala.collection.immutable import akka.actor.ExtendedActorSystem import akka.cluster.ddata._ import akka.cluster.ddata.Replicator.Internal._ -import akka.cluster.ddata.protobuf.msg.{ ReplicatedDataMessages ⇒ rd } -import akka.cluster.ddata.protobuf.msg.{ ReplicatorMessages ⇒ dm } +import akka.cluster.ddata.protobuf.msg.{ ReplicatedDataMessages => rd } +import akka.cluster.ddata.protobuf.msg.{ ReplicatorMessages => dm } import akka.serialization.SerializerWithStringManifest import akka.serialization.BaseSerializer import akka.protobuf.{ ByteString, GeneratedMessage } @@ -43,16 +43,16 @@ private object ReplicatedDataSerializer { def getKey(entry: A): Any final def compare(x: A, y: A): Int = compareKeys(getKey(x), getKey(y)) private final def compareKeys(t1: Any, t2: Any): Int = (t1, t2) match { - case (k1: String, k2: String) ⇒ k1.compareTo(k2) - case (k1: String, k2) ⇒ -1 - case (k1, k2: String) ⇒ 1 - case (k1: Int, k2: Int) ⇒ k1.compareTo(k2) - case (k1: Int, k2) ⇒ -1 - case (k1, k2: Int) ⇒ 1 - case (k1: Long, k2: Long) ⇒ k1.compareTo(k2) - case (k1: Long, k2) ⇒ -1 - case (k1, k2: Long) ⇒ 1 - case (k1: OtherMessage, k2: OtherMessage) ⇒ OtherMessageComparator.compare(k1, k2) + case (k1: String, k2: String) => k1.compareTo(k2) + case (k1: String, k2) => -1 + case (k1, k2: String) => 1 + case (k1: Int, k2: Int) => k1.compareTo(k2) + case (k1: Int, k2) => -1 + case (k1, k2: Int) => 1 + case (k1: Long, k2: Long) => k1.compareTo(k2) + case (k1: Long, k2) => -1 + case (k1, k2: Long) => 1 + case (k1: OtherMessage, k2: OtherMessage) => OtherMessageComparator.compare(k1, k2) } } @@ -210,110 +210,110 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) private val ORMultiMapKeyManifest = "k" private val VersionVectorManifest = "L" - private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] ⇒ AnyRef]( - GSetManifest → gsetFromBinary, - ORSetManifest → orsetFromBinary, - ORSetAddManifest → orsetAddFromBinary, - ORSetRemoveManifest → orsetRemoveFromBinary, - ORSetFullManifest → orsetFullFromBinary, - ORSetDeltaGroupManifest → orsetDeltaGroupFromBinary, - FlagManifest → flagFromBinary, - LWWRegisterManifest → lwwRegisterFromBinary, - GCounterManifest → gcounterFromBinary, - PNCounterManifest → pncounterFromBinary, - ORMapManifest → ormapFromBinary, - ORMapPutManifest → ormapPutFromBinary, - ORMapRemoveManifest → ormapRemoveFromBinary, - ORMapRemoveKeyManifest → ormapRemoveKeyFromBinary, - ORMapUpdateManifest → ormapUpdateFromBinary, - ORMapDeltaGroupManifest → ormapDeltaGroupFromBinary, - LWWMapManifest → lwwmapFromBinary, - PNCounterMapManifest → pncountermapFromBinary, - ORMultiMapManifest → multimapFromBinary, - DeletedDataManifest → (_ ⇒ DeletedData), - VersionVectorManifest → versionVectorFromBinary, + private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] => AnyRef]( + GSetManifest -> gsetFromBinary, + ORSetManifest -> orsetFromBinary, + ORSetAddManifest -> orsetAddFromBinary, + ORSetRemoveManifest -> orsetRemoveFromBinary, + ORSetFullManifest -> orsetFullFromBinary, + ORSetDeltaGroupManifest -> orsetDeltaGroupFromBinary, + FlagManifest -> flagFromBinary, + LWWRegisterManifest -> lwwRegisterFromBinary, + GCounterManifest -> gcounterFromBinary, + PNCounterManifest -> pncounterFromBinary, + ORMapManifest -> ormapFromBinary, + ORMapPutManifest -> ormapPutFromBinary, + ORMapRemoveManifest -> ormapRemoveFromBinary, + ORMapRemoveKeyManifest -> ormapRemoveKeyFromBinary, + ORMapUpdateManifest -> ormapUpdateFromBinary, + ORMapDeltaGroupManifest -> ormapDeltaGroupFromBinary, + LWWMapManifest -> lwwmapFromBinary, + PNCounterMapManifest -> pncountermapFromBinary, + ORMultiMapManifest -> multimapFromBinary, + DeletedDataManifest -> (_ => DeletedData), + VersionVectorManifest -> versionVectorFromBinary, - GSetKeyManifest → (bytes ⇒ GSetKey(keyIdFromBinary(bytes))), - ORSetKeyManifest → (bytes ⇒ ORSetKey(keyIdFromBinary(bytes))), - FlagKeyManifest → (bytes ⇒ FlagKey(keyIdFromBinary(bytes))), - LWWRegisterKeyManifest → (bytes ⇒ LWWRegisterKey(keyIdFromBinary(bytes))), - GCounterKeyManifest → (bytes ⇒ GCounterKey(keyIdFromBinary(bytes))), - PNCounterKeyManifest → (bytes ⇒ PNCounterKey(keyIdFromBinary(bytes))), - ORMapKeyManifest → (bytes ⇒ ORMapKey(keyIdFromBinary(bytes))), - LWWMapKeyManifest → (bytes ⇒ LWWMapKey(keyIdFromBinary(bytes))), - PNCounterMapKeyManifest → (bytes ⇒ PNCounterMapKey(keyIdFromBinary(bytes))), - ORMultiMapKeyManifest → (bytes ⇒ ORMultiMapKey(keyIdFromBinary(bytes)))) + GSetKeyManifest -> (bytes => GSetKey(keyIdFromBinary(bytes))), + ORSetKeyManifest -> (bytes => ORSetKey(keyIdFromBinary(bytes))), + FlagKeyManifest -> (bytes => FlagKey(keyIdFromBinary(bytes))), + LWWRegisterKeyManifest -> (bytes => LWWRegisterKey(keyIdFromBinary(bytes))), + GCounterKeyManifest -> (bytes => GCounterKey(keyIdFromBinary(bytes))), + PNCounterKeyManifest -> (bytes => PNCounterKey(keyIdFromBinary(bytes))), + ORMapKeyManifest -> (bytes => ORMapKey(keyIdFromBinary(bytes))), + LWWMapKeyManifest -> (bytes => LWWMapKey(keyIdFromBinary(bytes))), + PNCounterMapKeyManifest -> (bytes => PNCounterMapKey(keyIdFromBinary(bytes))), + ORMultiMapKeyManifest -> (bytes => ORMultiMapKey(keyIdFromBinary(bytes)))) override def manifest(obj: AnyRef): String = obj match { - case _: ORSet[_] ⇒ ORSetManifest - case _: ORSet.AddDeltaOp[_] ⇒ ORSetAddManifest - case _: ORSet.RemoveDeltaOp[_] ⇒ ORSetRemoveManifest - case _: GSet[_] ⇒ GSetManifest - case _: GCounter ⇒ GCounterManifest - case _: PNCounter ⇒ PNCounterManifest - case _: Flag ⇒ FlagManifest - case _: LWWRegister[_] ⇒ LWWRegisterManifest - case _: ORMap[_, _] ⇒ ORMapManifest - case _: ORMap.PutDeltaOp[_, _] ⇒ ORMapPutManifest - case _: ORMap.RemoveDeltaOp[_, _] ⇒ ORMapRemoveManifest - case _: ORMap.RemoveKeyDeltaOp[_, _] ⇒ ORMapRemoveKeyManifest - case _: ORMap.UpdateDeltaOp[_, _] ⇒ ORMapUpdateManifest - case _: LWWMap[_, _] ⇒ LWWMapManifest - case _: PNCounterMap[_] ⇒ PNCounterMapManifest - case _: ORMultiMap[_, _] ⇒ ORMultiMapManifest - case DeletedData ⇒ DeletedDataManifest - case _: VersionVector ⇒ VersionVectorManifest + case _: ORSet[_] => ORSetManifest + case _: ORSet.AddDeltaOp[_] => ORSetAddManifest + case _: ORSet.RemoveDeltaOp[_] => ORSetRemoveManifest + case _: GSet[_] => GSetManifest + case _: GCounter => GCounterManifest + case _: PNCounter => PNCounterManifest + case _: Flag => FlagManifest + case _: LWWRegister[_] => LWWRegisterManifest + case _: ORMap[_, _] => ORMapManifest + case _: ORMap.PutDeltaOp[_, _] => ORMapPutManifest + case _: ORMap.RemoveDeltaOp[_, _] => ORMapRemoveManifest + case _: ORMap.RemoveKeyDeltaOp[_, _] => ORMapRemoveKeyManifest + case _: ORMap.UpdateDeltaOp[_, _] => ORMapUpdateManifest + case _: LWWMap[_, _] => LWWMapManifest + case _: PNCounterMap[_] => PNCounterMapManifest + case _: ORMultiMap[_, _] => ORMultiMapManifest + case DeletedData => DeletedDataManifest + case _: VersionVector => VersionVectorManifest - case _: ORSetKey[_] ⇒ ORSetKeyManifest - case _: GSetKey[_] ⇒ GSetKeyManifest - case _: GCounterKey ⇒ GCounterKeyManifest - case _: PNCounterKey ⇒ PNCounterKeyManifest - case _: FlagKey ⇒ FlagKeyManifest - case _: LWWRegisterKey[_] ⇒ LWWRegisterKeyManifest - case _: ORMapKey[_, _] ⇒ ORMapKeyManifest - case _: LWWMapKey[_, _] ⇒ LWWMapKeyManifest - case _: PNCounterMapKey[_] ⇒ PNCounterMapKeyManifest - case _: ORMultiMapKey[_, _] ⇒ ORMultiMapKeyManifest + case _: ORSetKey[_] => ORSetKeyManifest + case _: GSetKey[_] => GSetKeyManifest + case _: GCounterKey => GCounterKeyManifest + case _: PNCounterKey => PNCounterKeyManifest + case _: FlagKey => FlagKeyManifest + case _: LWWRegisterKey[_] => LWWRegisterKeyManifest + case _: ORMapKey[_, _] => ORMapKeyManifest + case _: LWWMapKey[_, _] => LWWMapKeyManifest + case _: PNCounterMapKey[_] => PNCounterMapKeyManifest + case _: ORMultiMapKey[_, _] => ORMultiMapKeyManifest - case _: ORSet.DeltaGroup[_] ⇒ ORSetDeltaGroupManifest - case _: ORMap.DeltaGroup[_, _] ⇒ ORMapDeltaGroupManifest - case _: ORSet.FullStateDeltaOp[_] ⇒ ORSetFullManifest + case _: ORSet.DeltaGroup[_] => ORSetDeltaGroupManifest + case _: ORMap.DeltaGroup[_, _] => ORMapDeltaGroupManifest + case _: ORSet.FullStateDeltaOp[_] => ORSetFullManifest - case _ ⇒ + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: ORSet[_] ⇒ compress(orsetToProto(m)) - case m: ORSet.AddDeltaOp[_] ⇒ orsetToProto(m.underlying).toByteArray - case m: ORSet.RemoveDeltaOp[_] ⇒ orsetToProto(m.underlying).toByteArray - case m: GSet[_] ⇒ gsetToProto(m).toByteArray - case m: GCounter ⇒ gcounterToProto(m).toByteArray - case m: PNCounter ⇒ pncounterToProto(m).toByteArray - case m: Flag ⇒ flagToProto(m).toByteArray - case m: LWWRegister[_] ⇒ lwwRegisterToProto(m).toByteArray - case m: ORMap[_, _] ⇒ compress(ormapToProto(m)) - case m: ORMap.PutDeltaOp[_, _] ⇒ ormapPutToProto(m).toByteArray - case m: ORMap.RemoveDeltaOp[_, _] ⇒ ormapRemoveToProto(m).toByteArray - case m: ORMap.RemoveKeyDeltaOp[_, _] ⇒ ormapRemoveKeyToProto(m).toByteArray - case m: ORMap.UpdateDeltaOp[_, _] ⇒ ormapUpdateToProto(m).toByteArray - case m: LWWMap[_, _] ⇒ compress(lwwmapToProto(m)) - case m: PNCounterMap[_] ⇒ compress(pncountermapToProto(m)) - case m: ORMultiMap[_, _] ⇒ compress(multimapToProto(m)) - case DeletedData ⇒ dm.Empty.getDefaultInstance.toByteArray - case m: VersionVector ⇒ versionVectorToProto(m).toByteArray - case Key(id) ⇒ keyIdToBinary(id) - case m: ORSet.DeltaGroup[_] ⇒ orsetDeltaGroupToProto(m).toByteArray - case m: ORMap.DeltaGroup[_, _] ⇒ ormapDeltaGroupToProto(m).toByteArray - case m: ORSet.FullStateDeltaOp[_] ⇒ orsetToProto(m.underlying).toByteArray - case _ ⇒ + case m: ORSet[_] => compress(orsetToProto(m)) + case m: ORSet.AddDeltaOp[_] => orsetToProto(m.underlying).toByteArray + case m: ORSet.RemoveDeltaOp[_] => orsetToProto(m.underlying).toByteArray + case m: GSet[_] => gsetToProto(m).toByteArray + case m: GCounter => gcounterToProto(m).toByteArray + case m: PNCounter => pncounterToProto(m).toByteArray + case m: Flag => flagToProto(m).toByteArray + case m: LWWRegister[_] => lwwRegisterToProto(m).toByteArray + case m: ORMap[_, _] => compress(ormapToProto(m)) + case m: ORMap.PutDeltaOp[_, _] => ormapPutToProto(m).toByteArray + case m: ORMap.RemoveDeltaOp[_, _] => ormapRemoveToProto(m).toByteArray + case m: ORMap.RemoveKeyDeltaOp[_, _] => ormapRemoveKeyToProto(m).toByteArray + case m: ORMap.UpdateDeltaOp[_, _] => ormapUpdateToProto(m).toByteArray + case m: LWWMap[_, _] => compress(lwwmapToProto(m)) + case m: PNCounterMap[_] => compress(pncountermapToProto(m)) + case m: ORMultiMap[_, _] => compress(multimapToProto(m)) + case DeletedData => dm.Empty.getDefaultInstance.toByteArray + case m: VersionVector => versionVectorToProto(m).toByteArray + case Key(id) => keyIdToBinary(id) + case m: ORSet.DeltaGroup[_] => orsetDeltaGroupToProto(m).toByteArray + case m: ORMap.DeltaGroup[_, _] => ormapDeltaGroupToProto(m).toByteArray + case m: ORSet.FullStateDeltaOp[_] => orsetToProto(m.underlying).toByteArray + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = fromBinaryMap.get(manifest) match { - case Some(f) ⇒ f(bytes) - case None ⇒ throw new NotSerializableException( + case Some(f) => f(bytes) + case None => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } @@ -326,11 +326,11 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) val otherElements = new ArrayList[dm.OtherMessage] val actorRefElements = new ArrayList[String] gset.elements.foreach { - case s: String ⇒ stringElements.add(s) - case i: Int ⇒ intElements.add(i) - case l: Long ⇒ longElements.add(l) - case ref: ActorRef ⇒ actorRefElements.add(Serialization.serializedActorPath(ref)) - case other ⇒ otherElements.add(otherMessageToProto(other)) + case s: String => stringElements.add(s) + case i: Int => intElements.add(i) + case l: Long => longElements.add(l) + case ref: ActorRef => actorRefElements.add(Serialization.serializedActorPath(ref)) + case other => otherElements.add(otherMessageToProto(other)) } if (!stringElements.isEmpty) { Collections.sort(stringElements) @@ -382,11 +382,11 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) var otherElementsMap = Map.empty[dm.OtherMessage, Any] val actorRefElements = new ArrayList[ActorRef] orset.elementsMap.keysIterator.foreach { - case s: String ⇒ stringElements.add(s) - case i: Int ⇒ intElements.add(i) - case l: Long ⇒ longElements.add(l) - case ref: ActorRef ⇒ actorRefElements.add(ref) - case other ⇒ + case s: String => stringElements.add(s) + case i: Int => intElements.add(i) + case l: Long => longElements.add(l) + case ref: ActorRef => actorRefElements.add(ref) + case other => val enclosedMsg = otherMessageToProto(other) otherElements.add(enclosedMsg) // need the mapping back to the `other` when adding dots @@ -398,8 +398,8 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) val iter = elements.iterator while (iter.hasNext) { val element = iter.next() match { - case enclosedMsg: dm.OtherMessage ⇒ otherElementsMap(enclosedMsg) - case e ⇒ e + case enclosedMsg: dm.OtherMessage => otherElementsMap(enclosedMsg) + case e => e } b.addDots(versionVectorToProto(orset.elementsMap(element))) } @@ -458,13 +458,13 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) val b = rd.ORSetDeltaGroup.newBuilder() deltaGroup.ops.foreach { - case ORSet.AddDeltaOp(u) ⇒ + case ORSet.AddDeltaOp(u) => b.addEntries(createEntry(rd.ORSetDeltaOp.Add, u)) - case ORSet.RemoveDeltaOp(u) ⇒ + case ORSet.RemoveDeltaOp(u) => b.addEntries(createEntry(rd.ORSetDeltaOp.Remove, u)) - case ORSet.FullStateDeltaOp(u) ⇒ + case ORSet.FullStateDeltaOp(u) => b.addEntries(createEntry(rd.ORSetDeltaOp.Full, u)) - case ORSet.DeltaGroup(u) ⇒ + case ORSet.DeltaGroup(u) => throw new IllegalArgumentException("ORSet.DeltaGroup should not be nested") } b.build() @@ -473,7 +473,7 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) private def orsetDeltaGroupFromBinary(bytes: Array[Byte]): ORSet.DeltaGroup[Any] = { val deltaGroup = rd.ORSetDeltaGroup.parseFrom(bytes) val ops: Vector[ORSet.DeltaOp] = - deltaGroup.getEntriesList.asScala.iterator.map { entry ⇒ + deltaGroup.getEntriesList.asScala.iterator.map { entry => if (entry.getOperation == rd.ORSetDeltaOp.Add) ORSet.AddDeltaOp(orsetFromProto(entry.getUnderlying)) else if (entry.getOperation == rd.ORSetDeltaOp.Remove) @@ -528,8 +528,8 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) def gcounterToProto(gcounter: GCounter): rd.GCounter = { val b = rd.GCounter.newBuilder() - gcounter.state.toVector.sortBy { case (address, _) ⇒ address }.foreach { - case (address, value) ⇒ b.addEntries(rd.GCounter.Entry.newBuilder(). + gcounter.state.toVector.sortBy { case (address, _) => address }.foreach { + case (address, value) => b.addEntries(rd.GCounter.Entry.newBuilder(). setNode(uniqueAddressToProto(address)).setValue(ByteString.copyFrom(value.toByteArray))) } b.build() @@ -539,8 +539,8 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) gcounterFromProto(rd.GCounter.parseFrom(bytes)) def gcounterFromProto(gcounter: rd.GCounter): GCounter = { - new GCounter(state = gcounter.getEntriesList.asScala.iterator.map(entry ⇒ - uniqueAddressFromProto(entry.getNode) → BigInt(entry.getValue.toByteArray)).toMap) + new GCounter(state = gcounter.getEntriesList.asScala.iterator.map(entry => + uniqueAddressFromProto(entry.getNode) -> BigInt(entry.getValue.toByteArray)).toMap) } def pncounterToProto(pncounter: PNCounter): rd.PNCounter = @@ -561,14 +561,14 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) /* * Convert a Map[A, B] to an Iterable[Entry] where Entry is the protobuf map entry. */ - private def getEntries[IKey, IValue, EntryBuilder <: GeneratedMessage.Builder[EntryBuilder], PEntry <: GeneratedMessage, PValue <: GeneratedMessage](input: Map[IKey, IValue], createBuilder: () ⇒ EntryBuilder, valueConverter: IValue ⇒ PValue)(implicit comparator: Comparator[PEntry], eh: ProtoMapEntryWriter[PEntry, EntryBuilder, PValue]): java.lang.Iterable[PEntry] = { + private def getEntries[IKey, IValue, EntryBuilder <: GeneratedMessage.Builder[EntryBuilder], PEntry <: GeneratedMessage, PValue <: GeneratedMessage](input: Map[IKey, IValue], createBuilder: () => EntryBuilder, valueConverter: IValue => PValue)(implicit comparator: Comparator[PEntry], eh: ProtoMapEntryWriter[PEntry, EntryBuilder, PValue]): java.lang.Iterable[PEntry] = { // The resulting Iterable needs to be ordered deterministically in order to create same signature upon serializing same data val protoEntries = new TreeSet[PEntry](comparator) input.foreach { - case (key: String, value) ⇒ protoEntries.add(eh.setStringKey(createBuilder(), key, valueConverter(value))) - case (key: Int, value) ⇒ protoEntries.add(eh.setIntKey(createBuilder(), key, valueConverter(value))) - case (key: Long, value) ⇒ protoEntries.add(eh.setLongKey(createBuilder(), key, valueConverter(value))) - case (key, value) ⇒ protoEntries.add(eh.setOtherKey(createBuilder(), otherMessageToProto(key), valueConverter(value))) + case (key: String, value) => protoEntries.add(eh.setStringKey(createBuilder(), key, valueConverter(value))) + case (key: Int, value) => protoEntries.add(eh.setIntKey(createBuilder(), key, valueConverter(value))) + case (key: Long, value) => protoEntries.add(eh.setLongKey(createBuilder(), key, valueConverter(value))) + case (key, value) => protoEntries.add(eh.setOtherKey(createBuilder(), otherMessageToProto(key), valueConverter(value))) } protoEntries } @@ -582,25 +582,25 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) def ormapFromBinary(bytes: Array[Byte]): ORMap[Any, ReplicatedData] = ormapFromProto(rd.ORMap.parseFrom(decompress(bytes))) - def mapTypeFromProto[PEntry <: GeneratedMessage, A <: GeneratedMessage, B <: ReplicatedData](input: util.List[PEntry], valueCreator: A ⇒ B)(implicit eh: ProtoMapEntryReader[PEntry, A]): Map[Any, B] = { - input.asScala.map { entry ⇒ - if (eh.hasStringKey(entry)) eh.getStringKey(entry) → valueCreator(eh.getValue(entry)) - else if (eh.hasIntKey(entry)) eh.getIntKey(entry) → valueCreator(eh.getValue(entry)) - else if (eh.hasLongKey(entry)) eh.getLongKey(entry) → valueCreator(eh.getValue(entry)) - else if (eh.hasOtherKey(entry)) otherMessageFromProto(eh.getOtherKey(entry)) → valueCreator(eh.getValue(entry)) + def mapTypeFromProto[PEntry <: GeneratedMessage, A <: GeneratedMessage, B <: ReplicatedData](input: util.List[PEntry], valueCreator: A => B)(implicit eh: ProtoMapEntryReader[PEntry, A]): Map[Any, B] = { + input.asScala.map { entry => + if (eh.hasStringKey(entry)) eh.getStringKey(entry) -> valueCreator(eh.getValue(entry)) + else if (eh.hasIntKey(entry)) eh.getIntKey(entry) -> valueCreator(eh.getValue(entry)) + else if (eh.hasLongKey(entry)) eh.getLongKey(entry) -> valueCreator(eh.getValue(entry)) + else if (eh.hasOtherKey(entry)) otherMessageFromProto(eh.getOtherKey(entry)) -> valueCreator(eh.getValue(entry)) else throw new IllegalArgumentException(s"Can't deserialize ${entry.getClass} because it does not have any key in the serialized message.") }.toMap } def ormapFromProto(ormap: rd.ORMap): ORMap[Any, ReplicatedData] = { - val entries = mapTypeFromProto(ormap.getEntriesList, (v: dm.OtherMessage) ⇒ otherMessageFromProto(v).asInstanceOf[ReplicatedData]) + val entries = mapTypeFromProto(ormap.getEntriesList, (v: dm.OtherMessage) => otherMessageFromProto(v).asInstanceOf[ReplicatedData]) new ORMap( keys = orsetFromProto(ormap.getKeys), entries, ORMap.VanillaORMapTag) } - def singleMapEntryFromProto[PEntry <: GeneratedMessage, A <: GeneratedMessage, B <: ReplicatedData](input: util.List[PEntry], valueCreator: A ⇒ B)(implicit eh: ProtoMapEntryReader[PEntry, A]): Map[Any, B] = { + def singleMapEntryFromProto[PEntry <: GeneratedMessage, A <: GeneratedMessage, B <: ReplicatedData](input: util.List[PEntry], valueCreator: A => B)(implicit eh: ProtoMapEntryReader[PEntry, A]): Map[Any, B] = { val map = mapTypeFromProto(input, valueCreator) if (map.size > 1) throw new IllegalArgumentException(s"Can't deserialize the key/value pair in the ORMap delta - too many pairs on the wire") @@ -610,12 +610,12 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) def singleKeyEntryFromProto[PEntry <: GeneratedMessage, A <: GeneratedMessage](entryOption: Option[PEntry])(implicit eh: ProtoMapEntryReader[PEntry, A]): Any = entryOption match { - case Some(entry) ⇒ if (eh.hasStringKey(entry)) eh.getStringKey(entry) + case Some(entry) => if (eh.hasStringKey(entry)) eh.getStringKey(entry) else if (eh.hasIntKey(entry)) eh.getIntKey(entry) else if (eh.hasLongKey(entry)) eh.getLongKey(entry) else if (eh.hasOtherKey(entry)) otherMessageFromProto(eh.getOtherKey(entry)) else throw new IllegalArgumentException(s"Can't deserialize the key in the ORMap delta") - case _ ⇒ throw new IllegalArgumentException(s"Can't deserialize the key in the ORMap delta") + case _ => throw new IllegalArgumentException(s"Can't deserialize the key in the ORMap delta") } // wire protocol is always DeltaGroup @@ -656,12 +656,12 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) // this can be made client-extendable in the same way as Http codes in Spray are private def zeroTagFromCode(code: Int) = code match { - case ORMap.VanillaORMapTag.value ⇒ ORMap.VanillaORMapTag - case PNCounterMap.PNCounterMapTag.value ⇒ PNCounterMap.PNCounterMapTag - case ORMultiMap.ORMultiMapTag.value ⇒ ORMultiMap.ORMultiMapTag - case ORMultiMap.ORMultiMapWithValueDeltasTag.value ⇒ ORMultiMap.ORMultiMapWithValueDeltasTag - case LWWMap.LWWMapTag.value ⇒ LWWMap.LWWMapTag - case _ ⇒ throw new IllegalArgumentException("Invalid ZeroTag code") + case ORMap.VanillaORMapTag.value => ORMap.VanillaORMapTag + case PNCounterMap.PNCounterMapTag.value => PNCounterMap.PNCounterMapTag + case ORMultiMap.ORMultiMapTag.value => ORMultiMap.ORMultiMapTag + case ORMultiMap.ORMultiMapWithValueDeltasTag.value => ORMultiMap.ORMultiMapWithValueDeltasTag + case LWWMap.LWWMapTag.value => LWWMap.LWWMapTag + case _ => throw new IllegalArgumentException("Invalid ZeroTag code") } private def ormapDeltaGroupFromBinary(bytes: Array[Byte]): ORMap.DeltaGroup[Any, ReplicatedData] = { @@ -671,9 +671,9 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) private def ormapDeltaGroupOpsFromBinary(bytes: Array[Byte]): scala.collection.immutable.IndexedSeq[ORMap.DeltaOp] = { val deltaGroup = rd.ORMapDeltaGroup.parseFrom(bytes) val ops: Vector[ORMap.DeltaOp] = - deltaGroup.getEntriesList.asScala.iterator.map { entry ⇒ + deltaGroup.getEntriesList.asScala.iterator.map { entry => if (entry.getOperation == rd.ORMapDeltaOp.ORMapPut) { - val map = singleMapEntryFromProto(entry.getEntryDataList, (v: dm.OtherMessage) ⇒ otherMessageFromProto(v).asInstanceOf[ReplicatedData]) + val map = singleMapEntryFromProto(entry.getEntryDataList, (v: dm.OtherMessage) => otherMessageFromProto(v).asInstanceOf[ReplicatedData]) ORMap.PutDeltaOp(ORSet.AddDeltaOp(orsetFromProto(entry.getUnderlying)), map.head, zeroTagFromCode(entry.getZeroTag)) } else if (entry.getOperation == rd.ORMapDeltaOp.ORMapRemove) { ORMap.RemoveDeltaOp(ORSet.RemoveDeltaOp(orsetFromProto(entry.getUnderlying)), zeroTagFromCode(entry.getZeroTag)) @@ -681,7 +681,7 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) val elem = singleKeyEntryFromProto(entry.getEntryDataList.asScala.headOption) ORMap.RemoveKeyDeltaOp(ORSet.RemoveDeltaOp(orsetFromProto(entry.getUnderlying)), elem, zeroTagFromCode(entry.getZeroTag)) } else if (entry.getOperation == rd.ORMapDeltaOp.ORMapUpdate) { - val map = mapTypeFromProto(entry.getEntryDataList, (v: dm.OtherMessage) ⇒ otherMessageFromProto(v).asInstanceOf[ReplicatedDelta]) + val map = mapTypeFromProto(entry.getEntryDataList, (v: dm.OtherMessage) => otherMessageFromProto(v).asInstanceOf[ReplicatedDelta]) ORMap.UpdateDeltaOp(ORSet.AddDeltaOp(orsetFromProto(entry.getUnderlying)), map, zeroTagFromCode(entry.getZeroTag)) } else throw new NotSerializableException(s"Unknown ORMap delta operation ${entry.getOperation}") @@ -719,10 +719,10 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) .setUnderlying(orsetToProto(u)) .setZeroTag(zt) m.foreach { - case (key: String, value) ⇒ builder.addEntryData(rd.ORMapDeltaGroup.MapEntry.newBuilder().setStringKey(key).setValue(otherMessageToProto(value)).build()) - case (key: Int, value) ⇒ builder.addEntryData(rd.ORMapDeltaGroup.MapEntry.newBuilder().setIntKey(key).setValue(otherMessageToProto(value)).build()) - case (key: Long, value) ⇒ builder.addEntryData(rd.ORMapDeltaGroup.MapEntry.newBuilder().setLongKey(key).setValue(otherMessageToProto(value)).build()) - case (key, value) ⇒ builder.addEntryData(rd.ORMapDeltaGroup.MapEntry.newBuilder().setOtherKey(otherMessageToProto(key)).setValue(otherMessageToProto(value)).build()) + case (key: String, value) => builder.addEntryData(rd.ORMapDeltaGroup.MapEntry.newBuilder().setStringKey(key).setValue(otherMessageToProto(value)).build()) + case (key: Int, value) => builder.addEntryData(rd.ORMapDeltaGroup.MapEntry.newBuilder().setIntKey(key).setValue(otherMessageToProto(value)).build()) + case (key: Long, value) => builder.addEntryData(rd.ORMapDeltaGroup.MapEntry.newBuilder().setLongKey(key).setValue(otherMessageToProto(value)).build()) + case (key, value) => builder.addEntryData(rd.ORMapDeltaGroup.MapEntry.newBuilder().setOtherKey(otherMessageToProto(key)).setValue(otherMessageToProto(value)).build()) } builder } @@ -731,10 +731,10 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) def createEntryWithKey(opType: rd.ORMapDeltaOp, u: ORSet[_], k: Any, zt: Int) = { val entryDataBuilder = rd.ORMapDeltaGroup.MapEntry.newBuilder() k match { - case key: String ⇒ entryDataBuilder.setStringKey(key) - case key: Int ⇒ entryDataBuilder.setIntKey(key) - case key: Long ⇒ entryDataBuilder.setLongKey(key) - case key ⇒ entryDataBuilder.setOtherKey(otherMessageToProto(key)) + case key: String => entryDataBuilder.setStringKey(key) + case key: Int => entryDataBuilder.setIntKey(key) + case key: Long => entryDataBuilder.setLongKey(key) + case key => entryDataBuilder.setOtherKey(otherMessageToProto(key)) } val builder = rd.ORMapDeltaGroup.Entry.newBuilder() .setOperation(opType) @@ -746,15 +746,15 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) val b = rd.ORMapDeltaGroup.newBuilder() deltaGroupOps.foreach { - case ORMap.PutDeltaOp(op, pair, zt) ⇒ + case ORMap.PutDeltaOp(op, pair, zt) => b.addEntries(createEntry(rd.ORMapDeltaOp.ORMapPut, op.asInstanceOf[ORSet.AddDeltaOp[_]].underlying, Map(pair), zt.value)) - case ORMap.RemoveDeltaOp(op, zt) ⇒ + case ORMap.RemoveDeltaOp(op, zt) => b.addEntries(createEntry(rd.ORMapDeltaOp.ORMapRemove, op.asInstanceOf[ORSet.RemoveDeltaOp[_]].underlying, Map.empty, zt.value)) - case ORMap.RemoveKeyDeltaOp(op, k, zt) ⇒ + case ORMap.RemoveKeyDeltaOp(op, k, zt) => b.addEntries(createEntryWithKey(rd.ORMapDeltaOp.ORMapRemoveKey, op.asInstanceOf[ORSet.RemoveDeltaOp[_]].underlying, k, zt.value)) - case ORMap.UpdateDeltaOp(op, m, zt) ⇒ + case ORMap.UpdateDeltaOp(op, m, zt) => b.addEntries(createEntry(rd.ORMapDeltaOp.ORMapUpdate, op.asInstanceOf[ORSet.AddDeltaOp[_]].underlying, m, zt.value)) - case ORMap.DeltaGroup(u) ⇒ + case ORMap.DeltaGroup(u) => throw new IllegalArgumentException("ORMap.DeltaGroup should not be nested") } b.build() diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/ReplicatorMessageSerializer.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/ReplicatorMessageSerializer.scala index 9f09a571c0..970418951d 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/ReplicatorMessageSerializer.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/ReplicatorMessageSerializer.scala @@ -16,11 +16,11 @@ import akka.cluster.ddata.PruningState import akka.cluster.ddata.ReplicatedData import akka.cluster.ddata.Replicator._ import akka.cluster.ddata.Replicator.Internal._ -import akka.cluster.ddata.protobuf.msg.{ ReplicatorMessages ⇒ dm } +import akka.cluster.ddata.protobuf.msg.{ ReplicatorMessages => dm } import akka.serialization.Serialization import akka.serialization.SerializerWithStringManifest import akka.serialization.BaseSerializer -import akka.util.{ ByteString ⇒ AkkaByteString } +import akka.util.{ ByteString => AkkaByteString } import akka.protobuf.ByteString import akka.cluster.ddata.Key.KeyR import java.util.concurrent.atomic.AtomicInteger @@ -48,7 +48,7 @@ import akka.util.ccompat._ * `evict` must be called from the outside, i.e. the * cache will not cleanup itself. */ - final class SmallCache[A <: AnyRef, B <: AnyRef](size: Int, timeToLive: FiniteDuration, getOrAddFactory: A ⇒ B) { + final class SmallCache[A <: AnyRef, B <: AnyRef](size: Int, timeToLive: FiniteDuration, getOrAddFactory: A => B) { require((size & (size - 1)) == 0, "size must be a power of 2") require(size <= 32, "size must be <= 32") @@ -152,8 +152,8 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) private val cacheTimeToLive = system.settings.config.getDuration( "akka.cluster.distributed-data.serializer-cache-time-to-live", TimeUnit.MILLISECONDS).millis - private val readCache = new SmallCache[Read, Array[Byte]](4, cacheTimeToLive, m ⇒ readToProto(m).toByteArray) - private val writeCache = new SmallCache[Write, Array[Byte]](4, cacheTimeToLive, m ⇒ writeToProto(m).toByteArray) + private val readCache = new SmallCache[Read, Array[Byte]](4, cacheTimeToLive, m => readToProto(m).toByteArray) + private val writeCache = new SmallCache[Write, Array[Byte]](4, cacheTimeToLive, m => writeToProto(m).toByteArray) system.scheduler.schedule(cacheTimeToLive, cacheTimeToLive / 2) { readCache.evict() writeCache.evict() @@ -181,76 +181,76 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) val DeltaPropagationManifest = "Q" val DeltaNackManifest = "R" - private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] ⇒ AnyRef]( - GetManifest → getFromBinary, - GetSuccessManifest → getSuccessFromBinary, - NotFoundManifest → notFoundFromBinary, - GetFailureManifest → getFailureFromBinary, - SubscribeManifest → subscribeFromBinary, - UnsubscribeManifest → unsubscribeFromBinary, - ChangedManifest → changedFromBinary, - DataEnvelopeManifest → dataEnvelopeFromBinary, - WriteManifest → writeFromBinary, - WriteAckManifest → (_ ⇒ WriteAck), - ReadManifest → readFromBinary, - ReadResultManifest → readResultFromBinary, - StatusManifest → statusFromBinary, - GossipManifest → gossipFromBinary, - DeltaPropagationManifest → deltaPropagationFromBinary, - WriteNackManifest → (_ ⇒ WriteNack), - DeltaNackManifest → (_ ⇒ DeltaNack), - DurableDataEnvelopeManifest → durableDataEnvelopeFromBinary) + private val fromBinaryMap = collection.immutable.HashMap[String, Array[Byte] => AnyRef]( + GetManifest -> getFromBinary, + GetSuccessManifest -> getSuccessFromBinary, + NotFoundManifest -> notFoundFromBinary, + GetFailureManifest -> getFailureFromBinary, + SubscribeManifest -> subscribeFromBinary, + UnsubscribeManifest -> unsubscribeFromBinary, + ChangedManifest -> changedFromBinary, + DataEnvelopeManifest -> dataEnvelopeFromBinary, + WriteManifest -> writeFromBinary, + WriteAckManifest -> (_ => WriteAck), + ReadManifest -> readFromBinary, + ReadResultManifest -> readResultFromBinary, + StatusManifest -> statusFromBinary, + GossipManifest -> gossipFromBinary, + DeltaPropagationManifest -> deltaPropagationFromBinary, + WriteNackManifest -> (_ => WriteNack), + DeltaNackManifest -> (_ => DeltaNack), + DurableDataEnvelopeManifest -> durableDataEnvelopeFromBinary) override def manifest(obj: AnyRef): String = obj match { - case _: DataEnvelope ⇒ DataEnvelopeManifest - case _: Write ⇒ WriteManifest - case WriteAck ⇒ WriteAckManifest - case _: Read ⇒ ReadManifest - case _: ReadResult ⇒ ReadResultManifest - case _: DeltaPropagation ⇒ DeltaPropagationManifest - case _: Status ⇒ StatusManifest - case _: Get[_] ⇒ GetManifest - case _: GetSuccess[_] ⇒ GetSuccessManifest - case _: DurableDataEnvelope ⇒ DurableDataEnvelopeManifest - case _: Changed[_] ⇒ ChangedManifest - case _: NotFound[_] ⇒ NotFoundManifest - case _: GetFailure[_] ⇒ GetFailureManifest - case _: Subscribe[_] ⇒ SubscribeManifest - case _: Unsubscribe[_] ⇒ UnsubscribeManifest - case _: Gossip ⇒ GossipManifest - case WriteNack ⇒ WriteNackManifest - case DeltaNack ⇒ DeltaNackManifest - case _ ⇒ + case _: DataEnvelope => DataEnvelopeManifest + case _: Write => WriteManifest + case WriteAck => WriteAckManifest + case _: Read => ReadManifest + case _: ReadResult => ReadResultManifest + case _: DeltaPropagation => DeltaPropagationManifest + case _: Status => StatusManifest + case _: Get[_] => GetManifest + case _: GetSuccess[_] => GetSuccessManifest + case _: DurableDataEnvelope => DurableDataEnvelopeManifest + case _: Changed[_] => ChangedManifest + case _: NotFound[_] => NotFoundManifest + case _: GetFailure[_] => GetFailureManifest + case _: Subscribe[_] => SubscribeManifest + case _: Unsubscribe[_] => UnsubscribeManifest + case _: Gossip => GossipManifest + case WriteNack => WriteNackManifest + case DeltaNack => DeltaNackManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: DataEnvelope ⇒ dataEnvelopeToProto(m).toByteArray - case m: Write ⇒ writeCache.getOrAdd(m) - case WriteAck ⇒ writeAckBytes - case m: Read ⇒ readCache.getOrAdd(m) - case m: ReadResult ⇒ readResultToProto(m).toByteArray - case m: Status ⇒ statusToProto(m).toByteArray - case m: DeltaPropagation ⇒ deltaPropagationToProto(m).toByteArray - case m: Get[_] ⇒ getToProto(m).toByteArray - case m: GetSuccess[_] ⇒ getSuccessToProto(m).toByteArray - case m: DurableDataEnvelope ⇒ durableDataEnvelopeToProto(m).toByteArray - case m: Changed[_] ⇒ changedToProto(m).toByteArray - case m: NotFound[_] ⇒ notFoundToProto(m).toByteArray - case m: GetFailure[_] ⇒ getFailureToProto(m).toByteArray - case m: Subscribe[_] ⇒ subscribeToProto(m).toByteArray - case m: Unsubscribe[_] ⇒ unsubscribeToProto(m).toByteArray - case m: Gossip ⇒ compress(gossipToProto(m)) - case WriteNack ⇒ dm.Empty.getDefaultInstance.toByteArray - case DeltaNack ⇒ dm.Empty.getDefaultInstance.toByteArray - case _ ⇒ + case m: DataEnvelope => dataEnvelopeToProto(m).toByteArray + case m: Write => writeCache.getOrAdd(m) + case WriteAck => writeAckBytes + case m: Read => readCache.getOrAdd(m) + case m: ReadResult => readResultToProto(m).toByteArray + case m: Status => statusToProto(m).toByteArray + case m: DeltaPropagation => deltaPropagationToProto(m).toByteArray + case m: Get[_] => getToProto(m).toByteArray + case m: GetSuccess[_] => getSuccessToProto(m).toByteArray + case m: DurableDataEnvelope => durableDataEnvelopeToProto(m).toByteArray + case m: Changed[_] => changedToProto(m).toByteArray + case m: NotFound[_] => notFoundToProto(m).toByteArray + case m: GetFailure[_] => getFailureToProto(m).toByteArray + case m: Subscribe[_] => subscribeToProto(m).toByteArray + case m: Unsubscribe[_] => unsubscribeToProto(m).toByteArray + case m: Gossip => compress(gossipToProto(m)) + case WriteNack => dm.Empty.getDefaultInstance.toByteArray + case DeltaNack => dm.Empty.getDefaultInstance.toByteArray + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass} in [${getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = fromBinaryMap.get(manifest) match { - case Some(f) ⇒ f(bytes) - case None ⇒ throw new NotSerializableException( + case Some(f) => f(bytes) + case None => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } @@ -258,7 +258,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) val b = dm.Status.newBuilder() b.setChunk(status.chunk).setTotChunks(status.totChunks) val entries = status.digests.foreach { - case (key, digest) ⇒ + case (key, digest) => b.addEntries(dm.Status.Entry.newBuilder(). setKey(key). setDigest(ByteString.copyFrom(digest.toArray))) @@ -269,15 +269,15 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) private def statusFromBinary(bytes: Array[Byte]): Status = { val status = dm.Status.parseFrom(bytes) Status( - status.getEntriesList.asScala.iterator.map(e ⇒ - e.getKey → AkkaByteString(e.getDigest.toByteArray())).toMap, + status.getEntriesList.asScala.iterator.map(e => + e.getKey -> AkkaByteString(e.getDigest.toByteArray())).toMap, status.getChunk, status.getTotChunks) } private def gossipToProto(gossip: Gossip): dm.Gossip = { val b = dm.Gossip.newBuilder().setSendBack(gossip.sendBack) val entries = gossip.updatedData.foreach { - case (key, data) ⇒ + case (key, data) => b.addEntries(dm.Gossip.Entry.newBuilder(). setKey(key). setEnvelope(dataEnvelopeToProto(data))) @@ -288,8 +288,8 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) private def gossipFromBinary(bytes: Array[Byte]): Gossip = { val gossip = dm.Gossip.parseFrom(decompress(bytes)) Gossip( - gossip.getEntriesList.asScala.iterator.map(e ⇒ - e.getKey → dataEnvelopeFromProto(e.getEnvelope)).toMap, + gossip.getEntriesList.asScala.iterator.map(e => + e.getKey -> dataEnvelopeFromProto(e.getEnvelope)).toMap, sendBack = gossip.getSendBack) } @@ -299,7 +299,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) if (deltaPropagation.reply) b.setReply(deltaPropagation.reply) val entries = deltaPropagation.deltas.foreach { - case (key, Delta(data, fromSeqNr, toSeqNr)) ⇒ + case (key, Delta(data, fromSeqNr, toSeqNr)) => val b2 = dm.DeltaPropagation.Entry.newBuilder() .setKey(key) .setEnvelope(dataEnvelopeToProto(data)) @@ -317,19 +317,19 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) DeltaPropagation( uniqueAddressFromProto(deltaPropagation.getFromNode), reply, - deltaPropagation.getEntriesList.asScala.iterator.map { e ⇒ + deltaPropagation.getEntriesList.asScala.iterator.map { e => val fromSeqNr = e.getFromSeqNr val toSeqNr = if (e.hasToSeqNr) e.getToSeqNr else fromSeqNr - e.getKey → Delta(dataEnvelopeFromProto(e.getEnvelope), fromSeqNr, toSeqNr) + e.getKey -> Delta(dataEnvelopeFromProto(e.getEnvelope), fromSeqNr, toSeqNr) }.toMap) } private def getToProto(get: Get[_]): dm.Get = { val consistencyValue = get.consistency match { - case ReadLocal ⇒ 1 - case ReadFrom(n, _) ⇒ n - case _: ReadMajority ⇒ 0 - case _: ReadAll ⇒ -1 + case ReadLocal => 1 + case ReadFrom(n, _) => n + case _: ReadMajority => 0 + case _: ReadAll => -1 } val b = dm.Get.newBuilder(). @@ -337,7 +337,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) setConsistency(consistencyValue). setTimeout(get.consistency.timeout.toMillis.toInt) - get.request.foreach(o ⇒ b.setRequest(otherMessageToProto(o))) + get.request.foreach(o => b.setRequest(otherMessageToProto(o))) b.build() } @@ -347,10 +347,10 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) val request = if (get.hasRequest()) Some(otherMessageFromProto(get.getRequest)) else None val timeout = Duration(get.getTimeout, TimeUnit.MILLISECONDS) val consistency = get.getConsistency match { - case 0 ⇒ ReadMajority(timeout) - case -1 ⇒ ReadAll(timeout) - case 1 ⇒ ReadLocal - case n ⇒ ReadFrom(n, timeout) + case 0 => ReadMajority(timeout) + case -1 => ReadAll(timeout) + case 1 => ReadLocal + case n => ReadFrom(n, timeout) } Get(key, consistency, request) } @@ -360,7 +360,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) setKey(otherMessageToProto(getSuccess.key)). setData(otherMessageToProto(getSuccess.dataValue)) - getSuccess.request.foreach(o ⇒ b.setRequest(otherMessageToProto(o))) + getSuccess.request.foreach(o => b.setRequest(otherMessageToProto(o))) b.build() } @@ -374,7 +374,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) private def notFoundToProto(notFound: NotFound[_]): dm.NotFound = { val b = dm.NotFound.newBuilder().setKey(otherMessageToProto(notFound.key)) - notFound.request.foreach(o ⇒ b.setRequest(otherMessageToProto(o))) + notFound.request.foreach(o => b.setRequest(otherMessageToProto(o))) b.build() } @@ -387,7 +387,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) private def getFailureToProto(getFailure: GetFailure[_]): dm.GetFailure = { val b = dm.GetFailure.newBuilder().setKey(otherMessageToProto(getFailure.key)) - getFailure.request.foreach(o ⇒ b.setRequest(otherMessageToProto(o))) + getFailure.request.foreach(o => b.setRequest(otherMessageToProto(o))) b.build() } @@ -437,15 +437,15 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) private def pruningToProto(entries: Map[UniqueAddress, PruningState]): Iterable[dm.DataEnvelope.PruningEntry] = { entries.map { - case (removedAddress, state) ⇒ + case (removedAddress, state) => val b = dm.DataEnvelope.PruningEntry.newBuilder(). setRemovedAddress(uniqueAddressToProto(removedAddress)) state match { - case PruningState.PruningInitialized(owner, seen) ⇒ - seen.toVector.sorted(Member.addressOrdering).map(addressToProto).foreach { a ⇒ b.addSeen(a) } + case PruningState.PruningInitialized(owner, seen) => + seen.toVector.sorted(Member.addressOrdering).map(addressToProto).foreach { a => b.addSeen(a) } b.setOwnerAddress(uniqueAddressToProto(owner)) b.setPerformed(false) - case PruningState.PruningPerformed(obsoleteTime) ⇒ + case PruningState.PruningPerformed(obsoleteTime) => b.setPerformed(true).setObsoleteTime(obsoleteTime) // TODO ownerAddress is only needed for PruningInitialized, but kept here for // wire backwards compatibility with 2.4.16 (required field) @@ -483,7 +483,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) if (pruningEntries.isEmpty) Map.empty else - pruningEntries.asScala.iterator.map { pruningEntry ⇒ + pruningEntries.asScala.iterator.map { pruningEntry => val state = if (pruningEntry.getPerformed) { // for wire compatibility with Akka 2.4.x @@ -494,7 +494,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) uniqueAddressFromProto(pruningEntry.getOwnerAddress), pruningEntry.getSeenList.asScala.iterator.map(addressFromProto).to(immutable.Set)) val removed = uniqueAddressFromProto(pruningEntry.getRemovedAddress) - removed → state + removed -> state }.toMap } @@ -518,8 +518,8 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) private def readResultToProto(readResult: ReadResult): dm.ReadResult = { val b = dm.ReadResult.newBuilder() readResult.envelope match { - case Some(d) ⇒ b.setEnvelope(dataEnvelopeToProto(d)) - case None ⇒ + case Some(d) => b.setEnvelope(dataEnvelopeToProto(d)) + case None => } b.build() } @@ -535,8 +535,8 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) private def durableDataEnvelopeToProto(durableDataEnvelope: DurableDataEnvelope): dm.DurableDataEnvelope = { // only keep the PruningPerformed entries val pruning = durableDataEnvelope.dataEnvelope.pruning.filter { - case (_, _: PruningPerformed) ⇒ true - case _ ⇒ false + case (_, _: PruningPerformed) => true + case _ => false } val builder = dm.DurableDataEnvelope.newBuilder() diff --git a/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/SerializationSupport.scala b/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/SerializationSupport.scala index 965e8f98ce..0004fe2b69 100644 --- a/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/SerializationSupport.scala +++ b/akka-distributed-data/src/main/scala/akka/cluster/ddata/protobuf/SerializationSupport.scala @@ -15,7 +15,7 @@ import akka.actor.ActorRef import akka.actor.Address import akka.actor.ExtendedActorSystem import akka.cluster.UniqueAddress -import akka.cluster.ddata.protobuf.msg.{ ReplicatorMessages ⇒ dm } +import akka.cluster.ddata.protobuf.msg.{ ReplicatorMessages => dm } import akka.serialization._ import akka.protobuf.ByteString import akka.protobuf.MessageLite @@ -69,8 +69,8 @@ trait SerializationSupport { val buffer = new Array[Byte](BufferSize) @tailrec def readChunk(): Unit = in.read(buffer) match { - case -1 ⇒ () - case n ⇒ + case -1 => () + case n => out.write(buffer, 0, n) readChunk() } @@ -81,9 +81,9 @@ trait SerializationSupport { } def addressToProto(address: Address): dm.Address.Builder = address match { - case Address(_, _, Some(host), Some(port)) ⇒ + case Address(_, _, Some(host), Some(port)) => dm.Address.newBuilder().setHostname(host).setPort(port) - case _ ⇒ throw new IllegalArgumentException(s"Address [${address}] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [${address}] could not be serialized: host or port missing.") } def addressFromProto(address: dm.Address): Address = @@ -108,7 +108,7 @@ trait SerializationSupport { def versionVectorToProto(versionVector: VersionVector): dm.VersionVector = { val b = dm.VersionVector.newBuilder() versionVector.versionsIterator.foreach { - case (node, value) ⇒ b.addEntries(dm.VersionVector.Entry.newBuilder(). + case (node, value) => b.addEntries(dm.VersionVector.Entry.newBuilder(). setNode(uniqueAddressToProto(node)).setVersion(value)) } b.build() @@ -124,8 +124,8 @@ trait SerializationSupport { else if (entries.size == 1) VersionVector(uniqueAddressFromProto(entries.get(0).getNode), entries.get(0).getVersion) else { - val versions: TreeMap[UniqueAddress, Long] = scala.collection.immutable.TreeMap.from(versionVector.getEntriesList.asScala.iterator.map(entry ⇒ - uniqueAddressFromProto(entry.getNode) → entry.getVersion)) + val versions: TreeMap[UniqueAddress, Long] = scala.collection.immutable.TreeMap.from(versionVector.getEntriesList.asScala.iterator.map(entry => + uniqueAddressFromProto(entry.getNode) -> entry.getVersion)) VersionVector(versions) } } diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/DurableDataSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/DurableDataSpec.scala index 9320cf262a..fcebc6b256 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/DurableDataSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/DurableDataSpec.scala @@ -44,20 +44,20 @@ object DurableDataSpec { class TestDurableStore(failLoad: Boolean, failStore: Boolean) extends Actor { import DurableStore._ def receive = { - case LoadAll ⇒ + case LoadAll => if (failLoad) throw new LoadFailed("failed to load durable distributed-data") with NoStackTrace else sender() ! LoadAllCompleted - case Store(_, _, reply) ⇒ + case Store(_, _, reply) => if (failStore) reply match { - case Some(StoreReply(_, failureMsg, replyTo)) ⇒ replyTo ! failureMsg - case None ⇒ + case Some(StoreReply(_, failureMsg, replyTo)) => replyTo ! failureMsg + case None => } else reply match { - case Some(StoreReply(successMsg, _, replyTo)) ⇒ replyTo ! successMsg - case None ⇒ + case Some(StoreReply(successMsg, _, replyTo)) => replyTo ! successMsg + case None => } } diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/JepsenInspiredInsertSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/JepsenInspiredInsertSpec.scala index 46ce31b0af..cfdcd11b72 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/JepsenInspiredInsertSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/JepsenInspiredInsertSpec.scala @@ -61,8 +61,8 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w // val totalCount = 2000 val expectedData = (0 until totalCount).toSet val data: Map[RoleName, Seq[Int]] = { - val nodeIndex = nodes.zipWithIndex.map { case (n, i) ⇒ i → n }.toMap - (0 until totalCount).groupBy(i ⇒ nodeIndex(i % nodeCount)) + val nodeIndex = nodes.zipWithIndex.map { case (n, i) => i -> n }.toMap + (0 until totalCount).groupBy(i => nodeIndex(i % nodeCount)) } lazy val myData: Seq[Int] = data(myself) @@ -102,7 +102,7 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w } runOn(controller) { - nodes.foreach { n ⇒ enterBarrier(n.name + "-joined") } + nodes.foreach { n => enterBarrier(n.name + "-joined") } } enterBarrier("after-setup") @@ -113,13 +113,13 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w val key = ORSetKey[Int]("A") runOn(nodes: _*) { val writeProbe = TestProbe() - val writeAcks = myData.map { i ⇒ + val writeAcks = myData.map { i => sleepDelay() replicator.tell(Update(key, ORSet(), WriteLocal, Some(i))(_ :+ i), writeProbe.ref) writeProbe.receiveOne(3.seconds) } - val successWriteAcks = writeAcks.collect { case success: UpdateSuccess[_] ⇒ success } - val failureWriteAcks = writeAcks.collect { case fail: UpdateFailure[_] ⇒ fail } + val successWriteAcks = writeAcks.collect { case success: UpdateSuccess[_] => success } + val failureWriteAcks = writeAcks.collect { case fail: UpdateFailure[_] => fail } successWriteAcks.map(_.request.get).toSet should be(myData.toSet) successWriteAcks.size should be(myData.size) failureWriteAcks should be(Nil) @@ -130,7 +130,7 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w awaitAssert { val readProbe = TestProbe() replicator.tell(Get(key, ReadLocal), readProbe.ref) - val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) ⇒ g.get(key) } + val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) => g.get(key) } result.elements should be(expectedData) } } @@ -146,13 +146,13 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w val writeMajority = WriteMajority(timeout) runOn(nodes: _*) { val writeProbe = TestProbe() - val writeAcks = myData.map { i ⇒ + val writeAcks = myData.map { i => sleepDelay() replicator.tell(Update(key, ORSet(), writeMajority, Some(i))(_ :+ i), writeProbe.ref) writeProbe.receiveOne(timeout + 1.second) } - val successWriteAcks = writeAcks.collect { case success: UpdateSuccess[_] ⇒ success } - val failureWriteAcks = writeAcks.collect { case fail: UpdateFailure[_] ⇒ fail } + val successWriteAcks = writeAcks.collect { case success: UpdateSuccess[_] => success } + val failureWriteAcks = writeAcks.collect { case fail: UpdateFailure[_] => fail } successWriteAcks.map(_.request.get).toSet should be(myData.toSet) successWriteAcks.size should be(myData.size) failureWriteAcks should be(Nil) @@ -163,7 +163,7 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w // read from majority of nodes, which is enough to retrieve all data val readProbe = TestProbe() replicator.tell(Get(key, readMajority), readProbe.ref) - val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) ⇒ g.get(key) } + val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) => g.get(key) } //val survivors = result.elements.size result.elements should be(expectedData) @@ -180,23 +180,23 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w val key = ORSetKey[Int]("C") runOn(controller) { sleepBeforePartition() - for (a ← List(n1, n4, n5); b ← List(n2, n3)) + for (a <- List(n1, n4, n5); b <- List(n2, n3)) testConductor.blackhole(a, b, Direction.Both).await sleepDuringPartition() - for (a ← List(n1, n4, n5); b ← List(n2, n3)) + for (a <- List(n1, n4, n5); b <- List(n2, n3)) testConductor.passThrough(a, b, Direction.Both).await enterBarrier("partition-healed-3") } runOn(nodes: _*) { val writeProbe = TestProbe() - val writeAcks = myData.map { i ⇒ + val writeAcks = myData.map { i => sleepDelay() replicator.tell(Update(key, ORSet(), WriteLocal, Some(i))(_ :+ i), writeProbe.ref) writeProbe.receiveOne(3.seconds) } - val successWriteAcks = writeAcks.collect { case success: UpdateSuccess[_] ⇒ success } - val failureWriteAcks = writeAcks.collect { case fail: UpdateFailure[_] ⇒ fail } + val successWriteAcks = writeAcks.collect { case success: UpdateSuccess[_] => success } + val failureWriteAcks = writeAcks.collect { case fail: UpdateFailure[_] => fail } successWriteAcks.map(_.request.get).toSet should be(myData.toSet) successWriteAcks.size should be(myData.size) failureWriteAcks should be(Nil) @@ -209,7 +209,7 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w awaitAssert { val readProbe = TestProbe() replicator.tell(Get(key, ReadLocal), readProbe.ref) - val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) ⇒ g.get(key) } + val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) => g.get(key) } result.elements should be(expectedData) } } @@ -225,23 +225,23 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w val writeMajority = WriteMajority(timeout) runOn(controller) { sleepBeforePartition() - for (a ← List(n1, n4, n5); b ← List(n2, n3)) + for (a <- List(n1, n4, n5); b <- List(n2, n3)) testConductor.blackhole(a, b, Direction.Both).await sleepDuringPartition() - for (a ← List(n1, n4, n5); b ← List(n2, n3)) + for (a <- List(n1, n4, n5); b <- List(n2, n3)) testConductor.passThrough(a, b, Direction.Both).await enterBarrier("partition-healed-4") } runOn(nodes: _*) { val writeProbe = TestProbe() - val writeAcks = myData.map { i ⇒ + val writeAcks = myData.map { i => sleepDelay() replicator.tell(Update(key, ORSet(), writeMajority, Some(i))(_ :+ i), writeProbe.ref) writeProbe.receiveOne(timeout + 1.second) } - val successWriteAcks = writeAcks.collect { case success: UpdateSuccess[_] ⇒ success } - val failureWriteAcks = writeAcks.collect { case fail: UpdateFailure[_] ⇒ fail } + val successWriteAcks = writeAcks.collect { case success: UpdateSuccess[_] => success } + val failureWriteAcks = writeAcks.collect { case fail: UpdateFailure[_] => fail } runOn(n1, n4, n5) { successWriteAcks.map(_.request.get).toSet should be(myData.toSet) successWriteAcks.size should be(myData.size) @@ -260,7 +260,7 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w runOn(n2, n3) { val readProbe = TestProbe() replicator.tell(Get(key, readMajority), readProbe.ref) - val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) ⇒ g.get(key) } + val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) => g.get(key) } //val survivors = result.elements.size result.elements should be(expectedData) } @@ -272,7 +272,7 @@ class JepsenInspiredInsertSpec extends MultiNodeSpec(JepsenInspiredInsertSpec) w awaitAssert { val readProbe = TestProbe() replicator.tell(Get(key, ReadLocal), readProbe.ref) - val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) ⇒ g.get(key) } + val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) => g.get(key) } result.elements should be(expectedData) } } diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/PerformanceSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/PerformanceSpec.scala index 2b05030b0d..395c46bc4a 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/PerformanceSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/PerformanceSpec.scala @@ -48,7 +48,7 @@ object PerformanceSpec extends MultiNodeConfig { class CountDown(latch: TestLatch) extends Actor { def receive = { - case _ ⇒ + case _ => latch.countDown() if (latch.isOpen) context.stop(self) @@ -85,9 +85,9 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe def repeat(description: String, keys: Iterable[ORSetKey[Int]], n: Int, expectedAfterReplication: Option[Set[Int]] = None, oneByOne: Boolean = false)( - block: (ORSetKey[Int], Int, ActorRef) ⇒ Unit, afterEachKey: ORSetKey[Int] ⇒ Unit = _ ⇒ ()): Unit = { + block: (ORSetKey[Int], Int, ActorRef) => Unit, afterEachKey: ORSetKey[Int] => Unit = _ => ()): Unit = { - keys.foreach { key ⇒ + keys.foreach { key => val startTime = System.nanoTime() runOn(n1) { val latch = TestLatch(n) @@ -106,7 +106,7 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe if (!oneByOne) Await.ready(latch, 10.seconds + (2.second * factor)) } - expectedAfterReplication.foreach { expected ⇒ + expectedAfterReplication.foreach { expected => enterBarrier("repeat-" + key + "-before-awaitReplicated") awaitReplicated(key, expected) enterBarrier("repeat-" + key + "-after-awaitReplicated") @@ -124,14 +124,14 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe } def awaitReplicated(keys: Iterable[ORSetKey[Int]], expectedData: Set[Int]): Unit = - keys.foreach { key ⇒ awaitReplicated(key, expectedData) } + keys.foreach { key => awaitReplicated(key, expectedData) } def awaitReplicated(key: ORSetKey[Int], expectedData: Set[Int]): Unit = { within(20.seconds) { awaitAssert { val readProbe = TestProbe() replicator.tell(Get(key, ReadLocal), readProbe.ref) - val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) ⇒ g.get(key) } + val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) => g.get(key) } result.elements should be(expectedData) } } @@ -153,50 +153,50 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe } "be great for ORSet Update WriteLocal" taggedAs PerformanceTest in { - val keys = (1 to repeatCount).map(n ⇒ ORSetKey[Int]("A" + n)) + val keys = (1 to repeatCount).map(n => ORSetKey[Int]("A" + n)) val n = 1000 * factor val expectedData = (0 until n).toSet - repeat("ORSet Update WriteLocal", keys, n)({ (key, i, replyTo) ⇒ + repeat("ORSet Update WriteLocal", keys, n)({ (key, i, replyTo) => replicator.tell(Update(key, ORSet(), WriteLocal)(_ :+ i), replyTo) - }, key ⇒ awaitReplicated(key, expectedData)) + }, key => awaitReplicated(key, expectedData)) enterBarrier("after-1") } "be blazingly fast for ORSet Get ReadLocal" taggedAs PerformanceTest in { - val keys = (1 to repeatCount).map(n ⇒ ORSetKey[Int]("A" + n)) - repeat("Get ReadLocal", keys, 100000 * factor) { (key, _, replyTo) ⇒ + val keys = (1 to repeatCount).map(n => ORSetKey[Int]("A" + n)) + repeat("Get ReadLocal", keys, 100000 * factor) { (key, _, replyTo) => replicator.tell(Get(key, ReadLocal), replyTo) } enterBarrier("after-2") } "be good for ORSet Update WriteLocal and gossip replication" taggedAs PerformanceTest in { - val keys = (1 to repeatCount).map(n ⇒ ORSetKey[Int]("B" + n)) + val keys = (1 to repeatCount).map(n => ORSetKey[Int]("B" + n)) val n = 200 * factor val expected = Some((0 until n).toSet) - repeat("ORSet Update WriteLocal + gossip", keys, n, expected) { (key, i, replyTo) ⇒ + repeat("ORSet Update WriteLocal + gossip", keys, n, expected) { (key, i, replyTo) => replicator.tell(Update(key, ORSet(), WriteLocal)(_ :+ i), replyTo) } enterBarrier("after-3") } "be good for ORSet Update WriteLocal and gossip of existing keys" taggedAs PerformanceTest in { - val keys = (1 to repeatCount).map(n ⇒ ORSetKey[Int]("B" + n)) + val keys = (1 to repeatCount).map(n => ORSetKey[Int]("B" + n)) val n = 200 * factor val expected = Some((0 until n).toSet ++ (0 until n).map(-_).toSet) - repeat("ORSet Update WriteLocal existing + gossip", keys, n, expected) { (key, i, replyTo) ⇒ + repeat("ORSet Update WriteLocal existing + gossip", keys, n, expected) { (key, i, replyTo) => replicator.tell(Update(key, ORSet(), WriteLocal)(_ :+ (-i)), replyTo) } enterBarrier("after-4") } "be good for ORSet Update WriteTwo and gossip replication" taggedAs PerformanceTest in { - val keys = (1 to repeatCount).map(n ⇒ ORSetKey[Int]("C" + n)) + val keys = (1 to repeatCount).map(n => ORSetKey[Int]("C" + n)) val n = 200 * factor val expected = Some((0 until n).toSet) val writeTwo = WriteTo(2, timeout) - repeat("ORSet Update WriteTwo + gossip", keys, n, expected) { (key, i, replyTo) ⇒ + repeat("ORSet Update WriteTwo + gossip", keys, n, expected) { (key, i, replyTo) => replicator.tell(Update(key, ORSet(), writeTwo)(_ :+ i), replyTo) } enterBarrier("after-5") @@ -209,7 +209,7 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe runOn(n1, n2, n3) { val latch = TestLatch(n) val replyTo = system.actorOf(countDownProps(latch)) - for (_ ← 0 until n) + for (_ <- 0 until n) replicator.tell(Update(key, GCounter(), WriteLocal)(_ :+ 1), replyTo) Await.ready(latch, 5.seconds + (1.second * factor)) enterBarrier("update-done-6") @@ -228,7 +228,7 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe awaitAssert { val readProbe = TestProbe() replicator.tell(Get(key, ReadLocal), readProbe.ref) - val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) ⇒ g.get(key) } + val result = readProbe.expectMsgPF() { case g @ GetSuccess(`key`, _) => g.get(key) } result.value should be(3 * n) } } @@ -244,20 +244,20 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe } "be good for ORSet one-by-one deltas" taggedAs PerformanceTest in { - val keys = (1 to repeatCount).map(n ⇒ ORSetKey[Int]("E" + n)) + val keys = (1 to repeatCount).map(n => ORSetKey[Int]("E" + n)) val n = 300 * factor val writeMajority = WriteMajority(timeout) - repeat("ORSet Update one-by-one deltas", keys, n, oneByOne = true) { (key, i, replyTo) ⇒ + repeat("ORSet Update one-by-one deltas", keys, n, oneByOne = true) { (key, i, replyTo) => replicator.tell(Update(key, ORSet(), writeMajority)(_ :+ i), replyTo) } enterBarrier("after-7") } "be good for ORSet deltas" taggedAs PerformanceTest in { - val keys = (1 to repeatCount).map(n ⇒ ORSetKey[Int]("F" + n)) + val keys = (1 to repeatCount).map(n => ORSetKey[Int]("F" + n)) val n = 200 * factor val writeMajority = WriteMajority(timeout) - repeat("ORSet Update deltas", keys, n, oneByOne = false) { (key, i, replyTo) ⇒ + repeat("ORSet Update deltas", keys, n, oneByOne = false) { (key, i, replyTo) => replicator.tell(Update(key, ORSet(), writeMajority)(_ :+ i), replyTo) } enterBarrier("after-8") diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorChaosSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorChaosSpec.scala index 302119064f..2a40abcb40 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorChaosSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorChaosSpec.scala @@ -69,11 +69,11 @@ class ReplicatorChaosSpec extends MultiNodeSpec(ReplicatorChaosSpec) with STMult awaitAssert { replicator ! Get(key, ReadLocal) val value = expectMsgPF() { - case g @ GetSuccess(`key`, _) ⇒ g.dataValue match { - case c: GCounter ⇒ c.value - case c: PNCounter ⇒ c.value - case c: GSet[_] ⇒ c.elements - case c: ORSet[_] ⇒ c.elements + case g @ GetSuccess(`key`, _) => g.dataValue match { + case c: GCounter => c.value + case c: PNCounter => c.value + case c: GSet[_] => c.elements + case c: ORSet[_] => c.elements } } value should be(expected) @@ -105,7 +105,7 @@ class ReplicatorChaosSpec extends MultiNodeSpec(ReplicatorChaosSpec) with STMult } runOn(first) { - for (_ ← 0 until 5) { + for (_ <- 0 until 5) { replicator ! Update(KeyA, GCounter(), WriteLocal)(_ :+ 1) replicator ! Update(KeyB, PNCounter(), WriteLocal)(_ decrement 1) replicator ! Update(KeyC, GCounter(), WriteAll(timeout))(_ :+ 1) @@ -163,7 +163,7 @@ class ReplicatorChaosSpec extends MultiNodeSpec(ReplicatorChaosSpec) with STMult val side1 = Seq(first, second) val side2 = Seq(third, fourth, fifth) runOn(first) { - for (a ← side1; b ← side2) + for (a <- side1; b <- side2) testConductor.blackhole(a, b, Direction.Both).await } enterBarrier("split") @@ -216,7 +216,7 @@ class ReplicatorChaosSpec extends MultiNodeSpec(ReplicatorChaosSpec) with STMult val side1 = Seq(first, second) val side2 = Seq(third, fifth) // fourth was shutdown runOn(first) { - for (a ← side1; b ← side2) + for (a <- side1; b <- side2) testConductor.passThrough(a, b, Direction.Both).await } enterBarrier("split-repaired") diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorDeltaSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorDeltaSpec.scala index 9a39c35322..6de66619e8 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorDeltaSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorDeltaSpec.scala @@ -73,25 +73,25 @@ object ReplicatorDeltaSpec extends MultiNodeConfig { def consistency(): WriteConsistency = { rnd.nextInt(100) match { - case n if n < 90 ⇒ WriteLocal - case n if n < 95 ⇒ writeTwo - case n if n < 100 ⇒ writeMajority + case n if n < 90 => WriteLocal + case n if n < 95 => writeTwo + case n if n < 100 => writeMajority } } def rndPnCounterkey(): PNCounterKey = { rnd.nextInt(3) match { - case 0 ⇒ KeyA - case 1 ⇒ KeyB - case 2 ⇒ KeyC + case 0 => KeyA + case 1 => KeyB + case 2 => KeyC } } def rndOrSetkey(): ORSetKey[String] = { rnd.nextInt(3) match { - case 0 ⇒ KeyD - case 1 ⇒ KeyE - case 2 ⇒ KeyF + case 0 => KeyD + case 1 => KeyE + case 2 => KeyF } } @@ -111,12 +111,12 @@ object ReplicatorDeltaSpec extends MultiNodeConfig { availableForRemove.toVector(rnd.nextInt(availableForRemove.size)) } - (0 to (30 + rnd.nextInt(10))).map { _ ⇒ + (0 to (30 + rnd.nextInt(10))).map { _ => rnd.nextInt(4) match { - case 0 ⇒ Delay(rnd.nextInt(500)) - case 1 ⇒ Incr(rndPnCounterkey(), rnd.nextInt(100), consistency()) - case 2 ⇒ Decr(rndPnCounterkey(), rnd.nextInt(10), consistency()) - case 3 ⇒ + case 0 => Delay(rnd.nextInt(500)) + case 1 => Incr(rndPnCounterkey(), rnd.nextInt(100), consistency()) + case 2 => Decr(rndPnCounterkey(), rnd.nextInt(10), consistency()) + case 3 => // ORSet val key = rndOrSetkey() // only removals for KeyF on node first @@ -199,11 +199,11 @@ class ReplicatorDeltaSpec extends MultiNodeSpec(ReplicatorDeltaSpec) with STMult runOn(first) { // by setting something for each key we don't have to worry about NotFound - List(KeyA, KeyB, KeyC).foreach { key ⇒ + List(KeyA, KeyB, KeyC).foreach { key => fullStateReplicator ! Update(key, PNCounter.empty, WriteLocal)(_ :+ 1) deltaReplicator ! Update(key, PNCounter.empty, WriteLocal)(_ :+ 1) } - List(KeyD, KeyE, KeyF).foreach { key ⇒ + List(KeyD, KeyE, KeyF).foreach { key => fullStateReplicator ! Update(key, ORSet.empty[String], WriteLocal)(_ :+ "a") deltaReplicator ! Update(key, ORSet.empty[String], WriteLocal)(_ :+ "a") } @@ -213,14 +213,14 @@ class ReplicatorDeltaSpec extends MultiNodeSpec(ReplicatorDeltaSpec) with STMult within(5.seconds) { awaitAssert { val p = TestProbe() - List(KeyA, KeyB, KeyC).foreach { key ⇒ + List(KeyA, KeyB, KeyC).foreach { key => fullStateReplicator.tell(Get(key, ReadLocal), p.ref) p.expectMsgType[GetSuccess[PNCounter]].dataValue.getValue.intValue should be(1) } } awaitAssert { val p = TestProbe() - List(KeyD, KeyE, KeyF).foreach { key ⇒ + List(KeyD, KeyE, KeyF).foreach { key => deltaReplicator.tell(Get(key, ReadLocal), p.ref) p.expectMsgType[GetSuccess[ORSet[String]]].dataValue.elements should ===(Set("a")) } @@ -336,7 +336,7 @@ class ReplicatorDeltaSpec extends MultiNodeSpec(ReplicatorDeltaSpec) with STMult // NoDeltaPlaceholder from previous updates and the incr(4) delta will also // be folded into NoDeltaPlaceholder and not propagated as delta. A few DeltaPropagationTick // are needed to send to all and flush buffer. - roles.foreach { _ ⇒ + roles.foreach { _ => deltaReplicator ! Replicator.Internal.DeltaPropagationTick } deltaReplicator.tell(Update(KeyHigh, Highest(0), WriteLocal)(_.incr(4)), p1.ref) @@ -362,24 +362,24 @@ class ReplicatorDeltaSpec extends MultiNodeSpec(ReplicatorDeltaSpec) with STMult // perform random operations with both delta and full-state replicators // and compare that the end result is the same - for (op ← operations) { + for (op <- operations) { log.debug("operation: {}", op) op match { - case Delay(d) ⇒ Thread.sleep(d) - case Incr(key, n, consistency) ⇒ + case Delay(d) => Thread.sleep(d) + case Incr(key, n, consistency) => fullStateReplicator ! Update(key, PNCounter.empty, consistency)(_ :+ n) deltaReplicator ! Update(key, PNCounter.empty, consistency)(_ :+ n) - case Decr(key, n, consistency) ⇒ + case Decr(key, n, consistency) => fullStateReplicator ! Update(key, PNCounter.empty, consistency)(_ decrement n) deltaReplicator ! Update(key, PNCounter.empty, consistency)(_ decrement n) - case Add(key, elem, consistency) ⇒ + case Add(key, elem, consistency) => // to have an deterministic result when mixing add/remove we can only perform // the ORSet operations from one node runOn((if (key == KeyF) List(first) else List(first, second, third)): _*) { fullStateReplicator ! Update(key, ORSet.empty[String], consistency)(_ :+ elem) deltaReplicator ! Update(key, ORSet.empty[String], consistency)(_ :+ elem) } - case Remove(key, elem, consistency) ⇒ + case Remove(key, elem, consistency) => runOn(first) { fullStateReplicator ! Update(key, ORSet.empty[String], consistency)(_ remove elem) deltaReplicator ! Update(key, ORSet.empty[String], consistency)(_ remove elem) @@ -389,7 +389,7 @@ class ReplicatorDeltaSpec extends MultiNodeSpec(ReplicatorDeltaSpec) with STMult enterBarrier("updated-2") - List(KeyA, KeyB, KeyC).foreach { key ⇒ + List(KeyA, KeyB, KeyC).foreach { key => within(5.seconds) { awaitAssert { val p = TestProbe() @@ -402,7 +402,7 @@ class ReplicatorDeltaSpec extends MultiNodeSpec(ReplicatorDeltaSpec) with STMult } } - List(KeyD, KeyE, KeyF).foreach { key ⇒ + List(KeyD, KeyE, KeyF).foreach { key => within(5.seconds) { awaitAssert { val p = TestProbe() @@ -417,7 +417,7 @@ class ReplicatorDeltaSpec extends MultiNodeSpec(ReplicatorDeltaSpec) with STMult enterBarrierAfterTestStep() } catch { - case e: Throwable ⇒ + case e: Throwable => info(s"random operations on [${myself.name}]: ${operations.mkString(", ")}") throw e } diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorMapDeltaSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorMapDeltaSpec.scala index 702268cb6f..b6cc32d45c 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorMapDeltaSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorMapDeltaSpec.scala @@ -77,41 +77,41 @@ object ReplicatorMapDeltaSpec extends MultiNodeConfig { def consistency(): WriteConsistency = { rnd.nextInt(100) match { - case n if n < 90 ⇒ WriteLocal - case n if n < 95 ⇒ writeTwo - case n if n < 100 ⇒ writeMajority + case n if n < 90 => WriteLocal + case n if n < 95 => writeTwo + case n if n < 100 => writeMajority } } def rndPnCounterkey(): (PNCounterMapKey[String], String) = { rnd.nextInt(3) match { - case 0 ⇒ KeyA - case 1 ⇒ KeyB - case 2 ⇒ KeyC + case 0 => KeyA + case 1 => KeyB + case 2 => KeyC } } def rndOrSetkeyVD(): (ORMultiMapKey[String, String], String) = { rnd.nextInt(3) match { - case 0 ⇒ KeyD - case 1 ⇒ KeyE - case 2 ⇒ KeyF + case 0 => KeyD + case 1 => KeyE + case 2 => KeyF } } def rndOrSetkeyNoVD(): (ORMultiMapKey[String, String], String) = { rnd.nextInt(3) match { - case 0 ⇒ KeyG - case 1 ⇒ KeyH - case 2 ⇒ KeyI + case 0 => KeyG + case 1 => KeyH + case 2 => KeyI } } def rndOrSetkeyOM(): (ORMapKey[String, ORSet[String]], String) = { rnd.nextInt(3) match { - case 0 ⇒ KeyJ - case 1 ⇒ KeyK - case 2 ⇒ KeyL + case 0 => KeyJ + case 1 => KeyK + case 2 => KeyL } } @@ -131,12 +131,12 @@ object ReplicatorMapDeltaSpec extends MultiNodeConfig { availableForRemove.toVector(rnd.nextInt(availableForRemove.size)) } - (0 to (50 + rnd.nextInt(10))).map { _ ⇒ + (0 to (50 + rnd.nextInt(10))).map { _ => rnd.nextInt(6) match { - case 0 ⇒ Delay(rnd.nextInt(500)) - case 1 ⇒ Incr(rndPnCounterkey(), rnd.nextInt(100), consistency()) - case 2 ⇒ Decr(rndPnCounterkey(), rnd.nextInt(10), consistency()) - case 3 ⇒ + case 0 => Delay(rnd.nextInt(500)) + case 1 => Incr(rndPnCounterkey(), rnd.nextInt(100), consistency()) + case 2 => Decr(rndPnCounterkey(), rnd.nextInt(10), consistency()) + case 3 => // ORMultiMap.withValueDeltas val key = rndOrSetkeyVD() // only removals for KeyF on node first @@ -144,7 +144,7 @@ object ReplicatorMapDeltaSpec extends MultiNodeConfig { RemoveVD(key, rndRemoveElement(), consistency()) else AddVD(key, rndAddElement(), consistency()) - case 4 ⇒ + case 4 => // ORMultiMap - vanilla variant - without Value Deltas val key = rndOrSetkeyNoVD() // only removals for KeyI on node first @@ -152,7 +152,7 @@ object ReplicatorMapDeltaSpec extends MultiNodeConfig { RemoveNoVD(key, rndRemoveElement(), consistency()) else AddNoVD(key, rndAddElement(), consistency()) - case 5 ⇒ + case 5 => // Vanilla ORMap - with ORSet inside val key = rndOrSetkeyOM() // only removals for KeyL on node first @@ -241,21 +241,21 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with runOn(first) { // by setting something for each key we don't have to worry about NotFound - List(KeyA, KeyB, KeyC).foreach { key ⇒ + List(KeyA, KeyB, KeyC).foreach { key => fullStateReplicator ! Update(key._1, PNCounterMap.empty[String], WriteLocal)(_.incrementBy(key._2, 1)) deltaReplicator ! Update(key._1, PNCounterMap.empty[String], WriteLocal)(_.incrementBy(key._2, 1)) } - List(KeyD, KeyE, KeyF).foreach { key ⇒ - fullStateReplicator ! Update(key._1, ORMultiMap.emptyWithValueDeltas[String, String], WriteLocal)(_ :+ (key._2 → Set("a"))) - deltaReplicator ! Update(key._1, ORMultiMap.emptyWithValueDeltas[String, String], WriteLocal)(_ :+ (key._2 → Set("a"))) + List(KeyD, KeyE, KeyF).foreach { key => + fullStateReplicator ! Update(key._1, ORMultiMap.emptyWithValueDeltas[String, String], WriteLocal)(_ :+ (key._2 -> Set("a"))) + deltaReplicator ! Update(key._1, ORMultiMap.emptyWithValueDeltas[String, String], WriteLocal)(_ :+ (key._2 -> Set("a"))) } - List(KeyG, KeyH, KeyI).foreach { key ⇒ - fullStateReplicator ! Update(key._1, ORMultiMap.empty[String, String], WriteLocal)(_ :+ (key._2 → Set("a"))) - deltaReplicator ! Update(key._1, ORMultiMap.empty[String, String], WriteLocal)(_ :+ (key._2 → Set("a"))) + List(KeyG, KeyH, KeyI).foreach { key => + fullStateReplicator ! Update(key._1, ORMultiMap.empty[String, String], WriteLocal)(_ :+ (key._2 -> Set("a"))) + deltaReplicator ! Update(key._1, ORMultiMap.empty[String, String], WriteLocal)(_ :+ (key._2 -> Set("a"))) } - List(KeyJ, KeyK, KeyL).foreach { key ⇒ - fullStateReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(_ :+ (key._2 → (ORSet.empty :+ "a"))) - deltaReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(_ :+ (key._2 → (ORSet.empty :+ "a"))) + List(KeyJ, KeyK, KeyL).foreach { key => + fullStateReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(_ :+ (key._2 -> (ORSet.empty :+ "a"))) + deltaReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(_ :+ (key._2 -> (ORSet.empty :+ "a"))) } } enterBarrier("updated-1") @@ -263,28 +263,28 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with within(5.seconds) { awaitAssert { val p = TestProbe() - List(KeyA, KeyB, KeyC).foreach { key ⇒ + List(KeyA, KeyB, KeyC).foreach { key => fullStateReplicator.tell(Get(key._1, ReadLocal), p.ref) p.expectMsgType[GetSuccess[PNCounterMap[String]]].dataValue.get(key._2).get.intValue should be(1) } } awaitAssert { val p = TestProbe() - List(KeyD, KeyE, KeyF).foreach { key ⇒ + List(KeyD, KeyE, KeyF).foreach { key => fullStateReplicator.tell(Get(key._1, ReadLocal), p.ref) p.expectMsgType[GetSuccess[ORMultiMap[String, String]]].dataValue.get(key._2) should ===(Some(Set("a"))) } } awaitAssert { val p = TestProbe() - List(KeyG, KeyH, KeyI).foreach { key ⇒ + List(KeyG, KeyH, KeyI).foreach { key => fullStateReplicator.tell(Get(key._1, ReadLocal), p.ref) p.expectMsgType[GetSuccess[ORMultiMap[String, String]]].dataValue.get(key._2) should ===(Some(Set("a"))) } } awaitAssert { val p = TestProbe() - List(KeyJ, KeyK, KeyL).foreach { key ⇒ + List(KeyJ, KeyK, KeyL).foreach { key => fullStateReplicator.tell(Get(key._1, ReadLocal), p.ref) val res = p.expectMsgType[GetSuccess[ORMap[String, ORSet[String]]]].dataValue.get(key._2) res.map(_.elements) should ===(Some(Set("a"))) @@ -300,7 +300,7 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with val errorLogProbe = TestProbe() system.eventStream.subscribe(errorLogProbe.ref, classOf[Error]) runOn(first) { - for (_ ← 1 to N; key ← List(KeyA, KeyB)) { + for (_ <- 1 to N; key <- List(KeyA, KeyB)) { ordinaryReplicator ! Update(key._1, PNCounterMap.empty[String], WriteLocal)(_.incrementBy(key._2, 1)) } } @@ -309,7 +309,7 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with within(5.seconds) { awaitAssert { val p = TestProbe() - List(KeyA, KeyB).foreach { key ⇒ + List(KeyA, KeyB).foreach { key => ordinaryReplicator.tell(Get(key._1, ReadLocal), p.ref) p.expectMsgType[GetSuccess[PNCounterMap[String]]].dataValue.get(key._2).get.intValue should be(N) } @@ -330,58 +330,58 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with // perform random operations with both delta and full-state replicators // and compare that the end result is the same - for (op ← operations) { + for (op <- operations) { log.debug("operation: {}", op) op match { - case Delay(d) ⇒ Thread.sleep(d) - case Incr(key, n, _) ⇒ + case Delay(d) => Thread.sleep(d) + case Incr(key, n, _) => fullStateReplicator ! Update(key._1, PNCounterMap.empty[String], WriteLocal)(_ incrementBy (key._2, n)) deltaReplicator ! Update(key._1, PNCounterMap.empty[String], WriteLocal)(_ incrementBy (key._2, n)) - case Decr(key, n, _) ⇒ + case Decr(key, n, _) => fullStateReplicator ! Update(key._1, PNCounterMap.empty[String], WriteLocal)(_ decrementBy (key._2, n)) deltaReplicator ! Update(key._1, PNCounterMap.empty[String], WriteLocal)(_ decrementBy (key._2, n)) - case AddVD(key, elem, _) ⇒ + case AddVD(key, elem, _) => // to have an deterministic result when mixing add/remove we can only perform // the ORSet operations from one node runOn((if (key == KeyF) List(first) else List(first, second, third)): _*) { fullStateReplicator ! Update(key._1, ORMultiMap.emptyWithValueDeltas[String, String], WriteLocal)(_ addBindingBy (key._2, elem)) deltaReplicator ! Update(key._1, ORMultiMap.emptyWithValueDeltas[String, String], WriteLocal)(_ addBindingBy (key._2, elem)) } - case RemoveVD(key, elem, _) ⇒ + case RemoveVD(key, elem, _) => runOn(first) { fullStateReplicator ! Update(key._1, ORMultiMap.emptyWithValueDeltas[String, String], WriteLocal)(_ removeBindingBy (key._2, elem)) deltaReplicator ! Update(key._1, ORMultiMap.emptyWithValueDeltas[String, String], WriteLocal)(_ removeBindingBy (key._2, elem)) } - case AddNoVD(key, elem, _) ⇒ + case AddNoVD(key, elem, _) => // to have an deterministic result when mixing add/remove we can only perform // the ORSet operations from one node runOn((if (key == KeyI) List(first) else List(first, second, third)): _*) { fullStateReplicator ! Update(key._1, ORMultiMap.empty[String, String], WriteLocal)(_ addBindingBy (key._2, elem)) deltaReplicator ! Update(key._1, ORMultiMap.empty[String, String], WriteLocal)(_ addBindingBy (key._2, elem)) } - case RemoveNoVD(key, elem, _) ⇒ + case RemoveNoVD(key, elem, _) => runOn(first) { fullStateReplicator ! Update(key._1, ORMultiMap.empty[String, String], WriteLocal)(_ removeBindingBy (key._2, elem)) deltaReplicator ! Update(key._1, ORMultiMap.empty[String, String], WriteLocal)(_ removeBindingBy (key._2, elem)) } - case AddOM(key, elem, _) ⇒ + case AddOM(key, elem, _) => // to have an deterministic result when mixing add/remove we can only perform // the ORSet operations from one node runOn((if (key == KeyL) List(first) else List(first, second, third)): _*) { - fullStateReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(om ⇒ addElementToORMap(om, key._2, elem)) - deltaReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(om ⇒ addElementToORMap(om, key._2, elem)) + fullStateReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(om => addElementToORMap(om, key._2, elem)) + deltaReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(om => addElementToORMap(om, key._2, elem)) } - case RemoveOM(key, elem, _) ⇒ + case RemoveOM(key, elem, _) => runOn(first) { - fullStateReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(om ⇒ removeElementFromORMap(om, key._2, elem)) - deltaReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(om ⇒ removeElementFromORMap(om, key._2, elem)) + fullStateReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(om => removeElementFromORMap(om, key._2, elem)) + deltaReplicator ! Update(key._1, ORMap.empty[String, ORSet[String]], WriteLocal)(om => removeElementFromORMap(om, key._2, elem)) } } } enterBarrier("updated-3") - List(KeyA, KeyB, KeyC).foreach { key ⇒ + List(KeyA, KeyB, KeyC).foreach { key => within(5.seconds) { awaitAssert { val p = TestProbe() @@ -394,7 +394,7 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with } } - List(KeyD, KeyE, KeyF).foreach { key ⇒ + List(KeyD, KeyE, KeyF).foreach { key => within(5.seconds) { awaitAssert { val p = TestProbe() @@ -407,7 +407,7 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with } } - List(KeyG, KeyH, KeyI).foreach { key ⇒ + List(KeyG, KeyH, KeyI).foreach { key => within(5.seconds) { awaitAssert { val p = TestProbe() @@ -420,7 +420,7 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with } } - List(KeyJ, KeyK, KeyL).foreach { key ⇒ + List(KeyJ, KeyK, KeyL).foreach { key => within(5.seconds) { awaitAssert { val p = TestProbe() @@ -435,7 +435,7 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with enterBarrierAfterTestStep() } catch { - case e: Throwable ⇒ + case e: Throwable => info(s"random operations on [${myself.name}]: ${operations.mkString(", ")}") throw e } diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorORSetDeltaSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorORSetDeltaSpec.scala index 933582e782..7723556c74 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorORSetDeltaSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorORSetDeltaSpec.scala @@ -64,8 +64,8 @@ class ReplicatorORSetDeltaSpec extends MultiNodeSpec(ReplicatorORSetDeltaSpec) w awaitAssert { replicator ! Get(key, ReadLocal) val value = expectMsgPF() { - case g @ GetSuccess(`key`, _) ⇒ g.dataValue match { - case c: ORSet[_] ⇒ c.elements + case g @ GetSuccess(`key`, _) => g.dataValue match { + case c: ORSet[_] => c.elements } } value should be(expected) diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorPruningSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorPruningSpec.scala index cb84450858..acb6ced7cb 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorPruningSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorPruningSpec.scala @@ -78,8 +78,8 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST cluster.subscribe(memberProbe.ref, initialStateMode = InitialStateAsEvents, classOf[MemberUp]) val thirdUniqueAddress = { val member = memberProbe.fishForMessage(3.seconds) { - case MemberUp(m) if m.address == node(third).address ⇒ true - case _ ⇒ false + case MemberUp(m) if m.address == node(third).address => true + case _ => false }.asInstanceOf[MemberUp].member member.uniqueAddress } @@ -93,10 +93,10 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST replicator ! Update(KeyC, PNCounterMap.empty[String], WriteAll(timeout)) { _.incrementBy("x", 1).incrementBy("y", 1) } expectMsg(UpdateSuccess(KeyC, None)) - replicator ! Update(KeyD, ORMultiMap.empty[String, String], WriteAll(timeout)) { _ :+ ("a" → Set("A")) } + replicator ! Update(KeyD, ORMultiMap.empty[String, String], WriteAll(timeout)) { _ :+ ("a" -> Set("A")) } expectMsg(UpdateSuccess(KeyD, None)) - replicator ! Update(KeyE, ORMap.empty[String, GSet[String]], WriteAll(timeout)) { _ :+ ("a" → GSet.empty[String].add("A")) } + replicator ! Update(KeyE, ORMap.empty[String, GSet[String]], WriteAll(timeout)) { _ :+ ("a" -> GSet.empty[String].add("A")) } expectMsg(UpdateSuccess(KeyE, None)) enterBarrier("updates-done") @@ -152,7 +152,7 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST awaitAssert { replicator ! Get(KeyA, ReadLocal) expectMsgPF() { - case g @ GetSuccess(KeyA, _) ⇒ + case g @ GetSuccess(KeyA, _) => val value = g.get(KeyA).value.toInt values += value value should be(9) @@ -165,7 +165,7 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST awaitAssert { replicator ! Get(KeyB, ReadLocal) expectMsgPF() { - case g @ GetSuccess(KeyB, _) ⇒ + case g @ GetSuccess(KeyB, _) => g.get(KeyB).elements should be(Set("a", "b", "c")) g.get(KeyB).needPruningFrom(thirdUniqueAddress) should be(false) } @@ -175,8 +175,8 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST awaitAssert { replicator ! Get(KeyC, ReadLocal) expectMsgPF() { - case g @ GetSuccess(KeyC, _) ⇒ - g.get(KeyC).entries should be(Map("x" → 3L, "y" → 3L)) + case g @ GetSuccess(KeyC, _) => + g.get(KeyC).entries should be(Map("x" -> 3L, "y" -> 3L)) g.get(KeyC).needPruningFrom(thirdUniqueAddress) should be(false) } } @@ -185,7 +185,7 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST awaitAssert { replicator ! Get(KeyD, ReadLocal) expectMsgPF() { - case g @ GetSuccess(KeyD, _) ⇒ + case g @ GetSuccess(KeyD, _) => g.get(KeyD).entries("a") should be(Set("A")) g.get(KeyD).needPruningFrom(thirdUniqueAddress) should be(false) } @@ -195,7 +195,7 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST awaitAssert { replicator ! Get(KeyE, ReadLocal) expectMsgPF() { - case g @ GetSuccess(KeyE, _) ⇒ + case g @ GetSuccess(KeyE, _) => g.get(KeyE).needPruningFrom(thirdUniqueAddress) should be(false) } } @@ -205,12 +205,12 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST // after pruning performed we should not be able to update with data from removed node def updateAfterPruning(expectedValue: Int): Unit = { - replicator ! Update(KeyA, GCounter(), WriteAll(timeout), None) { existing ⇒ + replicator ! Update(KeyA, GCounter(), WriteAll(timeout), None) { existing => // inject data from removed node to simulate bad data existing.merge(oldCounter) :+ 1 } expectMsgPF() { - case UpdateSuccess(KeyA, _) ⇒ + case UpdateSuccess(KeyA, _) => replicator ! Get(KeyA, ReadLocal) val retrieved = expectMsgType[GetSuccess[GCounter]].dataValue retrieved.value should be(expectedValue) diff --git a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorSpec.scala b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorSpec.scala index 561d6ef5d6..d069f8c7bc 100644 --- a/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorSpec.scala +++ b/akka-distributed-data/src/multi-jvm/scala/akka/cluster/ddata/ReplicatorSpec.scala @@ -164,10 +164,10 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec // in case user is not using the passed in existing value replicator ! Update(KeyJ, GSet(), WriteLocal)(_ + "a" + "b") expectMsg(UpdateSuccess(KeyJ, None)) - replicator ! Update(KeyJ, GSet(), WriteLocal)(_ ⇒ GSet.empty[String] + "c") // normal usage would be `_ + "c"` + replicator ! Update(KeyJ, GSet(), WriteLocal)(_ => GSet.empty[String] + "c") // normal usage would be `_ + "c"` expectMsg(UpdateSuccess(KeyJ, None)) replicator ! Get(KeyJ, ReadLocal) - val s = expectMsgPF() { case g @ GetSuccess(KeyJ, _) ⇒ g.get(KeyJ) } + val s = expectMsgPF() { case g @ GetSuccess(KeyJ, _) => g.get(KeyJ) } s should ===(GSet.empty[String] + "a" + "b" + "c") } enterBarrierAfterTestStep() @@ -175,7 +175,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec "reply with ModifyFailure if exception is thrown by modify function" in { val e = new RuntimeException("errr") - replicator ! Update(KeyA, GCounter(), WriteLocal)(_ ⇒ throw e) + replicator ! Update(KeyA, GCounter(), WriteLocal)(_ => throw e) expectMsgType[ModifyFailure[_]].cause should be(e) } @@ -200,11 +200,11 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec within(5.seconds) { awaitAssert { replicator ! Get(KeyA, ReadLocal) - val c = expectMsgPF() { case g @ GetSuccess(KeyA, _) ⇒ g.get(KeyA) } + val c = expectMsgPF() { case g @ GetSuccess(KeyA, _) => g.get(KeyA) } c.value should be(6) } } - val c = changedProbe.expectMsgPF() { case c @ Changed(KeyA) ⇒ c.get(KeyA) } + val c = changedProbe.expectMsgPF() { case c @ Changed(KeyA) => c.get(KeyA) } c.value should be(6) } @@ -225,7 +225,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec // the total, after replication should be 42 awaitAssert { replicator ! Get(KeyB, readTwo) - val c = expectMsgPF() { case g @ GetSuccess(KeyB, _) ⇒ g.get(KeyB) } + val c = expectMsgPF() { case g @ GetSuccess(KeyB, _) => g.get(KeyB) } c.value should be(42) } } @@ -239,7 +239,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec // the total, after replication should be 44 awaitAssert { replicator ! Get(KeyB, readAll) - val c = expectMsgPF() { case g @ GetSuccess(KeyB, _) ⇒ g.get(KeyB) } + val c = expectMsgPF() { case g @ GetSuccess(KeyB, _) => g.get(KeyB) } c.value should be(44) } } @@ -253,7 +253,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec // the total, after replication should be 46 awaitAssert { replicator ! Get(KeyB, readMajority) - val c = expectMsgPF() { case g @ GetSuccess(KeyB, _) ⇒ g.get(KeyB) } + val c = expectMsgPF() { case g @ GetSuccess(KeyB, _) => g.get(KeyB) } c.value should be(46) } } @@ -270,7 +270,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec runOn(first) { replicator ! Update(KeyC, GCounter(), writeTwo)(_ :+ 30) expectMsg(UpdateSuccess(KeyC, None)) - changedProbe.expectMsgPF() { case c @ Changed(KeyC) ⇒ c.get(KeyC).value } should be(30) + changedProbe.expectMsgPF() { case c @ Changed(KeyC) => c.get(KeyC).value } should be(30) replicator ! Update(KeyY, GCounter(), writeTwo)(_ :+ 30) expectMsg(UpdateSuccess(KeyY, None)) @@ -282,20 +282,20 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec runOn(second) { replicator ! Get(KeyC, ReadLocal) - val c30 = expectMsgPF() { case g @ GetSuccess(KeyC, _) ⇒ g.get(KeyC) } + val c30 = expectMsgPF() { case g @ GetSuccess(KeyC, _) => g.get(KeyC) } c30.value should be(30) - changedProbe.expectMsgPF() { case c @ Changed(KeyC) ⇒ c.get(KeyC).value } should be(30) + changedProbe.expectMsgPF() { case c @ Changed(KeyC) => c.get(KeyC).value } should be(30) // replicate with gossip after WriteLocal replicator ! Update(KeyC, GCounter(), WriteLocal)(_ :+ 1) expectMsg(UpdateSuccess(KeyC, None)) - changedProbe.expectMsgPF() { case c @ Changed(KeyC) ⇒ c.get(KeyC).value } should be(31) + changedProbe.expectMsgPF() { case c @ Changed(KeyC) => c.get(KeyC).value } should be(31) replicator ! Delete(KeyY, WriteLocal, Some(777)) expectMsg(DeleteSuccess(KeyY, Some(777))) replicator ! Get(KeyZ, readMajority) - expectMsgPF() { case g @ GetSuccess(KeyZ, _) ⇒ g.get(KeyZ).value } should be(30) + expectMsgPF() { case g @ GetSuccess(KeyZ, _) => g.get(KeyZ).value } should be(30) } enterBarrier("update-c31") @@ -304,21 +304,21 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec within(5.seconds) { awaitAssert { replicator ! Get(KeyC, ReadLocal) - val c = expectMsgPF() { case g @ GetSuccess(KeyC, _) ⇒ g.get(KeyC) } + val c = expectMsgPF() { case g @ GetSuccess(KeyC, _) => g.get(KeyC) } c.value should be(31) replicator ! Get(KeyY, ReadLocal, Some(777)) expectMsg(DataDeleted(KeyY, Some(777))) } } - changedProbe.expectMsgPF() { case c @ Changed(KeyC) ⇒ c.get(KeyC).value } should be(31) + changedProbe.expectMsgPF() { case c @ Changed(KeyC) => c.get(KeyC).value } should be(31) } enterBarrier("verified-c31") // and also for concurrent updates runOn(first, second) { replicator ! Get(KeyC, ReadLocal) - val c31 = expectMsgPF() { case g @ GetSuccess(KeyC, _) ⇒ g.get(KeyC) } + val c31 = expectMsgPF() { case g @ GetSuccess(KeyC, _) => g.get(KeyC) } c31.value should be(31) replicator ! Update(KeyC, GCounter(), WriteLocal)(_ :+ 1) @@ -327,7 +327,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec within(5.seconds) { awaitAssert { replicator ! Get(KeyC, ReadLocal) - val c = expectMsgPF() { case g @ GetSuccess(KeyC, _) ⇒ g.get(KeyC) } + val c = expectMsgPF() { case g @ GetSuccess(KeyC, _) => g.get(KeyC) } c.value should be(33) } } @@ -347,7 +347,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec runOn(first, second) { replicator ! Get(KeyD, ReadLocal) - val c40 = expectMsgPF() { case g @ GetSuccess(KeyD, _) ⇒ g.get(KeyD) } + val c40 = expectMsgPF() { case g @ GetSuccess(KeyD, _) => g.get(KeyD) } c40.value should be(40) replicator ! Update(KeyD, GCounter() :+ 1, writeTwo)(_ :+ 1) expectMsg(timeout + 1.second, UpdateTimeout(KeyD, None)) @@ -355,7 +355,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec expectMsg(timeout + 1.second, UpdateTimeout(KeyD, None)) } runOn(first) { - for (n ← 1 to 30) { + for (n <- 1 to 30) { val KeyDn = GCounterKey("D" + n) replicator ! Update(KeyDn, GCounter(), WriteLocal)(_ :+ n) expectMsg(UpdateSuccess(KeyDn, None)) @@ -370,15 +370,15 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec runOn(first, second) { replicator ! Get(KeyD, readTwo) - val c44 = expectMsgPF() { case g @ GetSuccess(KeyD, _) ⇒ g.get(KeyD) } + val c44 = expectMsgPF() { case g @ GetSuccess(KeyD, _) => g.get(KeyD) } c44.value should be(44) within(10.seconds) { awaitAssert { - for (n ← 1 to 30) { + for (n <- 1 to 30) { val KeyDn = GCounterKey("D" + n) replicator ! Get(KeyDn, ReadLocal) - expectMsgPF() { case g @ GetSuccess(KeyDn, _) ⇒ g.get(KeyDn) }.value should be(n) + expectMsgPF() { case g @ GetSuccess(KeyDn, _) => g.get(KeyDn) }.value should be(n) } } } @@ -408,7 +408,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec runOn(first, second, third) { replicator ! Get(KeyE, readMajority) - val c150 = expectMsgPF() { case g @ GetSuccess(KeyE, _) ⇒ g.get(KeyE) } + val c150 = expectMsgPF() { case g @ GetSuccess(KeyE, _) => g.get(KeyE) } c150.value should be(150) } enterBarrier("read-initial-majority") @@ -431,7 +431,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec val probe2 = TestProbe() replicator.tell(Get(KeyE, readMajority), probe2.ref) probe2.expectMsgType[GetSuccess[_]] - replicator.tell(Update(KeyE, GCounter(), writeMajority, None) { data ⇒ + replicator.tell(Update(KeyE, GCounter(), writeMajority, None) { data => probe1.ref ! data.value data :+ 1 }, probe2.ref) @@ -441,7 +441,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec replicator.tell(Get(KeyE, readMajority), probe3.ref) probe1.expectMsg(151) probe2.expectMsg(UpdateSuccess(KeyE, None)) - val c152 = probe3.expectMsgPF() { case g @ GetSuccess(KeyE, _) ⇒ g.get(KeyE) } + val c152 = probe3.expectMsgPF() { case g @ GetSuccess(KeyE, _) => g.get(KeyE) } c152.value should be(152) } enterBarrier("majority-update-from-first") @@ -462,7 +462,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec probe1.expectMsg(UpdateSuccess(KeyE, Some(153))) probe2.expectMsg(UpdateSuccess(KeyE, Some(154))) probe3.expectMsg(UpdateSuccess(KeyE, Some(155))) - val c155 = probe5.expectMsgPF() { case g @ GetSuccess(KeyE, _) ⇒ g.get(KeyE) } + val c155 = probe5.expectMsgPF() { case g @ GetSuccess(KeyE, _) => g.get(KeyE) } c155.value should be(155) } enterBarrier("majority-update-from-second") @@ -483,7 +483,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec runOn(third) { replicator ! Get(KeyE, readMajority) - val c155 = expectMsgPF() { case g @ GetSuccess(KeyE, _) ⇒ g.get(KeyE) } + val c155 = expectMsgPF() { case g @ GetSuccess(KeyE, _) => g.get(KeyE) } c155.value should be(155) } @@ -493,7 +493,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec "converge after many concurrent updates" in within(10.seconds) { runOn(first, second, third) { var c = GCounter() - for (_ ← 0 until 100) { + for (_ <- 0 until 100) { c :+= 1 replicator ! Update(KeyF, GCounter(), writeTwo)(_ :+ 1) } @@ -503,7 +503,7 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec enterBarrier("100-updates-done") runOn(first, second, third) { replicator ! Get(KeyF, readTwo) - val c = expectMsgPF() { case g @ GetSuccess(KeyF, _) ⇒ g.get(KeyF) } + val c = expectMsgPF() { case g @ GetSuccess(KeyF, _) => g.get(KeyF) } c.value should be(3 * 100) } enterBarrierAfterTestStep() @@ -517,9 +517,9 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec enterBarrier("a-b-added-to-G") runOn(second) { replicator ! Get(KeyG, readAll) - expectMsgPF() { case g @ GetSuccess(KeyG, _) ⇒ g.get(KeyG).elements } should be(Set("a", "b")) + expectMsgPF() { case g @ GetSuccess(KeyG, _) => g.get(KeyG).elements } should be(Set("a", "b")) replicator ! Get(KeyG, ReadLocal) - expectMsgPF() { case g @ GetSuccess(KeyG, _) ⇒ g.get(KeyG).elements } should be(Set("a", "b")) + expectMsgPF() { case g @ GetSuccess(KeyG, _) => g.get(KeyG).elements } should be(Set("a", "b")) } enterBarrierAfterTestStep() } @@ -529,22 +529,22 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec runOn(second) { replicator ! Subscribe(KeyH, changedProbe.ref) - replicator ! Update(KeyH, ORMap.empty[String, Flag], writeTwo)(_ :+ ("a" → Flag.Disabled)) - changedProbe.expectMsgPF() { case c @ Changed(KeyH) ⇒ c.get(KeyH).entries } should be(Map("a" → Flag.Disabled)) + replicator ! Update(KeyH, ORMap.empty[String, Flag], writeTwo)(_ :+ ("a" -> Flag.Disabled)) + changedProbe.expectMsgPF() { case c @ Changed(KeyH) => c.get(KeyH).entries } should be(Map("a" -> Flag.Disabled)) } enterBarrier("update-h1") runOn(first) { - replicator ! Update(KeyH, ORMap.empty[String, Flag], writeTwo)(_ :+ ("a" → Flag.Enabled)) + replicator ! Update(KeyH, ORMap.empty[String, Flag], writeTwo)(_ :+ ("a" -> Flag.Enabled)) } runOn(second) { - changedProbe.expectMsgPF() { case c @ Changed(KeyH) ⇒ c.get(KeyH).entries } should be(Map("a" → Flag.Enabled)) + changedProbe.expectMsgPF() { case c @ Changed(KeyH) => c.get(KeyH).entries } should be(Map("a" -> Flag.Enabled)) - replicator ! Update(KeyH, ORMap.empty[String, Flag], writeTwo)(_ :+ ("b" → Flag.Enabled)) - changedProbe.expectMsgPF() { case c @ Changed(KeyH) ⇒ c.get(KeyH).entries } should be( - Map("a" → Flag.Enabled, "b" → Flag.Enabled)) + replicator ! Update(KeyH, ORMap.empty[String, Flag], writeTwo)(_ :+ ("b" -> Flag.Enabled)) + changedProbe.expectMsgPF() { case c @ Changed(KeyH) => c.get(KeyH).entries } should be( + Map("a" -> Flag.Enabled, "b" -> Flag.Enabled)) } enterBarrierAfterTestStep() @@ -556,11 +556,11 @@ class ReplicatorSpec extends MultiNodeSpec(ReplicatorSpec) with STMultiNodeSpec enterBarrier("subscribed-I") runOn(second) { - replicator ! Update(KeyI, GSet.empty[String], writeTwo)(a ⇒ a.add("a")) + replicator ! Update(KeyI, GSet.empty[String], writeTwo)(a => a.add("a")) } within(5.seconds) { // gossip to third - changedProbe.expectMsgPF() { case c @ Changed(KeyI) ⇒ c.get(KeyI).elements } should be(Set("a")) + changedProbe.expectMsgPF() { case c @ Changed(KeyI) => c.get(KeyI).elements } should be(Set("a")) } enterBarrier("update-I") diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/DeltaPropagationSelectorSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/DeltaPropagationSelectorSpec.scala index afeac957ae..9940857a43 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/DeltaPropagationSelectorSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/DeltaPropagationSelectorSpec.scala @@ -22,7 +22,7 @@ object DeltaPropagationSelectorSpec { override val gossipIntervalDivisor = 5 override def createDeltaPropagation(deltas: Map[KeyId, (ReplicatedData, Long, Long)]): DeltaPropagation = DeltaPropagation(selfUniqueAddress, false, deltas.map { - case (key, (d, fromSeqNr, toSeqNr)) ⇒ (key, Delta(DataEnvelope(d), fromSeqNr, toSeqNr)) + case (key, (d, fromSeqNr, toSeqNr)) => (key, Delta(DataEnvelope(d), fromSeqNr, toSeqNr)) }) override def maxDeltaSize: Int = 10 } @@ -35,7 +35,7 @@ object DeltaPropagationSelectorSpec { class DeltaPropagationSelectorSpec extends WordSpec with Matchers with TypeCheckedTripleEquals { import DeltaPropagationSelectorSpec._ val selfUniqueAddress = UniqueAddress(Address("akka", "Sys", "localhost", 4999), 1L) - val nodes = (2500 until 2600).map(n ⇒ Address("akka", "Sys", "localhost", n)).toVector + val nodes = (2500 until 2600).map(n => Address("akka", "Sys", "localhost", n)).toVector "DeltaPropagationSelector" must { "collect none when no nodes" in { @@ -54,9 +54,9 @@ class DeltaPropagationSelectorSpec extends WordSpec with Matchers with TypeCheck selector.hasDeltaEntries("A") should ===(true) selector.hasDeltaEntries("B") should ===(true) val expected = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(deltaA), 1L, 1L), - "B" → Delta(DataEnvelope(deltaB), 1L, 1L))) - selector.collectPropagations() should ===(Map(nodes(0) → expected)) + "A" -> Delta(DataEnvelope(deltaA), 1L, 1L), + "B" -> Delta(DataEnvelope(deltaB), 1L, 1L))) + selector.collectPropagations() should ===(Map(nodes(0) -> expected)) selector.collectPropagations() should ===(Map.empty[Address, DeltaPropagation]) selector.cleanupDeltaEntries() selector.hasDeltaEntries("A") should ===(false) @@ -68,13 +68,13 @@ class DeltaPropagationSelectorSpec extends WordSpec with Matchers with TypeCheck selector.update("A", deltaA) selector.update("B", deltaB) val expected = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(deltaA), 1L, 1L), - "B" → Delta(DataEnvelope(deltaB), 1L, 1L))) - selector.collectPropagations() should ===(Map(nodes(0) → expected, nodes(1) → expected)) + "A" -> Delta(DataEnvelope(deltaA), 1L, 1L), + "B" -> Delta(DataEnvelope(deltaB), 1L, 1L))) + selector.collectPropagations() should ===(Map(nodes(0) -> expected, nodes(1) -> expected)) selector.cleanupDeltaEntries() selector.hasDeltaEntries("A") should ===(true) selector.hasDeltaEntries("B") should ===(true) - selector.collectPropagations() should ===(Map(nodes(2) → expected)) + selector.collectPropagations() should ===(Map(nodes(2) -> expected)) selector.collectPropagations() should ===(Map.empty[Address, DeltaPropagation]) selector.cleanupDeltaEntries() selector.hasDeltaEntries("A") should ===(false) @@ -86,23 +86,23 @@ class DeltaPropagationSelectorSpec extends WordSpec with Matchers with TypeCheck selector.update("A", deltaA) selector.update("B", deltaB) val expected1 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(deltaA), 1L, 1L), - "B" → Delta(DataEnvelope(deltaB), 1L, 1L))) - selector.collectPropagations() should ===(Map(nodes(0) → expected1, nodes(1) → expected1)) + "A" -> Delta(DataEnvelope(deltaA), 1L, 1L), + "B" -> Delta(DataEnvelope(deltaB), 1L, 1L))) + selector.collectPropagations() should ===(Map(nodes(0) -> expected1, nodes(1) -> expected1)) // new update before previous was propagated to all nodes selector.update("C", deltaC) val expected2 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(deltaA), 1L, 1L), - "B" → Delta(DataEnvelope(deltaB), 1L, 1L), - "C" → Delta(DataEnvelope(deltaC), 1L, 1L))) + "A" -> Delta(DataEnvelope(deltaA), 1L, 1L), + "B" -> Delta(DataEnvelope(deltaB), 1L, 1L), + "C" -> Delta(DataEnvelope(deltaC), 1L, 1L))) val expected3 = DeltaPropagation(selfUniqueAddress, false, Map( - "C" → Delta(DataEnvelope(deltaC), 1L, 1L))) - selector.collectPropagations() should ===(Map(nodes(2) → expected2, nodes(0) → expected3)) + "C" -> Delta(DataEnvelope(deltaC), 1L, 1L))) + selector.collectPropagations() should ===(Map(nodes(2) -> expected2, nodes(0) -> expected3)) selector.cleanupDeltaEntries() selector.hasDeltaEntries("A") should ===(false) selector.hasDeltaEntries("B") should ===(false) selector.hasDeltaEntries("C") should ===(true) - selector.collectPropagations() should ===(Map(nodes(1) → expected3)) + selector.collectPropagations() should ===(Map(nodes(1) -> expected3)) selector.collectPropagations() should ===(Map.empty[Address, DeltaPropagation]) selector.cleanupDeltaEntries() selector.hasDeltaEntries("C") should ===(false) @@ -118,13 +118,13 @@ class DeltaPropagationSelectorSpec extends WordSpec with Matchers with TypeCheck selector.update("A", delta2) selector.currentVersion("A") should ===(2L) val expected1 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(delta1.merge(delta2)), 1L, 2L))) - selector.collectPropagations() should ===(Map(nodes(0) → expected1)) + "A" -> Delta(DataEnvelope(delta1.merge(delta2)), 1L, 2L))) + selector.collectPropagations() should ===(Map(nodes(0) -> expected1)) selector.update("A", delta3) selector.currentVersion("A") should ===(3L) val expected2 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(delta3), 3L, 3L))) - selector.collectPropagations() should ===(Map(nodes(0) → expected2)) + "A" -> Delta(DataEnvelope(delta3), 3L, 3L))) + selector.collectPropagations() should ===(Map(nodes(0) -> expected2)) selector.collectPropagations() should ===(Map.empty[Address, DeltaPropagation]) } @@ -137,26 +137,26 @@ class DeltaPropagationSelectorSpec extends WordSpec with Matchers with TypeCheck } selector.update("A", delta1) val expected1 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(delta1), 1L, 1L))) - selector.collectPropagations() should ===(Map(nodes(0) → expected1)) + "A" -> Delta(DataEnvelope(delta1), 1L, 1L))) + selector.collectPropagations() should ===(Map(nodes(0) -> expected1)) selector.update("A", delta2) val expected2 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(delta1.merge(delta2)), 1L, 2L))) - selector.collectPropagations() should ===(Map(nodes(1) → expected2)) + "A" -> Delta(DataEnvelope(delta1.merge(delta2)), 1L, 2L))) + selector.collectPropagations() should ===(Map(nodes(1) -> expected2)) selector.update("A", delta3) val expected3 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(delta1.merge(delta2).merge(delta3)), 1L, 3L))) - selector.collectPropagations() should ===(Map(nodes(2) → expected3)) + "A" -> Delta(DataEnvelope(delta1.merge(delta2).merge(delta3)), 1L, 3L))) + selector.collectPropagations() should ===(Map(nodes(2) -> expected3)) val expected4 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(delta2.merge(delta3)), 2L, 3L))) - selector.collectPropagations() should ===(Map(nodes(0) → expected4)) + "A" -> Delta(DataEnvelope(delta2.merge(delta3)), 2L, 3L))) + selector.collectPropagations() should ===(Map(nodes(0) -> expected4)) val expected5 = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(delta3), 3L, 3L))) - selector.collectPropagations() should ===(Map(nodes(1) → expected5)) + "A" -> Delta(DataEnvelope(delta3), 3L, 3L))) + selector.collectPropagations() should ===(Map(nodes(1) -> expected5)) selector.collectPropagations() should ===(Map.empty[Address, DeltaPropagation]) } @@ -166,61 +166,61 @@ class DeltaPropagationSelectorSpec extends WordSpec with Matchers with TypeCheck override def nodesSliceSize(allNodesSize: Int): Int = 1 } var data = PNCounterMap.empty[String] - (1 to 1000).foreach { n ⇒ + (1 to 1000).foreach { n => val d = data.resetDelta.increment(selfUniqueAddress, (n % 2).toString, 1) selector.update("A", d.delta.get) data = d } val expected = DeltaPropagation(selfUniqueAddress, false, Map( - "A" → Delta(DataEnvelope(NoDeltaPlaceholder), 1L, 1000L))) - selector.collectPropagations() should ===(Map(nodes(0) → expected)) + "A" -> Delta(DataEnvelope(NoDeltaPlaceholder), 1L, 1000L))) + selector.collectPropagations() should ===(Map(nodes(0) -> expected)) } "calculate right slice size" in { val selector = new TestSelector(selfUniqueAddress, nodes) selector.nodesSliceSize(0) should ===(0) selector.nodesSliceSize(1) should ===(1) - (2 to 9).foreach { n ⇒ + (2 to 9).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(2) } } - (10 to 14).foreach { n ⇒ + (10 to 14).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(3) } } - (15 to 19).foreach { n ⇒ + (15 to 19).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(4) } } - (20 to 24).foreach { n ⇒ + (20 to 24).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(5) } } - (25 to 29).foreach { n ⇒ + (25 to 29).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(6) } } - (30 to 34).foreach { n ⇒ + (30 to 34).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(7) } } - (35 to 39).foreach { n ⇒ + (35 to 39).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(8) } } - (40 to 44).foreach { n ⇒ + (40 to 44).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(9) } } - (45 to 200).foreach { n ⇒ + (45 to 200).foreach { n => withClue(s"n=$n") { selector.nodesSliceSize(n) should ===(10) } diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/FlagSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/FlagSpec.scala index df0c4daf35..c9b9d23952 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/FlagSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/FlagSpec.scala @@ -35,7 +35,7 @@ class FlagSpec extends WordSpec with Matchers { val Flag(value1) = f1 val value2: Boolean = value1 Changed(FlagKey("key"))(f1) match { - case c @ Changed(FlagKey("key")) ⇒ + case c @ Changed(FlagKey("key")) => val Flag(value3) = c.dataValue val value4: Boolean = value3 value4 should be(true) diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/GCounterSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/GCounterSpec.scala index 6e341f2c04..ade71647cc 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/GCounterSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/GCounterSpec.scala @@ -173,7 +173,7 @@ class GCounterSpec extends WordSpec with Matchers { val GCounter(value1) = c1 val value2: BigInt = value1 Changed(GCounterKey("key"))(c1) match { - case c @ Changed(GCounterKey("key")) ⇒ + case c @ Changed(GCounterKey("key")) => val GCounter(value3) = c.dataValue val value4: BigInt = value3 value4 should be(2L) diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/GSetSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/GSetSpec.scala index 5893790a05..3315701cc9 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/GSetSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/GSetSpec.scala @@ -140,7 +140,7 @@ class GSetSpec extends WordSpec with Matchers { val GSet(elements1) = s1 val elements2: Set[String] = elements1 Changed(GSetKey[String]("key"))(s1) match { - case c @ Changed(GSetKey("key")) ⇒ + case c @ Changed(GSetKey("key")) => val GSet(elements3) = c.dataValue val elements4: Set[String] = elements3 elements4 should be(Set("a", "b")) diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/LWWMapSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/LWWMapSpec.scala index 97953749d8..388a68dbe8 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/LWWMapSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/LWWMapSpec.scala @@ -20,7 +20,7 @@ class LWWMapSpec extends WordSpec with Matchers { "be able to set entries" in { val m = LWWMap.empty[String, Int].put(node1, "a", 1, defaultClock[Int]).put(node2, "b", 2, defaultClock[Int]) - m.entries should be(Map("a" → 1, "b" → 2)) + m.entries should be(Map("a" -> 1, "b" -> 2)) } "be able to have its entries correctly merged with another LWWMap with other entries" in { @@ -28,7 +28,7 @@ class LWWMapSpec extends WordSpec with Matchers { val m2 = LWWMap.empty[String, Int].put(node2, "c", 3, defaultClock[Int]) // merge both ways - val expected = Map("a" → 1, "b" → 2, "c" → 3) + val expected = Map("a" -> 1, "b" -> 2, "c" -> 3) (m1 merge m2).entries should be(expected) (m2 merge m1).entries should be(expected) } @@ -40,18 +40,18 @@ class LWWMapSpec extends WordSpec with Matchers { val merged1 = m1 merge m2 val m3 = merged1.remove(node1, "b") - (merged1 merge m3).entries should be(Map("a" → 1, "c" → 3)) + (merged1 merge m3).entries should be(Map("a" -> 1, "c" -> 3)) // but if there is a conflicting update the entry is not removed val m4 = merged1.put(node2, "b", 22, defaultClock[Int]) - (m3 merge m4).entries should be(Map("a" → 1, "b" → 22, "c" → 3)) + (m3 merge m4).entries should be(Map("a" -> 1, "b" -> 22, "c" -> 3)) } "be able to work with deltas" in { val m1 = LWWMap.empty[String, Int].put(node1, "a", 1, defaultClock[Int]).put(node1, "b", 2, defaultClock[Int]) val m2 = LWWMap.empty[String, Int].put(node2, "c", 3, defaultClock[Int]) - val expected = Map("a" → 1, "b" → 2, "c" → 3) + val expected = Map("a" -> 1, "b" -> 2, "c" -> 3) (m1 merge m2).entries should be(expected) (m2 merge m1).entries should be(expected) @@ -61,11 +61,11 @@ class LWWMapSpec extends WordSpec with Matchers { val merged1 = m1 merge m2 val m3 = merged1.resetDelta.remove(node1, "b") - (merged1 mergeDelta m3.delta.get).entries should be(Map("a" → 1, "c" → 3)) + (merged1 mergeDelta m3.delta.get).entries should be(Map("a" -> 1, "c" -> 3)) // but if there is a conflicting update the entry is not removed val m4 = merged1.resetDelta.put(node2, "b", 22, defaultClock[Int]) - (m3 mergeDelta m4.delta.get).entries should be(Map("a" → 1, "b" → 22, "c" → 3)) + (m3 mergeDelta m4.delta.get).entries should be(Map("a" -> 1, "b" -> 22, "c" -> 3)) } "have unapply extractor" in { @@ -73,10 +73,10 @@ class LWWMapSpec extends WordSpec with Matchers { val LWWMap(entries1) = m1 val entries2: Map[String, Long] = entries1 Changed(LWWMapKey[String, Long]("key"))(m1) match { - case c @ Changed(LWWMapKey("key")) ⇒ + case c @ Changed(LWWMapKey("key")) => val LWWMap(entries3) = c.dataValue val entries4: Map[String, Long] = entries3 - entries4 should be(Map("a" → 1L)) + entries4 should be(Map("a" -> 1L)) } } diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/LWWRegisterSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/LWWRegisterSpec.scala index b9e9f77d3f..d29bbdc32e 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/LWWRegisterSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/LWWRegisterSpec.scala @@ -19,7 +19,7 @@ class LWWRegisterSpec extends WordSpec with Matchers { "A LWWRegister" must { "use latest of successive assignments" in { val r = (1 to 100).foldLeft(LWWRegister(node1, 0, defaultClock[Int])) { - case (r, n) ⇒ + case (r, n) => r.value should be(n - 1) r.withValue(node1, n, defaultClock[Int]) } @@ -59,7 +59,7 @@ class LWWRegisterSpec extends WordSpec with Matchers { implicit val node = SelfUniqueAddress(node1) (1 to 100).foldLeft(LWWRegister.create(0)) { - case (r, n) ⇒ + case (r, n) => r.value should be(n - 1) val r2 = r.withValueOf(n) r2.timestamp should be > r.timestamp @@ -72,7 +72,7 @@ class LWWRegisterSpec extends WordSpec with Matchers { val LWWRegister(value1) = r1 val value2: String = value1 Changed(LWWRegisterKey[String]("key"))(r1) match { - case c @ Changed(LWWRegisterKey("key")) ⇒ + case c @ Changed(LWWRegisterKey("key")) => val LWWRegister(value3) = c.dataValue val value4: String = value3 value4 should be("a") @@ -82,7 +82,7 @@ class LWWRegisterSpec extends WordSpec with Matchers { "can be used as first-write-wins-register" in { import LWWRegister.reverseClock val r = (1 to 100).foldLeft(LWWRegister(node1, 0, reverseClock[Int])) { - case (r, n) ⇒ + case (r, n) => r.value should be(0) val newRegister = r.merge(r.withValue(node1, n, reverseClock[Int])) newRegister should be(r) diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/LocalConcurrencySpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/LocalConcurrencySpec.scala index 366522fadc..e1380c0d28 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/LocalConcurrencySpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/LocalConcurrencySpec.scala @@ -30,7 +30,7 @@ object LocalConcurrencySpec { val replicator = DistributedData(context.system).replicator def receive = { - case s: String ⇒ + case s: String => val update = Replicator.Update(Updater.key, ORSet.empty[String], Replicator.WriteLocal)(_ :+ s) replicator ! update } @@ -64,7 +64,7 @@ class LocalConcurrencySpec(_system: ActorSystem) extends TestKit(_system) val updater2 = system.actorOf(Props[Updater], "updater2") val numMessages = 100 - for (n ← 1 to numMessages) { + for (n <- 1 to numMessages) { updater1 ! s"a$n" updater2 ! s"b$n" } diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/LotsOfDataBot.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/LotsOfDataBot.scala index 5e173b5525..04382fbcba 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/LotsOfDataBot.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/LotsOfDataBot.scala @@ -28,7 +28,7 @@ object LotsOfDataBot { } def startup(ports: Seq[String]): Unit = { - ports.foreach { port ⇒ + ports.foreach { port => // Override the configuration of the port val config = ConfigFactory.parseString("akka.remote.netty.tcp.port=" + port). withFallback(ConfigFactory.load( @@ -87,9 +87,9 @@ class LotsOfDataBot extends Actor with ActorLogging { def receive = if (isPassive) passive else active def active: Receive = { - case Tick ⇒ + case Tick => val loop = if (count >= maxEntries) 1 else 100 - for (_ ← 1 to loop) { + for (_ <- 1 to loop) { count += 1 if (count % 10000 == 0) log.info("Reached {} entries", count) @@ -111,24 +111,24 @@ class LotsOfDataBot extends Actor with ActorLogging { } } - case _: UpdateResponse[_] ⇒ // ignore + case _: UpdateResponse[_] => // ignore - case c @ Changed(ORSetKey(id)) ⇒ + case c @ Changed(ORSetKey(id)) => val ORSet(elements) = c.dataValue log.info("Current elements: {} -> {}", id, elements) } def passive: Receive = { - case Tick ⇒ + case Tick => if (!tickTask.isCancelled) replicator ! GetKeyIds - case GetKeyIdsResult(keys) ⇒ + case GetKeyIdsResult(keys) => if (keys.size >= maxEntries) { tickTask.cancel() val duration = (System.nanoTime() - startTime).nanos.toMillis log.info("It took {} ms to replicate {} entries", duration, keys.size) } - case c @ Changed(ORSetKey(id)) ⇒ + case c @ Changed(ORSetKey(id)) => val ORSet(elements) = c.dataValue log.info("Current elements: {} -> {}", id, elements) } diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORMapSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORMapSpec.scala index 0a94283d81..7e5d56b870 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORMapSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORMapSpec.scala @@ -146,16 +146,16 @@ class ORMapSpec extends WordSpec with Matchers { val m1 = ORMap.empty.put(node1, "a", GSet.empty + "A") val deltaVersion = m1.delta.get match { - case ORMap.PutDeltaOp(delta, v, dt) ⇒ + case ORMap.PutDeltaOp(delta, v, dt) => delta match { - case AddDeltaOp(u) ⇒ + case AddDeltaOp(u) => if (u.elementsMap.contains("a")) Some(u.elementsMap("a").versionAt(node1)) else None - case _ ⇒ None + case _ => None } - case _ ⇒ None + case _ => None } val fullVersion = @@ -659,10 +659,10 @@ class ORMapSpec extends WordSpec with Matchers { val ORMap(entries1) = m1 val entries2: Map[String, Flag] = entries1 Changed(ORMapKey[String, Flag]("key"))(m1) match { - case c @ Changed(ORMapKey("key")) ⇒ + case c @ Changed(ORMapKey("key")) => val ORMap(entries3) = c.dataValue val entries4: Map[String, ReplicatedData] = entries3 - entries4 should be(Map("a" → Flag(true), "b" → Flag(false))) + entries4 should be(Map("a" -> Flag(true), "b" -> Flag(false))) } } diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORMultiMapSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORMultiMapSpec.scala index 314e8ebc9e..66e326d20a 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORMultiMapSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORMultiMapSpec.scala @@ -18,20 +18,20 @@ class ORMultiMapSpec extends WordSpec with Matchers { "be able to add entries" in { val m = ORMultiMap().addBinding(node1, "a", "A").addBinding(node1, "b", "B") - m.entries should be(Map("a" → Set("A"), "b" → Set("B"))) + m.entries should be(Map("a" -> Set("A"), "b" -> Set("B"))) val m2 = m.addBinding(node1, "a", "C") - m2.entries should be(Map("a" → Set("A", "C"), "b" → Set("B"))) + m2.entries should be(Map("a" -> Set("A", "C"), "b" -> Set("B"))) } "be able to remove entry" in { val m = ORMultiMap().addBinding(node1, "a", "A").addBinding(node1, "b", "B").removeBinding(node1, "a", "A") - m.entries should be(Map("b" → Set("B"))) + m.entries should be(Map("b" -> Set("B"))) } "be able to replace an entry" in { val m = ORMultiMap().addBinding(node1, "a", "A").replaceBinding(node1, "a", "A", "B") - m.entries should be(Map("a" → Set("B"))) + m.entries should be(Map("a" -> Set("B"))) } "not handle concurrent updates to the same set" in { @@ -61,9 +61,9 @@ class ORMultiMapSpec extends WordSpec with Matchers { // merge both ways val expectedMerge = Map( - "a" → Set("A"), - "b" → Set("B"), - "c" → Set("C")) + "a" -> Set("A"), + "b" -> Set("B"), + "c" -> Set("C")) val merged1 = m1 merge m2 merged1.entries should be(expectedMerge) @@ -88,10 +88,10 @@ class ORMultiMapSpec extends WordSpec with Matchers { // merge both ways val expectedMerged = Map( - "a" → Set("A2"), - "b" → Set("B1"), - "c" → Set("C2"), - "d" → Set("D1", "D2")) + "a" -> Set("A2"), + "b" -> Set("B1"), + "c" -> Set("C2"), + "d" -> Set("D1", "D2")) val merged1 = m1 merge m2 merged1.entries should be(expectedMerged) @@ -117,7 +117,7 @@ class ORMultiMapSpec extends WordSpec with Matchers { // merge both ways val expectedMerged = Map( - "b" → Set("B1")) + "b" -> Set("B1")) val merged1 = m1 merge m2 merged1.entries should be(expectedMerged) @@ -157,8 +157,8 @@ class ORMultiMapSpec extends WordSpec with Matchers { val m2 = m.put(node1, "a", a - "A1") val expectedMerged = Map( - "a" → Set("A2"), - "b" → Set("B1")) + "a" -> Set("A2"), + "b" -> Set("B1")) m2.entries should be(expectedMerged) } @@ -172,7 +172,7 @@ class ORMultiMapSpec extends WordSpec with Matchers { "remove all bindings for a given key" in { val m = ORMultiMap().addBinding(node1, "a", "A1").addBinding(node1, "a", "A2").addBinding(node1, "b", "B1") val m2 = m.remove(node1, "a") - m2.entries should be(Map("b" → Set("B1"))) + m2.entries should be(Map("b" -> Set("B1"))) } "not have usual anomalies for remove+addBinding scenario and delta-deltas" in { @@ -550,10 +550,10 @@ class ORMultiMapSpec extends WordSpec with Matchers { val ORMultiMap(entries1) = m1 val entries2: Map[String, Set[Long]] = entries1 Changed(ORMultiMapKey[String, Long]("key"))(m1) match { - case c @ Changed(ORMultiMapKey("key")) ⇒ + case c @ Changed(ORMultiMapKey("key")) => val ORMultiMap(entries3) = c.dataValue val entries4: Map[String, Set[Long]] = entries3 - entries4 should be(Map("a" → Set(1L, 2L), "b" → Set(3L))) + entries4 should be(Map("a" -> Set(1L, 2L), "b" -> Set(3L))) } } } diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORSetSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORSetSpec.scala index e5829f77d7..72b110ab7c 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORSetSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/ORSetSpec.scala @@ -234,8 +234,8 @@ class ORSetSpec extends WordSpec with Matchers { def asAddDeltaOp(delta: Any): ORSet.AddDeltaOp[String] = delta match { - case d: ORSet.AddDeltaOp[String] @unchecked ⇒ d - case _ ⇒ throw new IllegalArgumentException("Expected AddDeltaOp") + case d: ORSet.AddDeltaOp[String] @unchecked => d + case _ => throw new IllegalArgumentException("Expected AddDeltaOp") } "work for additions" in { @@ -486,30 +486,30 @@ class ORSetSpec extends WordSpec with Matchers { "ORSet unit test" must { "verify subtractDots" in { - val dot = VersionVector(TreeMap(nodeA → 3L, nodeB → 2L, nodeD → 14L, nodeG → 22L)) - val vvector = VersionVector(TreeMap(nodeA → 4L, nodeB → 1L, nodeC → 1L, nodeD → 14L, nodeE → 5L, nodeF → 2L)) - val expected = VersionVector(TreeMap(nodeB → 2L, nodeG → 22L)) + val dot = VersionVector(TreeMap(nodeA -> 3L, nodeB -> 2L, nodeD -> 14L, nodeG -> 22L)) + val vvector = VersionVector(TreeMap(nodeA -> 4L, nodeB -> 1L, nodeC -> 1L, nodeD -> 14L, nodeE -> 5L, nodeF -> 2L)) + val expected = VersionVector(TreeMap(nodeB -> 2L, nodeG -> 22L)) ORSet.subtractDots(dot, vvector) should be(expected) } "verify mergeCommonKeys" in { val commonKeys: Set[String] = Set("K1", "K2") - val thisDot1 = VersionVector(TreeMap(nodeA → 3L, nodeD → 7L)) - val thisDot2 = VersionVector(TreeMap(nodeB → 5L, nodeC → 2L)) - val thisVvector = VersionVector(TreeMap(nodeA → 3L, nodeB → 5L, nodeC → 2L, nodeD → 7L)) + val thisDot1 = VersionVector(TreeMap(nodeA -> 3L, nodeD -> 7L)) + val thisDot2 = VersionVector(TreeMap(nodeB -> 5L, nodeC -> 2L)) + val thisVvector = VersionVector(TreeMap(nodeA -> 3L, nodeB -> 5L, nodeC -> 2L, nodeD -> 7L)) val thisSet = new ORSet( - elementsMap = Map("K1" → thisDot1, "K2" → thisDot2), + elementsMap = Map("K1" -> thisDot1, "K2" -> thisDot2), vvector = thisVvector) val thatDot1 = VersionVector(nodeA, 3L) val thatDot2 = VersionVector(nodeB, 6L) - val thatVvector = VersionVector(TreeMap(nodeA → 3L, nodeB → 6L, nodeC → 1L, nodeD → 8L)) + val thatVvector = VersionVector(TreeMap(nodeA -> 3L, nodeB -> 6L, nodeC -> 1L, nodeD -> 8L)) val thatSet = new ORSet( - elementsMap = Map("K1" → thatDot1, "K2" → thatDot2), + elementsMap = Map("K1" -> thatDot1, "K2" -> thatDot2), vvector = thatVvector) val expectedDots = Map( - "K1" → VersionVector(nodeA, 3L), - "K2" → VersionVector(TreeMap(nodeB → 6L, nodeC → 2L))) + "K1" -> VersionVector(nodeA, 3L), + "K2" -> VersionVector(TreeMap(nodeB -> 6L, nodeC -> 2L))) ORSet.mergeCommonKeys(commonKeys, thisSet, thatSet) should be(expectedDots) } @@ -517,14 +517,14 @@ class ORSetSpec extends WordSpec with Matchers { "verify mergeDisjointKeys" in { val keys: Set[Any] = Set("K3", "K4", "K5") val elements: Map[Any, VersionVector] = Map( - "K3" → VersionVector(nodeA, 4L), - "K4" → VersionVector(TreeMap(nodeA → 3L, nodeD → 8L)), - "K5" → VersionVector(nodeA, 2L)) - val vvector = VersionVector(TreeMap(nodeA → 3L, nodeD → 7L)) - val acc: Map[Any, VersionVector] = Map("K1" → VersionVector(nodeA, 3L)) + "K3" -> VersionVector(nodeA, 4L), + "K4" -> VersionVector(TreeMap(nodeA -> 3L, nodeD -> 8L)), + "K5" -> VersionVector(nodeA, 2L)) + val vvector = VersionVector(TreeMap(nodeA -> 3L, nodeD -> 7L)) + val acc: Map[Any, VersionVector] = Map("K1" -> VersionVector(nodeA, 3L)) val expectedDots = acc ++ Map( - "K3" → VersionVector(nodeA, 4L), - "K4" → VersionVector(nodeD, 8L)) // "a" -> 3 removed, optimized to include only those unseen + "K3" -> VersionVector(nodeA, 4L), + "K4" -> VersionVector(nodeD, 8L)) // "a" -> 3 removed, optimized to include only those unseen ORSet.mergeDisjointKeys(keys, elements, vvector, acc) should be(expectedDots) } @@ -612,7 +612,7 @@ class ORSetSpec extends WordSpec with Matchers { val elements2: Set[String] = elements1 Changed(ORSetKey[String]("key"))(s1) match { - case c @ Changed(ORSetKey("key")) ⇒ + case c @ Changed(ORSetKey("key")) => val x: ORSet[String] = c.dataValue val ORSet(elements3) = c.dataValue val elements4: Set[String] = elements3 @@ -621,7 +621,7 @@ class ORSetSpec extends WordSpec with Matchers { val msg: Any = Changed(ORSetKey[String]("key"))(s1) msg match { - case c @ Changed(ORSetKey("key")) ⇒ + case c @ Changed(ORSetKey("key")) => val ORSet(elements3) = c.dataValue // `unapply(a: ReplicatedData)` is used here // if `unapply(a: ReplicatedData)` isn't defined the next line doesn't compile: // type mismatch; found : scala.collection.immutable.Set[A] where type A required: Set[Any] Note: A <: Any, diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/PNCounterMapSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/PNCounterMapSpec.scala index 54137c62c6..74a9735232 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/PNCounterMapSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/PNCounterMapSpec.scala @@ -19,12 +19,12 @@ class PNCounterMapSpec extends WordSpec with Matchers { "be able to increment and decrement entries with implicit SelfUniqueAddress" in { implicit val node = SelfUniqueAddress(node1) - PNCounterMap().incrementBy("a", 2).incrementBy("b", 1).incrementBy("b", 2).decrementBy("a", 1).entries should be(Map("a" → 1, "b" → 3)) + PNCounterMap().incrementBy("a", 2).incrementBy("b", 1).incrementBy("b", 2).decrementBy("a", 1).entries should be(Map("a" -> 1, "b" -> 3)) } "be able to increment and decrement entries" in { val m = PNCounterMap().increment(node1, "a", 2).increment(node1, "b", 3).decrement(node2, "a", 1) - m.entries should be(Map("a" → 1, "b" → 3)) + m.entries should be(Map("a" -> 1, "b" -> 3)) } "be able to have its entries correctly merged with another ORMap with other entries" in { @@ -32,7 +32,7 @@ class PNCounterMapSpec extends WordSpec with Matchers { val m2 = PNCounterMap().increment(node2, "c", 5) // merge both ways - val expected = Map("a" → 1, "b" → 3, "c" → 7) + val expected = Map("a" -> 1, "b" -> 3, "c" -> 7) (m1 merge m2).entries should be(expected) (m2 merge m1).entries should be(expected) } @@ -44,29 +44,29 @@ class PNCounterMapSpec extends WordSpec with Matchers { val merged1 = m1 merge m2 val m3 = merged1.remove(node1, "b") - (merged1 merge m3).entries should be(Map("a" → 1, "c" → 7)) + (merged1 merge m3).entries should be(Map("a" -> 1, "c" -> 7)) // but if there is a conflicting update the entry is not removed val m4 = merged1.increment(node2, "b", 10) - (m3 merge m4).entries should be(Map("a" → 1, "b" → 13, "c" → 7)) + (m3 merge m4).entries should be(Map("a" -> 1, "b" -> 13, "c" -> 7)) } "be able to work with deltas" in { val m1 = PNCounterMap().increment(node1, "a", 1).increment(node1, "b", 3).increment(node1, "c", 2) val m2 = PNCounterMap().increment(node2, "c", 5) - val expected = Map("a" → 1, "b" → 3, "c" → 7) + val expected = Map("a" -> 1, "b" -> 3, "c" -> 7) (PNCounterMap() mergeDelta m1.delta.get mergeDelta m2.delta.get).entries should be(expected) (PNCounterMap() mergeDelta m2.delta.get mergeDelta m1.delta.get).entries should be(expected) val merged1 = m1 merge m2 val m3 = merged1.resetDelta.remove(node1, "b") - (merged1 mergeDelta m3.delta.get).entries should be(Map("a" → 1, "c" → 7)) + (merged1 mergeDelta m3.delta.get).entries should be(Map("a" -> 1, "c" -> 7)) // but if there is a conflicting update the entry is not removed val m4 = merged1.resetDelta.increment(node2, "b", 10) - (m3 mergeDelta m4.delta.get).entries should be(Map("a" → 1, "b" → 13, "c" → 7)) + (m3 mergeDelta m4.delta.get).entries should be(Map("a" -> 1, "b" -> 13, "c" -> 7)) } "have unapply extractor" in { @@ -74,10 +74,10 @@ class PNCounterMapSpec extends WordSpec with Matchers { val PNCounterMap(entries1) = m1 val entries2: Map[String, BigInt] = entries1 Changed(PNCounterMapKey[String]("key"))(m1) match { - case c @ Changed(PNCounterMapKey("key")) ⇒ + case c @ Changed(PNCounterMapKey("key")) => val PNCounterMap(entries3) = c.dataValue val entries4: Map[String, BigInt] = entries3 - entries4 should be(Map("a" → 1L, "b" → 2L)) + entries4 should be(Map("a" -> 1L, "b" -> 2L)) } } diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/PNCounterSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/PNCounterSpec.scala index 69f6dae785..315f172b01 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/PNCounterSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/PNCounterSpec.scala @@ -193,7 +193,7 @@ class PNCounterSpec extends WordSpec with Matchers { val PNCounter(value1) = c1 val value2: BigInt = value1 Changed(PNCounterKey("key"))(c1) match { - case c @ Changed(PNCounterKey("key")) ⇒ + case c @ Changed(PNCounterKey("key")) => val PNCounter(value3) = c.dataValue val value4: BigInt = value3 value4 should be(1L) diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/WriteAggregatorSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/WriteAggregatorSpec.scala index a4b931660f..f2c8e70e1f 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/WriteAggregatorSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/WriteAggregatorSpec.scala @@ -40,7 +40,7 @@ object WriteAggregatorSpec { context.actorSelection(probes(address).path) override def senderAddress(): Address = - probes.find { case (a, r) ⇒ r == sender() }.get._1 + probes.find { case (a, r) => r == sender() }.get._1 } def writeAckAdapterProps(replica: ActorRef): Props = @@ -50,13 +50,13 @@ object WriteAggregatorSpec { var replicator: Option[ActorRef] = None def receive = { - case WriteAck ⇒ + case WriteAck => replicator.foreach(_ ! WriteAck) - case WriteNack ⇒ + case WriteNack => replicator.foreach(_ ! WriteNack) - case DeltaNack ⇒ + case DeltaNack => replicator.foreach(_ ! DeltaNack) - case msg ⇒ + case msg => replicator = Some(sender()) replica ! msg } @@ -100,14 +100,14 @@ class WriteAggregatorSpec extends AkkaSpec(s""" val writeAll = WriteAll(timeout) def probes(probe: ActorRef): Map[Address, ActorRef] = - nodes.toSeq.map(_ → system.actorOf(WriteAggregatorSpec.writeAckAdapterProps(probe))).toMap + nodes.toSeq.map(_ -> system.actorOf(WriteAggregatorSpec.writeAckAdapterProps(probe))).toMap /** * Create a tuple for each node with the WriteAckAdapter and the TestProbe */ def probes(): Map[Address, TestMock] = { val probe = TestProbe() - nodes.toSeq.map(_ → TestMock()).toMap + nodes.toSeq.map(_ -> TestMock()).toMap } "WriteAggregator" must { @@ -127,7 +127,7 @@ class WriteAggregatorSpec extends AkkaSpec(s""" "send to more when no immediate reply" in { val testProbes = probes() - val testProbeRefs = testProbes.map { case (a, tm) ⇒ a → tm.writeAckAdapter } + val testProbeRefs = testProbes.map { case (a, tm) => a -> tm.writeAckAdapter } val aggr = system.actorOf(WriteAggregatorSpec.writeAggregatorProps( data, writeMajority, testProbeRefs, nodes, Set(nodeC, nodeD), testActor, durable = false)) @@ -211,7 +211,7 @@ class WriteAggregatorSpec extends AkkaSpec(s""" "retry with full state when no immediate reply or nack" in { val testProbes = probes() - val testProbeRefs = testProbes.map { case (a, tm) ⇒ a → tm.writeAckAdapter } + val testProbeRefs = testProbes.map { case (a, tm) => a -> tm.writeAckAdapter } val aggr = system.actorOf(WriteAggregatorSpec.writeAggregatorPropsWithDelta( fullState2, delta, writeAll, testProbeRefs, nodes, Set.empty, testActor, durable = false)) diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/protobuf/ReplicatedDataSerializerSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/protobuf/ReplicatedDataSerializerSpec.scala index 3321fdd480..5e66016758 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/protobuf/ReplicatedDataSerializerSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/protobuf/ReplicatedDataSerializerSpec.scala @@ -157,7 +157,7 @@ class ReplicatedDataSerializerSpec extends TestKit(ActorSystem( "serialize large GSet" in { val largeSet = (10000 until 20000).foldLeft(GSet.empty[String]) { - case (acc, n) ⇒ acc.resetDelta.add(n.toString) + case (acc, n) => acc.resetDelta.add(n.toString) } val numberOfBytes = checkSerialization(largeSet) info(s"size of GSet with ${largeSet.size} elements: $numberOfBytes bytes") @@ -166,11 +166,11 @@ class ReplicatedDataSerializerSpec extends TestKit(ActorSystem( "serialize large ORSet" in { val largeSet = (10000 until 20000).foldLeft(ORSet.empty[String]) { - case (acc, n) ⇒ + case (acc, n) => val address = (n % 3) match { - case 0 ⇒ address1 - case 1 ⇒ address2 - case 2 ⇒ address3 + case 0 => address1 + case 1 => address2 + case 2 => address3 } acc.resetDelta.add(address, n.toString) } diff --git a/akka-distributed-data/src/test/scala/akka/cluster/ddata/protobuf/ReplicatorMessageSerializerSpec.scala b/akka-distributed-data/src/test/scala/akka/cluster/ddata/protobuf/ReplicatorMessageSerializerSpec.scala index 476d29baf0..7c58f7bba6 100644 --- a/akka-distributed-data/src/test/scala/akka/cluster/ddata/protobuf/ReplicatorMessageSerializerSpec.scala +++ b/akka-distributed-data/src/test/scala/akka/cluster/ddata/protobuf/ReplicatorMessageSerializerSpec.scala @@ -83,8 +83,8 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( checkSerialization(Changed(keyA)(data1)) checkSerialization(DataEnvelope(data1)) checkSerialization(DataEnvelope(data1, pruning = Map( - address1 → PruningPerformed(System.currentTimeMillis()), - address3 → PruningInitialized(address2, Set(address1.address))))) + address1 -> PruningPerformed(System.currentTimeMillis()), + address3 -> PruningInitialized(address2, Set(address1.address))))) checkSerialization(Write("A", DataEnvelope(data1))) checkSerialization(WriteAck) checkSerialization(WriteNack) @@ -93,29 +93,29 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( checkSerialization(ReadResult(Some(DataEnvelope(data1)))) checkSerialization(ReadResult(None)) checkSerialization(Status(Map( - "A" → ByteString.fromString("a"), - "B" → ByteString.fromString("b")), chunk = 3, totChunks = 10)) + "A" -> ByteString.fromString("a"), + "B" -> ByteString.fromString("b")), chunk = 3, totChunks = 10)) checkSerialization(Gossip(Map( - "A" → DataEnvelope(data1), - "B" → DataEnvelope(GSet() + "b" + "c")), sendBack = true)) + "A" -> DataEnvelope(data1), + "B" -> DataEnvelope(GSet() + "b" + "c")), sendBack = true)) checkSerialization(DeltaPropagation(address1, reply = true, Map( - "A" → Delta(DataEnvelope(delta1), 1L, 1L), - "B" → Delta(DataEnvelope(delta2), 3L, 5L), - "C" → Delta(DataEnvelope(delta3), 1L, 1L), - "DC" → Delta(DataEnvelope(delta4), 1L, 1L)))) + "A" -> Delta(DataEnvelope(delta1), 1L, 1L), + "B" -> Delta(DataEnvelope(delta2), 3L, 5L), + "C" -> Delta(DataEnvelope(delta3), 1L, 1L), + "DC" -> Delta(DataEnvelope(delta4), 1L, 1L)))) checkSerialization(new DurableDataEnvelope(data1)) val pruning = Map( - address1 → PruningPerformed(System.currentTimeMillis()), - address3 → PruningInitialized(address2, Set(address1.address))) + address1 -> PruningPerformed(System.currentTimeMillis()), + address3 -> PruningInitialized(address2, Set(address1.address))) val deserializedDurableDataEnvelope = checkSerialization(new DurableDataEnvelope(DataEnvelope(data1, pruning, deltaVersions = VersionVector(address1, 13L)))) // equals of DurableDataEnvelope is only checking the data, PruningPerformed // should be serialized val expectedPruning = pruning.filter { - case (_, _: PruningPerformed) ⇒ true - case _ ⇒ false + case (_, _: PruningPerformed) => true + case _ => false } deserializedDurableDataEnvelope.dataEnvelope.pruning should ===(expectedPruning) deserializedDurableDataEnvelope.dataEnvelope.deltaVersions.size should ===(0) @@ -127,12 +127,12 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( import ReplicatorMessageSerializer._ "be power of 2" in { intercept[IllegalArgumentException] { - new SmallCache[String, String](3, 5.seconds, _ ⇒ null) + new SmallCache[String, String](3, 5.seconds, _ => null) } } "get added element" in { - val cache = new SmallCache[Read, String](2, 5.seconds, _ ⇒ null) + val cache = new SmallCache[Read, String](2, 5.seconds, _ => null) val a = Read("a") cache.add(a, "A") cache.get(a) should be("A") @@ -143,7 +143,7 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( } "return null for non-existing elements" in { - val cache = new SmallCache[Read, String](4, 5.seconds, _ ⇒ null) + val cache = new SmallCache[Read, String](4, 5.seconds, _ => null) val a = Read("a") cache.get(a) should be(null) cache.add(a, "A") @@ -152,7 +152,7 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( } "hold latest added elements" in { - val cache = new SmallCache[Read, String](4, 5.seconds, _ ⇒ null) + val cache = new SmallCache[Read, String](4, 5.seconds, _ => null) val a = Read("a") val b = Read("b") val c = Read("c") @@ -183,9 +183,9 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( } "handle Int wrap around" ignore { // ignored because it takes 20 seconds (but it works) - val cache = new SmallCache[Read, String](2, 5.seconds, _ ⇒ null) + val cache = new SmallCache[Read, String](2, 5.seconds, _ => null) val a = Read("a") - val x = a → "A" + val x = a -> "A" var n = 0 while (n <= Int.MaxValue - 3) { cache.add(x) @@ -220,7 +220,7 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( } } - val cache = new SmallCache[Read, AnyRef](4, 5.seconds, a ⇒ createValue(a)) + val cache = new SmallCache[Read, AnyRef](4, 5.seconds, a => createValue(a)) val a = Read("a") val v1 = cache.getOrAdd(a) v1.toString should be("v1") @@ -228,7 +228,7 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( } "evict cache after time-to-live" in { - val cache = new SmallCache[Read, AnyRef](4, 10.millis, _ ⇒ null) + val cache = new SmallCache[Read, AnyRef](4, 10.millis, _ => null) val b = Read("b") val c = Read("c") cache.add(b, "B") @@ -241,7 +241,7 @@ class ReplicatorMessageSerializerSpec extends TestKit(ActorSystem( } "not evict cache before time-to-live" in { - val cache = new SmallCache[Read, AnyRef](4, 5.seconds, _ ⇒ null) + val cache = new SmallCache[Read, AnyRef](4, 5.seconds, _ => null) val b = Read("b") val c = Read("c") cache.add(b, "B") diff --git a/akka-docs/src/main/categories/additional-sink-and-source-converters.md b/akka-docs/src/main/categories/additional-sink-and-source-converters.md index ffa1e81282..9da6bdcc15 100644 --- a/akka-docs/src/main/categories/additional-sink-and-source-converters.md +++ b/akka-docs/src/main/categories/additional-sink-and-source-converters.md @@ -12,7 +12,7 @@ For example, following snippet will fall with timeout exception: ```scala ... -.toMat(StreamConverters.asInputStream().mapMaterializedValue { inputStream ⇒ +.toMat(StreamConverters.asInputStream().mapMaterializedValue { inputStream => inputStream.read() // this could block forever ... }).run() diff --git a/akka-docs/src/main/paradox/common/circuitbreaker.md b/akka-docs/src/main/paradox/common/circuitbreaker.md index 85e8b65719..deb957dba1 100644 --- a/akka-docs/src/main/paradox/common/circuitbreaker.md +++ b/akka-docs/src/main/paradox/common/circuitbreaker.md @@ -115,7 +115,7 @@ Akka circuit breaker provides a way to achieve such use case: All methods above accepts an argument `defineFailureFn` -Type of `defineFailureFn`: @scala[`Try[T] ⇒ Boolean`]@java[`BiFunction[Optional[T], Optional[Throwable], java.lang.Boolean]`] +Type of `defineFailureFn`: @scala[`Try[T] => Boolean`]@java[`BiFunction[Optional[T], Optional[Throwable], java.lang.Boolean]`] @scala[This is a function which takes in a `Try[T]` and returns a `Boolean`. The `Try[T]` correspond to the `Future[T]` of the protected call.] @java[The response of a protected call is modelled using `Optional[T]` for a successful return value and `Optional[Throwable]` for exceptions.] This function should return `true` if the call should increase failure count, else false. diff --git a/akka-docs/src/main/paradox/stream/operators/index.md b/akka-docs/src/main/paradox/stream/operators/index.md index 4f646923de..b3b2cdc805 100644 --- a/akka-docs/src/main/paradox/stream/operators/index.md +++ b/akka-docs/src/main/paradox/stream/operators/index.md @@ -82,7 +82,7 @@ For example, following snippet will fall with timeout exception: ```scala ... -.toMat(StreamConverters.asInputStream().mapMaterializedValue { inputStream ⇒ +.toMat(StreamConverters.asInputStream().mapMaterializedValue { inputStream => inputStream.read() // this could block forever ... }).run() diff --git a/akka-docs/src/test/scala/docs/CompileOnlySpec.scala b/akka-docs/src/test/scala/docs/CompileOnlySpec.scala index 553bdaae89..afc9ae5403 100644 --- a/akka-docs/src/test/scala/docs/CompileOnlySpec.scala +++ b/akka-docs/src/test/scala/docs/CompileOnlySpec.scala @@ -9,5 +9,5 @@ trait CompileOnlySpec { * Given a block of code... does NOT execute it. * Useful when writing code samples in tests, which should only be compiled. */ - def compileOnlySpec(body: ⇒ Unit) = () + def compileOnlySpec(body: => Unit) = () } diff --git a/akka-docs/src/test/scala/docs/actor/ActorDocSpec.scala b/akka-docs/src/test/scala/docs/actor/ActorDocSpec.scala index 680440a8ca..c0e86efa3d 100644 --- a/akka-docs/src/test/scala/docs/actor/ActorDocSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/ActorDocSpec.scala @@ -31,8 +31,8 @@ class MyActor extends Actor { val log = Logging(context.system, this) def receive = { - case "test" ⇒ log.info("received test") - case _ ⇒ log.info("received unknown message") + case "test" => log.info("received test") + case _ => log.info("received unknown message") } } //#my-actor @@ -45,20 +45,20 @@ class FirstActor extends Actor { val child = context.actorOf(Props[MyActor], name = "myChild") //#plus-some-behavior def receive = { - case x ⇒ sender() ! x + case x => sender() ! x } //#plus-some-behavior } //#context-actorOf class ActorWithArgs(arg: String) extends Actor { - def receive = { case _ ⇒ () } + def receive = { case _ => () } } //#actor-with-value-class-argument class Argument(val value: String) extends AnyVal class ValueClassActor(arg: Argument) extends Actor { - def receive = { case _ ⇒ () } + def receive = { case _ => () } } object ValueClassActor { @@ -83,7 +83,7 @@ class DemoActorWrapper extends Actor { class DemoActor(magicNumber: Int) extends Actor { def receive = { - case x: Int ⇒ sender() ! (x + magicNumber) + case x: Int => sender() ! (x + magicNumber) } } @@ -93,7 +93,7 @@ class DemoActorWrapper extends Actor { // ... //#props-factory def receive = { - case msg ⇒ + case msg => } //#props-factory } @@ -111,8 +111,8 @@ class ActorWithMessagesWrapper { class MyActor extends Actor with ActorLogging { import MyActor._ def receive = { - case Greeting(greeter) ⇒ log.info(s"I was greeted by $greeter.") - case Goodbye ⇒ log.info("Someone said goodbye to me.") + case Greeting(greeter) => log.info(s"I was greeted by $greeter.") + case Goodbye => log.info("Someone said goodbye to me.") } } //#messages-in-companion @@ -139,13 +139,13 @@ class Hook extends Actor { class ReplyException extends Actor { def receive = { - case _ ⇒ + case _ => //#reply-exception try { val result = operation() sender() ! result } catch { - case e: Exception ⇒ + case e: Exception => sender() ! akka.actor.Status.Failure(e) throw e } @@ -163,10 +163,10 @@ class StoppingActorsWrapper { val child: ActorRef = ??? def receive = { - case "interrupt-child" ⇒ + case "interrupt-child" => context stop child - case "done" ⇒ + case "done" => context stop self } @@ -185,15 +185,15 @@ class Manager extends Actor { val worker = context.watch(context.actorOf(Props[Cruncher], "worker")) def receive = { - case "job" ⇒ worker ! "crunch" - case Shutdown ⇒ + case "job" => worker ! "crunch" + case Shutdown => worker ! PoisonPill context become shuttingDown } def shuttingDown: Receive = { - case "job" ⇒ sender() ! "service unavailable, shutting down" - case Terminated(`worker`) ⇒ + case "job" => sender() ! "service unavailable, shutting down" + case Terminated(`worker`) => context stop self } } @@ -201,7 +201,7 @@ class Manager extends Actor { class Cruncher extends Actor { def receive = { - case "crunch" ⇒ // crunch... + case "crunch" => // crunch... } } @@ -212,10 +212,10 @@ class Swapper extends Actor { val log = Logging(system, this) def receive = { - case Swap ⇒ + case Swap => log.info("Hi") become({ - case Swap ⇒ + case Swap => log.info("Ho") unbecome() // resets the latest 'become' (just for fun) }, discardOld = false) // push on top instead of replace @@ -237,22 +237,22 @@ object SwapperApp extends App { //#receive-orElse trait ProducerBehavior { - this: Actor ⇒ + this: Actor => val producerBehavior: Receive = { - case GiveMeThings ⇒ + case GiveMeThings => sender() ! Give("thing") } } trait ConsumerBehavior { - this: Actor with ActorLogging ⇒ + this: Actor with ActorLogging => val consumerBehavior: Receive = { - case ref: ActorRef ⇒ + case ref: ActorRef => ref ! GiveMeThings - case Give(thing) ⇒ + case Give(thing) => log.info("Got a thing! It's {}", thing) } } @@ -289,7 +289,7 @@ class Pinger extends Actor { var countDown = 100 def receive = { - case Pong ⇒ + case Pong => println(s"${self.path} received pong, count down $countDown") if (countDown > 0) { @@ -304,7 +304,7 @@ class Pinger extends Actor { class Ponger(pinger: ActorRef) extends Actor { def receive = { - case Ping ⇒ + case Ping => println(s"${self.path} received ping") pinger ! Pong } @@ -331,7 +331,7 @@ class ActorDocSpec extends AkkaSpec(""" import context._ val myActor = actorOf(Props[MyActor], name = "myactor") def receive = { - case x ⇒ myActor ! x + case x => myActor ! x } } //#import-context @@ -348,17 +348,17 @@ class ActorDocSpec extends AkkaSpec(""" // TODO: convert docs to AkkaSpec(Map(...)) val filter = EventFilter.custom { - case e: Logging.Info ⇒ true - case _ ⇒ false + case e: Logging.Info => true + case _ => false } system.eventStream.publish(TestEvent.Mute(filter)) system.eventStream.subscribe(testActor, classOf[Logging.Info]) myActor ! "test" - expectMsgPF(1 second) { case Logging.Info(_, _, "received test") ⇒ true } + expectMsgPF(1 second) { case Logging.Info(_, _, "received test") => true } myActor ! "unknown" - expectMsgPF(1 second) { case Logging.Info(_, _, "received unknown message") ⇒ true } + expectMsgPF(1 second) { case Logging.Info(_, _, "received unknown message") => true } system.eventStream.unsubscribe(testActor) system.eventStream.publish(TestEvent.UnMute(filter)) @@ -436,8 +436,8 @@ class ActorDocSpec extends AkkaSpec(""" "creating actor with IndirectActorProducer" in { class Echo(name: String) extends Actor { def receive = { - case n: Int ⇒ sender() ! name - case message ⇒ + case n: Int => sender() ! name + case message => val target = testActor //#forward target forward message @@ -514,10 +514,10 @@ class ActorDocSpec extends AkkaSpec(""" // To set an initial delay context.setReceiveTimeout(30 milliseconds) def receive = { - case "Hello" ⇒ + case "Hello" => // To set in a response to a message context.setReceiveTimeout(100 milliseconds) - case ReceiveTimeout ⇒ + case ReceiveTimeout => // To turn it off context.setReceiveTimeout(Duration.Undefined) throw new RuntimeException("Receive timed out") @@ -530,18 +530,18 @@ class ActorDocSpec extends AkkaSpec(""" class HotSwapActor extends Actor { import context._ def angry: Receive = { - case "foo" ⇒ sender() ! "I am already angry?" - case "bar" ⇒ become(happy) + case "foo" => sender() ! "I am already angry?" + case "bar" => become(happy) } def happy: Receive = { - case "bar" ⇒ sender() ! "I am already happy :-)" - case "foo" ⇒ become(angry) + case "bar" => sender() ! "I am already happy :-)" + case "foo" => become(angry) } def receive = { - case "foo" ⇒ become(angry) - case "bar" ⇒ become(happy) + case "foo" => become(angry) + case "bar" => become(happy) } } //#hot-swap-actor @@ -555,16 +555,16 @@ class ActorDocSpec extends AkkaSpec(""" import akka.actor.Stash class ActorWithProtocol extends Actor with Stash { def receive = { - case "open" ⇒ + case "open" => unstashAll() context.become({ - case "write" ⇒ // do writing... - case "close" ⇒ + case "write" => // do writing... + case "close" => unstashAll() context.unbecome() - case msg ⇒ stash() + case msg => stash() }, discardOld = false) // stack on top instead of replacing - case msg ⇒ stash() + case msg => stash() } } //#stash @@ -581,9 +581,9 @@ class ActorDocSpec extends AkkaSpec(""" var lastSender = context.system.deadLetters def receive = { - case "kill" ⇒ + case "kill" => context.stop(child); lastSender = sender() - case Terminated(`child`) ⇒ lastSender ! "finished" + case Terminated(`child`) => lastSender ! "finished" } } //#watch @@ -606,7 +606,7 @@ class ActorDocSpec extends AkkaSpec(""" victim ! Kill expectMsgPF(hint = "expecting victim to terminate") { - case Terminated(v) if v == victim ⇒ v // the Actor has indeed terminated + case Terminated(v) if v == victim => v // the Actor has indeed terminated } //#kill } @@ -640,15 +640,15 @@ class ActorDocSpec extends AkkaSpec(""" context.actorSelection("/user/another") ! Identify(identifyId) def receive = { - case ActorIdentity(`identifyId`, Some(ref)) ⇒ + case ActorIdentity(`identifyId`, Some(ref)) => context.watch(ref) context.become(active(ref)) - case ActorIdentity(`identifyId`, None) ⇒ context.stop(self) + case ActorIdentity(`identifyId`, None) => context.stop(self) } def active(another: ActorRef): Actor.Receive = { - case Terminated(`another`) ⇒ context.stop(self) + case Terminated(`another`) => context.stop(self) } } //#identify @@ -673,7 +673,7 @@ class ActorDocSpec extends AkkaSpec(""" // the actor has been stopped } catch { // the actor wasn't stopped within 5 seconds - case e: akka.pattern.AskTimeoutException ⇒ + case e: akka.pattern.AskTimeoutException => } //#gracefulStop } @@ -690,9 +690,9 @@ class ActorDocSpec extends AkkaSpec(""" val f: Future[Result] = for { - x ← ask(actorA, Request).mapTo[Int] // call pattern directly - s ← (actorB ask Request).mapTo[String] // call by implicit conversion - d ← (actorC ? Request).mapTo[Double] // call by symbolic name + x <- ask(actorA, Request).mapTo[Int] // call pattern directly + s <- (actorB ask Request).mapTo[String] // call by implicit conversion + d <- (actorC ? Request).mapTo[Double] // call by symbolic name } yield Result(x, s, d) f pipeTo actorD // .. or .. @@ -702,12 +702,12 @@ class ActorDocSpec extends AkkaSpec(""" class Replier extends Actor { def receive = { - case ref: ActorRef ⇒ + case ref: ActorRef => //#reply-with-sender sender().tell("reply", context.parent) // replies will go back to parent sender().!("reply")(context.parent) // alternative syntax (beware of the parens!) //#reply-with-sender - case x ⇒ + case x => //#reply-without-sender sender() ! x // replies will go to this actor //#reply-without-sender @@ -730,8 +730,8 @@ class ActorDocSpec extends AkkaSpec(""" "using ActorDSL outside of akka.actor package" in { import akka.actor.ActorDSL._ actor(new Act { - superviseWith(OneForOneStrategy() { case _ ⇒ Stop; Restart; Resume; Escalate }) - superviseWith(AllForOneStrategy() { case _ ⇒ Stop; Restart; Resume; Escalate }) + superviseWith(OneForOneStrategy() { case _ => Stop; Restart; Resume; Escalate }) + superviseWith(AllForOneStrategy() { case _ => Stop; Restart; Resume; Escalate }) }) } @@ -739,11 +739,11 @@ class ActorDocSpec extends AkkaSpec(""" val someActor = system.actorOf(Props(classOf[Replier], this)) //#coordinated-shutdown-addTask CoordinatedShutdown(system).addTask( - CoordinatedShutdown.PhaseBeforeServiceUnbind, "someTaskName") { () ⇒ + CoordinatedShutdown.PhaseBeforeServiceUnbind, "someTaskName") { () => import akka.pattern.ask import system.dispatcher implicit val timeout = Timeout(5.seconds) - (someActor ? "stop").map(_ ⇒ Done) + (someActor ? "stop").map(_ => Done) } //#coordinated-shutdown-addTask diff --git a/akka-docs/src/test/scala/docs/actor/BlockingDispatcherSample.scala b/akka-docs/src/test/scala/docs/actor/BlockingDispatcherSample.scala index dd9ffcbe85..a0a4d24f5c 100644 --- a/akka-docs/src/test/scala/docs/actor/BlockingDispatcherSample.scala +++ b/akka-docs/src/test/scala/docs/actor/BlockingDispatcherSample.scala @@ -12,7 +12,7 @@ import scala.concurrent.{ ExecutionContext, Future } // #blocking-in-actor class BlockingActor extends Actor { def receive = { - case i: Int ⇒ + case i: Int => Thread.sleep(5000) //block for 5 seconds, representing blocking I/O, etc println(s"Blocking operation finished: ${i}") } @@ -24,7 +24,7 @@ class BlockingFutureActor extends Actor { implicit val executionContext: ExecutionContext = context.dispatcher def receive = { - case i: Int ⇒ + case i: Int => println(s"Calling blocking Future: ${i}") Future { Thread.sleep(5000) //block for 5 seconds @@ -39,7 +39,7 @@ class SeparateDispatcherFutureActor extends Actor { implicit val executionContext: ExecutionContext = context.system.dispatchers.lookup("my-blocking-dispatcher") def receive = { - case i: Int ⇒ + case i: Int => println(s"Calling blocking Future: ${i}") Future { Thread.sleep(5000) //block for 5 seconds @@ -52,7 +52,7 @@ class SeparateDispatcherFutureActor extends Actor { // #print-actor class PrintActor extends Actor { def receive = { - case i: Int ⇒ + case i: Int => println(s"PrintActor: ${i}") } } @@ -67,7 +67,7 @@ object BlockingDispatcherSample { val actor1 = system.actorOf(Props(new BlockingFutureActor)) val actor2 = system.actorOf(Props(new PrintActor)) - for (i ← 1 to 100) { + for (i <- 1 to 100) { actor1 ! i actor2 ! i } @@ -103,7 +103,7 @@ object SeparateDispatcherSample { val actor1 = system.actorOf(Props(new SeparateDispatcherFutureActor)) val actor2 = system.actorOf(Props(new PrintActor)) - for (i ← 1 to 100) { + for (i <- 1 to 100) { actor1 ! i actor2 ! i } diff --git a/akka-docs/src/test/scala/docs/actor/FSMDocSpec.scala b/akka-docs/src/test/scala/docs/actor/FSMDocSpec.scala index 416c40fbab..865e49797d 100644 --- a/akka-docs/src/test/scala/docs/actor/FSMDocSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/FSMDocSpec.scala @@ -6,7 +6,7 @@ package docs.actor import language.postfixOps -import akka.testkit.{ AkkaSpec ⇒ MyFavoriteTestFrameWorkPlusAkkaTestKit } +import akka.testkit.{ AkkaSpec => MyFavoriteTestFrameWorkPlusAkkaTestKit } import akka.util.ByteString //#test-code @@ -55,24 +55,24 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit { //#when-syntax when(Idle) { - case Event(SetTarget(ref), Uninitialized) ⇒ + case Event(SetTarget(ref), Uninitialized) => stay using Todo(ref, Vector.empty) } //#when-syntax //#transition-elided onTransition { - case Active -> Idle ⇒ + case Active -> Idle => stateData match { - case Todo(ref, queue) ⇒ ref ! Batch(queue) - case _ ⇒ // nothing to do + case Todo(ref, queue) => ref ! Batch(queue) + case _ => // nothing to do } } //#transition-elided //#when-syntax when(Active, stateTimeout = 1 second) { - case Event(Flush | StateTimeout, t: Todo) ⇒ + case Event(Flush | StateTimeout, t: Todo) => goto(Idle) using t.copy(queue = Vector.empty) } //#when-syntax @@ -80,10 +80,10 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit { //#unhandled-elided whenUnhandled { // common code for both states - case Event(Queue(obj), t @ Todo(_, v)) ⇒ + case Event(Queue(obj), t @ Todo(_, v)) => goto(Active) using t.copy(queue = v :+ obj) - case Event(e, s) ⇒ + case Event(e, s) => log.warning("received unhandled request {} in state {}/{}", e, stateName, s) stay } @@ -109,16 +109,16 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit { //#modifier-syntax when(SomeState) { - case Event(msg, _) ⇒ + case Event(msg, _) => goto(Processing) using (newData) forMax (5 seconds) replying (WillDo) } //#modifier-syntax //#transition-syntax onTransition { - case Idle -> Active ⇒ setTimer("timeout", Tick, 1 second, repeat = true) - case Active -> _ ⇒ cancelTimer("timeout") - case x -> Idle ⇒ log.info("entering Idle from " + x) + case Idle -> Active => setTimer("timeout", Tick, 1 second, repeat = true) + case Active -> _ => cancelTimer("timeout") + case x -> Idle => log.info("entering Idle from " + x) } //#transition-syntax @@ -132,7 +132,7 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit { //#stop-syntax when(Error) { - case Event("stop", _) ⇒ + case Event("stop", _) => // do cleanup ... stop() } @@ -140,38 +140,38 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit { //#transform-syntax when(SomeState)(transform { - case Event(bytes: ByteString, read) ⇒ stay using (read + bytes.length) + case Event(bytes: ByteString, read) => stay using (read + bytes.length) } using { - case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 ⇒ + case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 => goto(Processing) }) //#transform-syntax //#alt-transform-syntax val processingTrigger: PartialFunction[State, State] = { - case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 ⇒ + case s @ FSM.State(state, read, timeout, stopReason, replies) if read > 1000 => goto(Processing) } when(SomeState)(transform { - case Event(bytes: ByteString, read) ⇒ stay using (read + bytes.length) + case Event(bytes: ByteString, read) => stay using (read + bytes.length) } using processingTrigger) //#alt-transform-syntax //#termination-syntax onTermination { - case StopEvent(FSM.Normal, state, data) ⇒ // ... - case StopEvent(FSM.Shutdown, state, data) ⇒ // ... - case StopEvent(FSM.Failure(cause), state, data) ⇒ // ... + case StopEvent(FSM.Normal, state, data) => // ... + case StopEvent(FSM.Shutdown, state, data) => // ... + case StopEvent(FSM.Failure(cause), state, data) => // ... } //#termination-syntax //#unhandled-syntax whenUnhandled { - case Event(x: X, data) ⇒ + case Event(x: X, data) => log.info("Received unhandled event: " + x) stay - case Event(msg, _) ⇒ + case Event(msg, _) => log.warning("Received unknown event: " + msg) goto(Error) } @@ -185,7 +185,7 @@ class FSMDocSpec extends MyFavoriteTestFrameWorkPlusAkkaTestKit { //#body-elided override def logDepth = 12 onTermination { - case StopEvent(FSM.Failure(_), state, data) ⇒ + case StopEvent(FSM.Failure(_), state, data) => val lastEvents = getLog.mkString("\n\t") log.warning("Failure in state " + state + " with data " + data + "\n" + "Events leading up to this point:\n\t" + lastEvents) diff --git a/akka-docs/src/test/scala/docs/actor/FaultHandlingDocSample.scala b/akka-docs/src/test/scala/docs/actor/FaultHandlingDocSample.scala index 671a0a1204..e4e65418b2 100644 --- a/akka-docs/src/test/scala/docs/actor/FaultHandlingDocSample.scala +++ b/akka-docs/src/test/scala/docs/actor/FaultHandlingDocSample.scala @@ -50,14 +50,14 @@ class Listener extends Actor with ActorLogging { context.setReceiveTimeout(15 seconds) def receive = { - case Progress(percent) ⇒ + case Progress(percent) => log.info("Current progress: {} %", percent) if (percent >= 100.0) { log.info("That's all, shutting down") context.system.terminate() } - case ReceiveTimeout ⇒ + case ReceiveTimeout => // No progress within 15 seconds, ServiceUnavailable log.error("Shutting down due to unavailable service") context.system.terminate() @@ -84,7 +84,7 @@ class Worker extends Actor with ActorLogging { // Stop the CounterService child if it throws ServiceUnavailable override val supervisorStrategy = OneForOneStrategy() { - case _: CounterService.ServiceUnavailable ⇒ Stop + case _: CounterService.ServiceUnavailable => Stop } // The sender of the initial Start message will continuously be notified @@ -95,18 +95,18 @@ class Worker extends Actor with ActorLogging { import context.dispatcher // Use this Actors' Dispatcher as ExecutionContext def receive = LoggingReceive { - case Start if progressListener.isEmpty ⇒ + case Start if progressListener.isEmpty => progressListener = Some(sender()) context.system.scheduler.schedule(Duration.Zero, 1 second, self, Do) - case Do ⇒ + case Do => counterService ! Increment(1) counterService ! Increment(1) counterService ! Increment(1) // Send current progress to the initial sender counterService ? GetCurrentCount map { - case CurrentCount(_, count) ⇒ Progress(100.0 * count / totalCount) + case CurrentCount(_, count) => Progress(100.0 * count / totalCount) } pipeTo progressListener.get } } @@ -138,7 +138,7 @@ class CounterService extends Actor { override val supervisorStrategy = OneForOneStrategy( maxNrOfRetries = 3, withinTimeRange = 5 seconds) { - case _: Storage.StorageException ⇒ Restart + case _: Storage.StorageException => Restart } val key = self.path.name @@ -169,21 +169,21 @@ class CounterService extends Actor { def receive = LoggingReceive { - case Entry(k, v) if k == key && counter == None ⇒ + case Entry(k, v) if k == key && counter == None => // Reply from Storage of the initial value, now we can create the Counter val c = context.actorOf(Props(classOf[Counter], key, v)) counter = Some(c) // Tell the counter to use current storage c ! UseStorage(storage) // and send the buffered backlog to the counter - for ((replyTo, msg) ← backlog) c.tell(msg, sender = replyTo) + for ((replyTo, msg) <- backlog) c.tell(msg, sender = replyTo) backlog = IndexedSeq.empty - case msg: Increment ⇒ forwardOrPlaceInBacklog(msg) + case msg: Increment => forwardOrPlaceInBacklog(msg) - case msg: GetCurrentCount ⇒ forwardOrPlaceInBacklog(msg) + case msg: GetCurrentCount => forwardOrPlaceInBacklog(msg) - case Terminated(actorRef) if Some(actorRef) == storage ⇒ + case Terminated(actorRef) if Some(actorRef) == storage => // After 3 restarts the storage child is stopped. // We receive Terminated because we watch the child, see initStorage. storage = None @@ -192,7 +192,7 @@ class CounterService extends Actor { // Try to re-establish storage after while context.system.scheduler.scheduleOnce(10 seconds, self, Reconnect) - case Reconnect ⇒ + case Reconnect => // Re-establish storage after the scheduled delay initStorage() } @@ -202,8 +202,8 @@ class CounterService extends Actor { // the counter. Before that we place the messages in a backlog, to be sent // to the counter when it is initialized. counter match { - case Some(c) ⇒ c forward msg - case None ⇒ + case Some(c) => c forward msg + case None => if (backlog.size >= MaxBacklog) throw new ServiceUnavailable( "CounterService not available, lack of initial value") @@ -233,15 +233,15 @@ class Counter(key: String, initialValue: Long) extends Actor { var storage: Option[ActorRef] = None def receive = LoggingReceive { - case UseStorage(s) ⇒ + case UseStorage(s) => storage = s storeCount() - case Increment(n) ⇒ + case Increment(n) => count += n storeCount() - case GetCurrentCount ⇒ + case GetCurrentCount => sender() ! CurrentCount(key, count) } @@ -274,8 +274,8 @@ class Storage extends Actor { val db = DummyDB def receive = LoggingReceive { - case Store(Entry(key, count)) ⇒ db.save(key, count) - case Get(key) ⇒ sender() ! Entry(key, db.load(key).getOrElse(0L)) + case Store(Entry(key, count)) => db.save(key, count) + case Get(key) => sender() ! Entry(key, db.load(key).getOrElse(0L)) } } diff --git a/akka-docs/src/test/scala/docs/actor/FaultHandlingDocSpec.scala b/akka-docs/src/test/scala/docs/actor/FaultHandlingDocSpec.scala index 60ccbffaff..b327d880c8 100644 --- a/akka-docs/src/test/scala/docs/actor/FaultHandlingDocSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/FaultHandlingDocSpec.scala @@ -29,15 +29,15 @@ object FaultHandlingDocSpec { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { - case _: ArithmeticException ⇒ Resume - case _: NullPointerException ⇒ Restart - case _: IllegalArgumentException ⇒ Stop - case _: Exception ⇒ Escalate + case _: ArithmeticException => Resume + case _: NullPointerException => Restart + case _: IllegalArgumentException => Stop + case _: Exception => Escalate } //#strategy def receive = { - case p: Props ⇒ sender() ! context.actorOf(p) + case p: Props => sender() ! context.actorOf(p) } } //#supervisor @@ -51,15 +51,15 @@ object FaultHandlingDocSpec { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { - case _: ArithmeticException ⇒ Resume - case _: NullPointerException ⇒ Restart - case _: IllegalArgumentException ⇒ Stop - case _: Exception ⇒ Escalate + case _: ArithmeticException => Resume + case _: NullPointerException => Restart + case _: IllegalArgumentException => Stop + case _: Exception => Escalate } //#strategy2 def receive = { - case p: Props ⇒ sender() ! context.actorOf(p) + case p: Props => sender() ! context.actorOf(p) } // override default to kill all children during restart override def preRestart(cause: Throwable, msg: Option[Any]): Unit = {} @@ -74,9 +74,9 @@ object FaultHandlingDocSpec { override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) { - case _: ArithmeticException ⇒ Resume - case t ⇒ - super.supervisorStrategy.decider.applyOrElse(t, (_: Any) ⇒ Escalate) + case _: ArithmeticException => Resume + case t => + super.supervisorStrategy.decider.applyOrElse(t, (_: Any) => Escalate) } //#default-strategy-fallback @@ -87,9 +87,9 @@ object FaultHandlingDocSpec { class Child extends Actor { var state = 0 def receive = { - case ex: Exception ⇒ throw ex - case x: Int ⇒ state = x - case "get" ⇒ sender() ! state + case ex: Exception => throw ex + case x: Int => state = x + case "get" => sender() ! state } } //#child @@ -149,7 +149,7 @@ class FaultHandlingDocSpec(_system: ActorSystem) extends TestKit(_system) //#stop watch(child) // have testActor watch “child” child ! new IllegalArgumentException // break it - expectMsgPF() { case Terminated(`child`) ⇒ () } + expectMsgPF() { case Terminated(`child`) => () } //#stop } EventFilter[Exception]("CRASH", occurrences = 2) intercept { @@ -162,7 +162,7 @@ class FaultHandlingDocSpec(_system: ActorSystem) extends TestKit(_system) child2 ! new Exception("CRASH") // escalate failure expectMsgPF() { - case t @ Terminated(`child2`) if t.existenceConfirmed ⇒ () + case t @ Terminated(`child2`) if t.existenceConfirmed => () } //#escalate-kill //#escalate-restart diff --git a/akka-docs/src/test/scala/docs/actor/InitializationDocSpec.scala b/akka-docs/src/test/scala/docs/actor/InitializationDocSpec.scala index 24611615b0..3bf1a69206 100644 --- a/akka-docs/src/test/scala/docs/actor/InitializationDocSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/InitializationDocSpec.scala @@ -11,7 +11,7 @@ object InitializationDocSpec { class PreStartInitExample extends Actor { override def receive = { - case _ ⇒ // Ignore + case _ => // Ignore } //#preStartInit @@ -38,14 +38,14 @@ object InitializationDocSpec { var initializeMe: Option[String] = None override def receive = { - case "init" ⇒ + case "init" => initializeMe = Some("Up and running") context.become(initialized, discardOld = true) } def initialized: Receive = { - case "U OK?" ⇒ initializeMe foreach { sender() ! _ } + case "U OK?" => initializeMe foreach { sender() ! _ } } //#messageInit diff --git a/akka-docs/src/test/scala/docs/actor/PropsEdgeCaseSpec.scala b/akka-docs/src/test/scala/docs/actor/PropsEdgeCaseSpec.scala index b8bc9f45e2..384d4970c9 100644 --- a/akka-docs/src/test/scala/docs/actor/PropsEdgeCaseSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/PropsEdgeCaseSpec.scala @@ -18,7 +18,7 @@ class PropsEdgeCaseSpec extends WordSpec with CompileOnlySpec { //#props-edge-cases-value-class-example class ValueActor(value: MyValueClass) extends Actor { def receive = { - case multiplier: Long ⇒ sender() ! (value.v * multiplier) + case multiplier: Long => sender() ! (value.v * multiplier) } } val valueClassProp = Props(classOf[ValueActor], MyValueClass(5)) // Unsupported @@ -27,7 +27,7 @@ class PropsEdgeCaseSpec extends WordSpec with CompileOnlySpec { //#props-edge-cases-default-values class DefaultValueActor(a: Int, b: Int = 5) extends Actor { def receive = { - case x: Int ⇒ sender() ! ((a + x) * b) + case x: Int => sender() ! ((a + x) * b) } } @@ -35,7 +35,7 @@ class PropsEdgeCaseSpec extends WordSpec with CompileOnlySpec { class DefaultValueActor2(b: Int = 5) extends Actor { def receive = { - case x: Int ⇒ sender() ! (x * b) + case x: Int => sender() ! (x * b) } } val defaultValueProp2 = Props[DefaultValueActor2] // Unsupported diff --git a/akka-docs/src/test/scala/docs/actor/SchedulerDocSpec.scala b/akka-docs/src/test/scala/docs/actor/SchedulerDocSpec.scala index bfd2f600f2..3790ed39b4 100644 --- a/akka-docs/src/test/scala/docs/actor/SchedulerDocSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/SchedulerDocSpec.scala @@ -44,7 +44,7 @@ class SchedulerDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) { val Tick = "tick" class TickActor extends Actor { def receive = { - case Tick ⇒ //Do something + case Tick => //Do something } } val tickActor = system.actorOf(Props(classOf[TickActor], this)) diff --git a/akka-docs/src/test/scala/docs/actor/SharedMutableStateDocSpec.scala b/akka-docs/src/test/scala/docs/actor/SharedMutableStateDocSpec.scala index 5d01dd49b4..2f004cc2e5 100644 --- a/akka-docs/src/test/scala/docs/actor/SharedMutableStateDocSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/SharedMutableStateDocSpec.scala @@ -19,13 +19,13 @@ class SharedMutableStateDocSpec { class EchoActor extends Actor { def receive = { - case msg ⇒ sender() ! msg + case msg => sender() ! msg } } class CleanUpActor extends Actor { def receive = { - case set: mutable.Set[_] ⇒ set.clear() + case set: mutable.Set[_] => set.clear() } } @@ -44,7 +44,7 @@ class SharedMutableStateDocSpec { } def receive = { - case _ ⇒ + case _ => implicit val ec = context.dispatcher implicit val timeout = Timeout(5 seconds) // needed for `?` below @@ -53,7 +53,7 @@ class SharedMutableStateDocSpec { // application to break in weird ways Future { state = "This will race" } ((echoActor ? Message("With this other one")).mapTo[Message]) - .foreach { received ⇒ state = received.msg } + .foreach { received => state = received.msg } // Very bad: shared mutable object allows // the other actor to mutate your own state, diff --git a/akka-docs/src/test/scala/docs/actor/TimerDocSpec.scala b/akka-docs/src/test/scala/docs/actor/TimerDocSpec.scala index d9d7015c69..2c8780926d 100644 --- a/akka-docs/src/test/scala/docs/actor/TimerDocSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/TimerDocSpec.scala @@ -22,10 +22,10 @@ object TimerDocSpec { timers.startSingleTimer(TickKey, FirstTick, 500.millis) def receive = { - case FirstTick ⇒ + case FirstTick => // do something useful here timers.startPeriodicTimer(TickKey, Tick, 1.second) - case Tick ⇒ + case Tick => // do something useful here } } diff --git a/akka-docs/src/test/scala/docs/actor/TypedActorDocSpec.scala b/akka-docs/src/test/scala/docs/actor/TypedActorDocSpec.scala index 679ddd716f..0eb135f6f4 100644 --- a/akka-docs/src/test/scala/docs/actor/TypedActorDocSpec.scala +++ b/akka-docs/src/test/scala/docs/actor/TypedActorDocSpec.scala @@ -5,7 +5,7 @@ package docs.actor //#imports -import java.lang.String.{ valueOf ⇒ println } +import java.lang.String.{ valueOf => println } import akka.actor.{ ActorContext, ActorRef, TypedActor, TypedProps } import akka.routing.RoundRobinGroup @@ -16,7 +16,7 @@ import scala.concurrent.duration._ //#imports //Mr funny man avoids printing to stdout AND keeping docs alright -import java.lang.String.{ valueOf ⇒ println } +import java.lang.String.{ valueOf => println } //#typed-actor-iface trait Squarer { @@ -112,7 +112,7 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) { //#typed-actor-extension-tools } catch { - case e: Exception ⇒ //dun care + case e: Exception => //dun care } } @@ -182,7 +182,7 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) { //Use "childSquarer" as a Squarer //#typed-actor-hierarchy } catch { - case e: Exception ⇒ //ignore + case e: Exception => //ignore } } @@ -205,7 +205,7 @@ class TypedActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) { // prepare routees val routees: List[HasName] = List.fill(5) { namedActor() } - val routeePaths = routees map { r ⇒ + val routeePaths = routees map { r => TypedActor(system).getActorRefFor(r).path.toStringWithoutAddress } diff --git a/akka-docs/src/test/scala/docs/actor/UnnestedReceives.scala b/akka-docs/src/test/scala/docs/actor/UnnestedReceives.scala index 03f872f261..b996bbc4fb 100644 --- a/akka-docs/src/test/scala/docs/actor/UnnestedReceives.scala +++ b/akka-docs/src/test/scala/docs/actor/UnnestedReceives.scala @@ -35,16 +35,16 @@ class UnnestedReceives extends Actor { } def receive = { - case 'Replay ⇒ //Our first message should be a 'Replay message, all others are invalid + case 'Replay => //Our first message should be a 'Replay message, all others are invalid allOldMessages() foreach process //Process all old messages/events become { //Switch behavior to look for the GoAhead signal - case 'GoAhead ⇒ //When we get the GoAhead signal we process all our buffered messages/events + case 'GoAhead => //When we get the GoAhead signal we process all our buffered messages/events queue foreach process queue.clear become { //Then we change behavior to process incoming messages/events as they arrive - case msg ⇒ process(msg) + case msg => process(msg) } - case msg ⇒ //While we haven't gotten the GoAhead signal, buffer all incoming messages + case msg => //While we haven't gotten the GoAhead signal, buffer all incoming messages queue += msg //Here you have full control, you can handle overflow etc } } diff --git a/akka-docs/src/test/scala/docs/agent/AgentDocSpec.scala b/akka-docs/src/test/scala/docs/agent/AgentDocSpec.scala index 52685bdd89..9845fe514c 100644 --- a/akka-docs/src/test/scala/docs/agent/AgentDocSpec.scala +++ b/akka-docs/src/test/scala/docs/agent/AgentDocSpec.scala @@ -60,7 +60,7 @@ class AgentDocSpec extends AkkaSpec { agent send (_ * 2) //#send - def longRunningOrBlockingFunction = (i: Int) ⇒ i * 1 // Just for the example code + def longRunningOrBlockingFunction = (i: Int) => i * 1 // Just for the example code def someExecutionContext() = scala.concurrent.ExecutionContext.Implicits.global // Just for the example code //#send-off // the ExecutionContext you want to run the function on @@ -83,7 +83,7 @@ class AgentDocSpec extends AkkaSpec { val f3: Future[Int] = agent alter (_ * 2) //#alter - def longRunningOrBlockingFunction = (i: Int) ⇒ i * 1 // Just for the example code + def longRunningOrBlockingFunction = (i: Int) => i * 1 // Just for the example code def someExecutionContext() = ExecutionContext.global // Just for the example code //#alter-off @@ -104,7 +104,7 @@ class AgentDocSpec extends AkkaSpec { import scala.concurrent.stm._ def transfer(from: Agent[Int], to: Agent[Int], amount: Int): Boolean = { - atomic { txn ⇒ + atomic { txn => if (from.get < amount) false else { from send (_ - amount) @@ -135,19 +135,19 @@ class AgentDocSpec extends AkkaSpec { val agent2 = Agent(5) // uses foreach - for (value ← agent1) + for (value <- agent1) println(value) // uses map - val agent3 = for (value ← agent1) yield value + 1 + val agent3 = for (value <- agent1) yield value + 1 // or using map directly val agent4 = agent1 map (_ + 1) // uses flatMap val agent5 = for { - value1 ← agent1 - value2 ← agent2 + value1 <- agent1 + value2 <- agent2 } yield value1 + value2 //#monadic-example diff --git a/akka-docs/src/test/scala/docs/camel/Consumers.scala b/akka-docs/src/test/scala/docs/camel/Consumers.scala index 6ffcaa226c..9c9057bcf6 100644 --- a/akka-docs/src/test/scala/docs/camel/Consumers.scala +++ b/akka-docs/src/test/scala/docs/camel/Consumers.scala @@ -15,7 +15,7 @@ object Consumers { def endpointUri = "file:data/input/actor" def receive = { - case msg: CamelMessage ⇒ println("received %s" format msg.bodyAs[String]) + case msg: CamelMessage => println("received %s" format msg.bodyAs[String]) } } //#Consumer1 @@ -28,7 +28,7 @@ object Consumers { def endpointUri = "jetty:http://localhost:8877/camel/default" def receive = { - case msg: CamelMessage ⇒ sender() ! ("Hello %s" format msg.bodyAs[String]) + case msg: CamelMessage => sender() ! ("Hello %s" format msg.bodyAs[String]) } } //#Consumer2 @@ -45,7 +45,7 @@ object Consumers { def endpointUri = "jms:queue:test" def receive = { - case msg: CamelMessage ⇒ + case msg: CamelMessage => sender() ! Ack // on success // .. @@ -65,7 +65,7 @@ object Consumers { def endpointUri = "jetty:http://localhost:8877/camel/default" override def replyTimeout = 500 millis def receive = { - case msg: CamelMessage ⇒ sender() ! ("Hello %s" format msg.bodyAs[String]) + case msg: CamelMessage => sender() ! ("Hello %s" format msg.bodyAs[String]) } } //#Consumer4 diff --git a/akka-docs/src/test/scala/docs/camel/CustomRoute.scala b/akka-docs/src/test/scala/docs/camel/CustomRoute.scala index eaaf35bc98..ee930790aa 100644 --- a/akka-docs/src/test/scala/docs/camel/CustomRoute.scala +++ b/akka-docs/src/test/scala/docs/camel/CustomRoute.scala @@ -18,9 +18,9 @@ object CustomRoute { import akka.camel._ class Responder extends Actor { def receive = { - case msg: CamelMessage ⇒ + case msg: CamelMessage => sender() ! (msg.mapBody { - body: String ⇒ "received %s" format body + body: String => "received %s" format body }) } } @@ -47,9 +47,9 @@ object CustomRoute { class ErrorThrowingConsumer(override val endpointUri: String) extends Consumer { def receive = { - case msg: CamelMessage ⇒ throw new Exception("error: %s" format msg.body) + case msg: CamelMessage => throw new Exception("error: %s" format msg.body) } - override def onRouteDefinition = (rd) ⇒ rd.onException(classOf[Exception]). + override def onRouteDefinition = (rd) => rd.onException(classOf[Exception]). handled(true).transform(Builder.exceptionMessage).end final override def preRestart(reason: Throwable, message: Option[Any]): Unit = { diff --git a/akka-docs/src/test/scala/docs/camel/Introduction.scala b/akka-docs/src/test/scala/docs/camel/Introduction.scala index 05be15e965..0460beed78 100644 --- a/akka-docs/src/test/scala/docs/camel/Introduction.scala +++ b/akka-docs/src/test/scala/docs/camel/Introduction.scala @@ -21,8 +21,8 @@ object Introduction { def endpointUri = "mina2:tcp://localhost:6200?textline=true" def receive = { - case msg: CamelMessage ⇒ { /* ... */ } - case _ ⇒ { /* ... */ } + case msg: CamelMessage => { /* ... */ } + case _ => { /* ... */ } } } @@ -41,8 +41,8 @@ object Introduction { def endpointUri = "jetty:http://localhost:8877/example" def receive = { - case msg: CamelMessage ⇒ { /* ... */ } - case _ ⇒ { /* ... */ } + case msg: CamelMessage => { /* ... */ } + case _ => { /* ... */ } } } //#Consumer @@ -91,8 +91,8 @@ object Introduction { def endpointUri = "mina2:tcp://localhost:6200?textline=true" def receive = { - case msg: CamelMessage ⇒ { /* ... */ } - case _ ⇒ { /* ... */ } + case msg: CamelMessage => { /* ... */ } + case _ => { /* ... */ } } } val system = ActorSystem("some-system") diff --git a/akka-docs/src/test/scala/docs/camel/Producers.scala b/akka-docs/src/test/scala/docs/camel/Producers.scala index a6cc1de011..f6ff60e87e 100644 --- a/akka-docs/src/test/scala/docs/camel/Producers.scala +++ b/akka-docs/src/test/scala/docs/camel/Producers.scala @@ -37,7 +37,7 @@ object Producers { class ResponseReceiver extends Actor { def receive = { - case msg: CamelMessage ⇒ + case msg: CamelMessage => // do something with the forwarded response } } @@ -65,11 +65,11 @@ object Producers { def endpointUri = uri def upperCase(msg: CamelMessage) = msg.mapBody { - body: String ⇒ body.toUpperCase + body: String => body.toUpperCase } override def transformOutgoingMessage(msg: Any) = msg match { - case msg: CamelMessage ⇒ upperCase(msg) + case msg: CamelMessage => upperCase(msg) } } //#TransformOutgoingMessage @@ -110,7 +110,7 @@ object Producers { import akka.actor.Actor class MyActor extends Actor { def receive = { - case msg ⇒ + case msg => val template = CamelExtension(context.system).template template.sendBody("direct:news", msg) } @@ -122,7 +122,7 @@ object Producers { import akka.actor.Actor class MyActor extends Actor { def receive = { - case msg ⇒ + case msg => val template = CamelExtension(context.system).template sender() ! template.requestBody("direct:news", msg) } diff --git a/akka-docs/src/test/scala/docs/camel/PublishSubscribe.scala b/akka-docs/src/test/scala/docs/camel/PublishSubscribe.scala index 98a97189a9..c39b9ecf0c 100644 --- a/akka-docs/src/test/scala/docs/camel/PublishSubscribe.scala +++ b/akka-docs/src/test/scala/docs/camel/PublishSubscribe.scala @@ -13,7 +13,7 @@ object PublishSubscribe { def endpointUri = uri def receive = { - case msg: CamelMessage ⇒ println("%s received: %s" format (name, msg.body)) + case msg: CamelMessage => println("%s received: %s" format (name, msg.body)) } } @@ -29,7 +29,7 @@ object PublishSubscribe { def endpointUri = uri def receive = { - case msg: CamelMessage ⇒ { + case msg: CamelMessage => { publisher ! msg.bodyAs[String] sender() ! ("message published") } diff --git a/akka-docs/src/test/scala/docs/circuitbreaker/CircuitBreakerDocSpec.scala b/akka-docs/src/test/scala/docs/circuitbreaker/CircuitBreakerDocSpec.scala index 83d26a7bf5..b6aacd3aca 100644 --- a/akka-docs/src/test/scala/docs/circuitbreaker/CircuitBreakerDocSpec.scala +++ b/akka-docs/src/test/scala/docs/circuitbreaker/CircuitBreakerDocSpec.scala @@ -36,9 +36,9 @@ class DangerousActor extends Actor with ActorLogging { def dangerousCall: String = "This really isn't that dangerous of a call after all" def receive = { - case "is my middle name" ⇒ + case "is my middle name" => breaker.withCircuitBreaker(Future(dangerousCall)) pipeTo sender() - case "block for me" ⇒ + case "block for me" => sender() ! breaker.withSyncCircuitBreaker(dangerousCall) } //#circuit-breaker-usage @@ -62,16 +62,16 @@ class TellPatternActor(recipient: ActorRef) extends Actor with ActorLogging { import akka.actor.ReceiveTimeout def receive = { - case "call" if breaker.isClosed ⇒ { + case "call" if breaker.isClosed => { recipient ! "message" } - case "response" ⇒ { + case "response" => { breaker.succeed() } - case err: Throwable ⇒ { + case err: Throwable => { breaker.fail() } - case ReceiveTimeout ⇒ { + case ReceiveTimeout => { breaker.fail() } } @@ -82,9 +82,9 @@ class EvenNoFailureActor extends Actor { import context.dispatcher //#even-no-as-failure def luckyNumber(): Future[Int] = { - val evenNumberAsFailure: Try[Int] ⇒ Boolean = { - case Success(n) ⇒ n % 2 == 0 - case Failure(_) ⇒ true + val evenNumberAsFailure: Try[Int] => Boolean = { + case Success(n) => n % 2 == 0 + case Failure(_) => true } val breaker = @@ -100,6 +100,6 @@ class EvenNoFailureActor extends Actor { //#even-no-as-failure override def receive = { - case x: Int ⇒ + case x: Int => } } diff --git a/akka-docs/src/test/scala/docs/cluster/FactorialBackend.scala b/akka-docs/src/test/scala/docs/cluster/FactorialBackend.scala index 5969c46eb7..497f04e0a5 100644 --- a/akka-docs/src/test/scala/docs/cluster/FactorialBackend.scala +++ b/akka-docs/src/test/scala/docs/cluster/FactorialBackend.scala @@ -19,8 +19,8 @@ class FactorialBackend extends Actor with ActorLogging { import context.dispatcher def receive = { - case (n: Int) ⇒ - Future(factorial(n)) map { result ⇒ (n, result) } pipeTo sender() + case (n: Int) => + Future(factorial(n)) map { result => (n, result) } pipeTo sender() } def factorial(n: Int): BigInt = { diff --git a/akka-docs/src/test/scala/docs/cluster/FactorialFrontend.scala b/akka-docs/src/test/scala/docs/cluster/FactorialFrontend.scala index 209a6b1d42..7cb1c224f8 100644 --- a/akka-docs/src/test/scala/docs/cluster/FactorialFrontend.scala +++ b/akka-docs/src/test/scala/docs/cluster/FactorialFrontend.scala @@ -31,13 +31,13 @@ class FactorialFrontend(upToN: Int, repeat: Boolean) extends Actor with ActorLog } def receive = { - case (n: Int, factorial: BigInt) ⇒ + case (n: Int, factorial: BigInt) => if (n == upToN) { log.debug("{}! = {}", n, factorial) if (repeat) sendJobs() else context.stop(self) } - case ReceiveTimeout ⇒ + case ReceiveTimeout => log.info("Timeout") sendJobs() } diff --git a/akka-docs/src/test/scala/docs/cluster/MetricsListener.scala b/akka-docs/src/test/scala/docs/cluster/MetricsListener.scala index c05fb86bf3..9eb944c8d4 100644 --- a/akka-docs/src/test/scala/docs/cluster/MetricsListener.scala +++ b/akka-docs/src/test/scala/docs/cluster/MetricsListener.scala @@ -27,24 +27,24 @@ class MetricsListener extends Actor with ActorLogging { override def postStop(): Unit = extension.unsubscribe(self) def receive = { - case ClusterMetricsChanged(clusterMetrics) ⇒ - clusterMetrics.filter(_.address == selfAddress) foreach { nodeMetrics ⇒ + case ClusterMetricsChanged(clusterMetrics) => + clusterMetrics.filter(_.address == selfAddress) foreach { nodeMetrics => logHeap(nodeMetrics) logCpu(nodeMetrics) } - case state: CurrentClusterState ⇒ // Ignore. + case state: CurrentClusterState => // Ignore. } def logHeap(nodeMetrics: NodeMetrics): Unit = nodeMetrics match { - case HeapMemory(address, timestamp, used, committed, max) ⇒ + case HeapMemory(address, timestamp, used, committed, max) => log.info("Used heap: {} MB", used.doubleValue / 1024 / 1024) - case _ ⇒ // No heap info. + case _ => // No heap info. } def logCpu(nodeMetrics: NodeMetrics): Unit = nodeMetrics match { - case Cpu(address, timestamp, Some(systemLoadAverage), cpuCombined, cpuStolen, processors) ⇒ + case Cpu(address, timestamp, Some(systemLoadAverage), cpuCombined, cpuStolen, processors) => log.info("Load: {} ({} processors)", systemLoadAverage, processors) - case _ ⇒ // No cpu info. + case _ => // No cpu info. } } //#metrics-listener diff --git a/akka-docs/src/test/scala/docs/cluster/SimpleClusterListener.scala b/akka-docs/src/test/scala/docs/cluster/SimpleClusterListener.scala index d191e1fa9b..8b1470cb85 100644 --- a/akka-docs/src/test/scala/docs/cluster/SimpleClusterListener.scala +++ b/akka-docs/src/test/scala/docs/cluster/SimpleClusterListener.scala @@ -23,14 +23,14 @@ class SimpleClusterListener extends Actor with ActorLogging { override def postStop(): Unit = cluster.unsubscribe(self) def receive = { - case MemberUp(member) ⇒ + case MemberUp(member) => log.info("Member is Up: {}", member.address) - case UnreachableMember(member) ⇒ + case UnreachableMember(member) => log.info("Member detected as unreachable: {}", member) - case MemberRemoved(member, previousStatus) ⇒ + case MemberRemoved(member, previousStatus) => log.info( "Member is Removed: {} after {}", member.address, previousStatus) - case _: MemberEvent ⇒ // ignore + case _: MemberEvent => // ignore } } diff --git a/akka-docs/src/test/scala/docs/cluster/SimpleClusterListener2.scala b/akka-docs/src/test/scala/docs/cluster/SimpleClusterListener2.scala index 4d76f9cf72..9dde5ec65c 100644 --- a/akka-docs/src/test/scala/docs/cluster/SimpleClusterListener2.scala +++ b/akka-docs/src/test/scala/docs/cluster/SimpleClusterListener2.scala @@ -33,16 +33,16 @@ class SimpleClusterListener2 extends Actor with ActorLogging { override def postStop(): Unit = cluster.unsubscribe(self) def receive = { - case state: CurrentClusterState ⇒ + case state: CurrentClusterState => log.info("Current members: {}", state.members.mkString(", ")) - case MemberUp(member) ⇒ + case MemberUp(member) => log.info("Member is Up: {}", member.address) - case UnreachableMember(member) ⇒ + case UnreachableMember(member) => log.info("Member detected as unreachable: {}", member) - case MemberRemoved(member, previousStatus) ⇒ + case MemberRemoved(member, previousStatus) => log.info( "Member is Removed: {} after {}", member.address, previousStatus) - case _: MemberEvent ⇒ // ignore + case _: MemberEvent => // ignore } } diff --git a/akka-docs/src/test/scala/docs/cluster/TransformationBackend.scala b/akka-docs/src/test/scala/docs/cluster/TransformationBackend.scala index de2aa1bb50..d7cd697e85 100644 --- a/akka-docs/src/test/scala/docs/cluster/TransformationBackend.scala +++ b/akka-docs/src/test/scala/docs/cluster/TransformationBackend.scala @@ -29,10 +29,10 @@ class TransformationBackend extends Actor { override def postStop(): Unit = cluster.unsubscribe(self) def receive = { - case TransformationJob(text) ⇒ sender() ! TransformationResult(text.toUpperCase) - case state: CurrentClusterState ⇒ + case TransformationJob(text) => sender() ! TransformationResult(text.toUpperCase) + case state: CurrentClusterState => state.members.filter(_.status == MemberStatus.Up) foreach register - case MemberUp(m) ⇒ register(m) + case MemberUp(m) => register(m) } def register(member: Member): Unit = diff --git a/akka-docs/src/test/scala/docs/cluster/TransformationFrontend.scala b/akka-docs/src/test/scala/docs/cluster/TransformationFrontend.scala index c3362b08ae..381dd977a0 100644 --- a/akka-docs/src/test/scala/docs/cluster/TransformationFrontend.scala +++ b/akka-docs/src/test/scala/docs/cluster/TransformationFrontend.scala @@ -24,18 +24,18 @@ class TransformationFrontend extends Actor { var jobCounter = 0 def receive = { - case job: TransformationJob if backends.isEmpty ⇒ + case job: TransformationJob if backends.isEmpty => sender() ! JobFailed("Service unavailable, try again later", job) - case job: TransformationJob ⇒ + case job: TransformationJob => jobCounter += 1 backends(jobCounter % backends.size) forward job - case BackendRegistration if !backends.contains(sender()) ⇒ + case BackendRegistration if !backends.contains(sender()) => context watch sender() backends = backends :+ sender() - case Terminated(a) ⇒ + case Terminated(a) => backends = backends.filterNot(_ == a) } } @@ -57,7 +57,7 @@ object TransformationFrontend { system.scheduler.schedule(2.seconds, 2.seconds) { implicit val timeout = Timeout(5 seconds) (frontend ? TransformationJob("hello-" + counter.incrementAndGet())) - .foreach { result ⇒ println(result) } + .foreach { result => println(result) } } } diff --git a/akka-docs/src/test/scala/docs/cluster/singleton/ClusterSingletonSupervision.scala b/akka-docs/src/test/scala/docs/cluster/singleton/ClusterSingletonSupervision.scala index 9e1f84e0d2..964b7e0f14 100644 --- a/akka-docs/src/test/scala/docs/cluster/singleton/ClusterSingletonSupervision.scala +++ b/akka-docs/src/test/scala/docs/cluster/singleton/ClusterSingletonSupervision.scala @@ -10,7 +10,7 @@ class SupervisorActor(childProps: Props, override val supervisorStrategy: Superv val child = context.actorOf(childProps, "supervised-child") def receive = { - case msg ⇒ child forward msg + case msg => child forward msg } } //#singleton-supervisor-actor diff --git a/akka-docs/src/test/scala/docs/ddata/DistributedDataDocSpec.scala b/akka-docs/src/test/scala/docs/ddata/DistributedDataDocSpec.scala index 4440a2e0ff..d134c4ed87 100644 --- a/akka-docs/src/test/scala/docs/ddata/DistributedDataDocSpec.scala +++ b/akka-docs/src/test/scala/docs/ddata/DistributedDataDocSpec.scala @@ -73,7 +73,7 @@ object DistributedDataDocSpec { replicator ! Subscribe(DataKey, self) def receive = { - case Tick ⇒ + case Tick => val s = ThreadLocalRandom.current().nextInt(97, 123).toChar.toString if (ThreadLocalRandom.current().nextBoolean()) { // add @@ -85,9 +85,9 @@ object DistributedDataDocSpec { replicator ! Update(DataKey, ORSet.empty[String], WriteLocal)(_ remove s) } - case _: UpdateResponse[_] ⇒ // ignore + case _: UpdateResponse[_] => // ignore - case c @ Changed(DataKey) ⇒ + case c @ Changed(DataKey) => val data = c.get(DataKey) log.info("Current elements: {}", data.elements) } @@ -129,19 +129,19 @@ class DistributedDataDocSpec extends AkkaSpec(DistributedDataDocSpec.config) { probe.expectMsgType[UpdateResponse[_]] match { //#update-response1 - case UpdateSuccess(Counter1Key, req) ⇒ // ok + case UpdateSuccess(Counter1Key, req) => // ok //#update-response1 - case unexpected ⇒ fail("Unexpected response: " + unexpected) + case unexpected => fail("Unexpected response: " + unexpected) } probe.expectMsgType[UpdateResponse[_]] match { //#update-response2 - case UpdateSuccess(Set1Key, req) ⇒ // ok - case UpdateTimeout(Set1Key, req) ⇒ + case UpdateSuccess(Set1Key, req) => // ok + case UpdateTimeout(Set1Key, req) => // write to 3 nodes failed within 1.second //#update-response2 - case UpdateSuccess(Set2Key, None) ⇒ - case unexpected ⇒ fail("Unexpected response: " + unexpected) + case UpdateSuccess(Set2Key, None) => + case unexpected => fail("Unexpected response: " + unexpected) } } @@ -158,14 +158,14 @@ class DistributedDataDocSpec extends AkkaSpec(DistributedDataDocSpec.config) { val Counter1Key = PNCounterKey("counter1") def receive: Receive = { - case "increment" ⇒ + case "increment" => // incoming command to increase the counter val upd = Update(Counter1Key, PNCounter(), writeTwo, request = Some(sender()))(_ :+ 1) replicator ! upd - case UpdateSuccess(Counter1Key, Some(replyTo: ActorRef)) ⇒ + case UpdateSuccess(Counter1Key, Some(replyTo: ActorRef)) => replyTo ! "ack" - case UpdateTimeout(Counter1Key, Some(replyTo: ActorRef)) ⇒ + case UpdateTimeout(Counter1Key, Some(replyTo: ActorRef)) => replyTo ! "nack" } //#update-request-context @@ -196,24 +196,24 @@ class DistributedDataDocSpec extends AkkaSpec(DistributedDataDocSpec.config) { probe.expectMsgType[GetResponse[_]] match { //#get-response1 - case g @ GetSuccess(Counter1Key, req) ⇒ + case g @ GetSuccess(Counter1Key, req) => val value = g.get(Counter1Key).value - case NotFound(Counter1Key, req) ⇒ // key counter1 does not exist + case NotFound(Counter1Key, req) => // key counter1 does not exist //#get-response1 - case unexpected ⇒ fail("Unexpected response: " + unexpected) + case unexpected => fail("Unexpected response: " + unexpected) } probe.expectMsgType[GetResponse[_]] match { //#get-response2 - case g @ GetSuccess(Set1Key, req) ⇒ + case g @ GetSuccess(Set1Key, req) => val elements = g.get(Set1Key).elements - case GetFailure(Set1Key, req) ⇒ + case GetFailure(Set1Key, req) => // read from 3 nodes failed within 1.second - case NotFound(Set1Key, req) ⇒ // key set1 does not exist + case NotFound(Set1Key, req) => // key set1 does not exist //#get-response2 - case g @ GetSuccess(Set2Key, None) ⇒ + case g @ GetSuccess(Set2Key, None) => val elements = g.get(Set2Key).elements - case unexpected ⇒ fail("Unexpected response: " + unexpected) + case unexpected => fail("Unexpected response: " + unexpected) } } @@ -230,16 +230,16 @@ class DistributedDataDocSpec extends AkkaSpec(DistributedDataDocSpec.config) { val Counter1Key = PNCounterKey("counter1") def receive: Receive = { - case "get-count" ⇒ + case "get-count" => // incoming request to retrieve current value of the counter replicator ! Get(Counter1Key, readTwo, request = Some(sender())) - case g @ GetSuccess(Counter1Key, Some(replyTo: ActorRef)) ⇒ + case g @ GetSuccess(Counter1Key, Some(replyTo: ActorRef)) => val value = g.get(Counter1Key).value.longValue replyTo ! value - case GetFailure(Counter1Key, Some(replyTo: ActorRef)) ⇒ + case GetFailure(Counter1Key, Some(replyTo: ActorRef)) => replyTo ! -1L - case NotFound(Counter1Key, Some(replyTo: ActorRef)) ⇒ + case NotFound(Counter1Key, Some(replyTo: ActorRef)) => replyTo ! 0L } //#get-request-context @@ -259,9 +259,9 @@ class DistributedDataDocSpec extends AkkaSpec(DistributedDataDocSpec.config) { var currentValue = BigInt(0) def receive: Receive = { - case c @ Changed(Counter1Key) ⇒ + case c @ Changed(Counter1Key) => currentValue = c.get(Counter1Key).value - case "get-count" ⇒ + case "get-count" => // incoming request to retrieve current value of the counter sender() ! currentValue } @@ -306,7 +306,7 @@ class DistributedDataDocSpec extends AkkaSpec(DistributedDataDocSpec.config) { val m2 = m1.decrement(node, "a", 2) val m3 = m2.increment(node, "b", 1) println(m3.get("a")) // 5 - m3.entries.foreach { case (key, value) ⇒ println(s"$key -> $value") } + m3.entries.foreach { case (key, value) => println(s"$key -> $value") } //#pncountermap } diff --git a/akka-docs/src/test/scala/docs/ddata/ShoppingCart.scala b/akka-docs/src/test/scala/docs/ddata/ShoppingCart.scala index 9bf9b0f8cf..d73af75547 100644 --- a/akka-docs/src/test/scala/docs/ddata/ShoppingCart.scala +++ b/akka-docs/src/test/scala/docs/ddata/ShoppingCart.scala @@ -49,18 +49,18 @@ class ShoppingCart(userId: String) extends Actor { //#get-cart def receiveGetCart: Receive = { - case GetCart ⇒ + case GetCart => replicator ! Get(DataKey, readMajority, Some(sender())) - case g @ GetSuccess(DataKey, Some(replyTo: ActorRef)) ⇒ + case g @ GetSuccess(DataKey, Some(replyTo: ActorRef)) => val data = g.get(DataKey) val cart = Cart(data.entries.values.toSet) replyTo ! cart - case NotFound(DataKey, Some(replyTo: ActorRef)) ⇒ + case NotFound(DataKey, Some(replyTo: ActorRef)) => replyTo ! Cart(Set.empty) - case GetFailure(DataKey, Some(replyTo: ActorRef)) ⇒ + case GetFailure(DataKey, Some(replyTo: ActorRef)) => // ReadMajority failure, try again with local read replicator ! Get(DataKey, ReadLocal, Some(replyTo)) } @@ -68,9 +68,9 @@ class ShoppingCart(userId: String) extends Actor { //#add-item def receiveAddItem: Receive = { - case cmd @ AddItem(item) ⇒ + case cmd @ AddItem(item) => val update = Update(DataKey, LWWMap.empty[String, LineItem], writeMajority, Some(cmd)) { - cart ⇒ updateCart(cart, item) + cart => updateCart(cart, item) } replicator ! update } @@ -78,38 +78,38 @@ class ShoppingCart(userId: String) extends Actor { def updateCart(data: LWWMap[String, LineItem], item: LineItem): LWWMap[String, LineItem] = data.get(item.productId) match { - case Some(LineItem(_, _, existingQuantity)) ⇒ + case Some(LineItem(_, _, existingQuantity)) => data :+ (item.productId -> item.copy(quantity = existingQuantity + item.quantity)) - case None ⇒ data :+ (item.productId -> item) + case None => data :+ (item.productId -> item) } //#remove-item def receiveRemoveItem: Receive = { - case cmd @ RemoveItem(productId) ⇒ + case cmd @ RemoveItem(productId) => // Try to fetch latest from a majority of nodes first, since ORMap // remove must have seen the item to be able to remove it. replicator ! Get(DataKey, readMajority, Some(cmd)) - case GetSuccess(DataKey, Some(RemoveItem(productId))) ⇒ + case GetSuccess(DataKey, Some(RemoveItem(productId))) => replicator ! Update(DataKey, LWWMap(), writeMajority, None) { _.remove(node, productId) } - case GetFailure(DataKey, Some(RemoveItem(productId))) ⇒ + case GetFailure(DataKey, Some(RemoveItem(productId))) => // ReadMajority failed, fall back to best effort local value replicator ! Update(DataKey, LWWMap(), writeMajority, None) { _.remove(node, productId) } - case NotFound(DataKey, Some(RemoveItem(productId))) ⇒ + case NotFound(DataKey, Some(RemoveItem(productId))) => // nothing to remove } //#remove-item def receiveOther: Receive = { - case _: UpdateSuccess[_] | _: UpdateTimeout[_] ⇒ + case _: UpdateSuccess[_] | _: UpdateTimeout[_] => // UpdateTimeout, will eventually be replicated - case e: UpdateFailure[_] ⇒ throw new IllegalStateException("Unexpected failure: " + e) + case e: UpdateFailure[_] => throw new IllegalStateException("Unexpected failure: " + e) } } diff --git a/akka-docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer.scala b/akka-docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer.scala index c3622c5650..a7fb8c8757 100644 --- a/akka-docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer.scala +++ b/akka-docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer.scala @@ -23,8 +23,8 @@ class TwoPhaseSetSerializer(val system: ExtendedActorSystem) override def identifier = 99999 override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: TwoPhaseSet ⇒ twoPhaseSetToProto(m).toByteArray - case _ ⇒ throw new IllegalArgumentException( + case m: TwoPhaseSet => twoPhaseSetToProto(m).toByteArray + case _ => throw new IllegalArgumentException( s"Can't serialize object of type ${obj.getClass}") } @@ -54,8 +54,8 @@ class TwoPhaseSetSerializer(val system: ExtendedActorSystem) val msg = TwoPhaseSetMessages.TwoPhaseSet.parseFrom(bytes) val addsSet = msg.getAddsList.iterator.asScala.toSet val removalsSet = msg.getRemovalsList.iterator.asScala.toSet - val adds = addsSet.foldLeft(GSet.empty[String])((acc, el) ⇒ acc.add(el)) - val removals = removalsSet.foldLeft(GSet.empty[String])((acc, el) ⇒ acc.add(el)) + val adds = addsSet.foldLeft(GSet.empty[String])((acc, el) => acc.add(el)) + val removals = removalsSet.foldLeft(GSet.empty[String])((acc, el) => acc.add(el)) // GSet will accumulate deltas when adding elements, // but those are not of interest in the result of the deserialization TwoPhaseSet(adds.resetDelta, removals.resetDelta) @@ -67,8 +67,8 @@ class TwoPhaseSetSerializerWithCompression(system: ExtendedActorSystem) extends TwoPhaseSetSerializer(system) { //#compression override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: TwoPhaseSet ⇒ compress(twoPhaseSetToProto(m)) - case _ ⇒ throw new IllegalArgumentException( + case m: TwoPhaseSet => compress(twoPhaseSetToProto(m)) + case _ => throw new IllegalArgumentException( s"Can't serialize object of type ${obj.getClass}") } diff --git a/akka-docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer2.scala b/akka-docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer2.scala index cce2be2ef9..202d1e0f3b 100644 --- a/akka-docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer2.scala +++ b/akka-docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer2.scala @@ -23,8 +23,8 @@ class TwoPhaseSetSerializer2(val system: ExtendedActorSystem) val replicatedDataSerializer = new ReplicatedDataSerializer(system) override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case m: TwoPhaseSet ⇒ twoPhaseSetToProto(m).toByteArray - case _ ⇒ throw new IllegalArgumentException( + case m: TwoPhaseSet => twoPhaseSetToProto(m).toByteArray + case _ => throw new IllegalArgumentException( s"Can't serialize object of type ${obj.getClass}") } diff --git a/akka-docs/src/test/scala/docs/dispatcher/DispatcherDocSpec.scala b/akka-docs/src/test/scala/docs/dispatcher/DispatcherDocSpec.scala index 83ebdf7c00..dc91edd2d8 100644 --- a/akka-docs/src/test/scala/docs/dispatcher/DispatcherDocSpec.scala +++ b/akka-docs/src/test/scala/docs/dispatcher/DispatcherDocSpec.scala @@ -229,16 +229,16 @@ object DispatcherDocSpec { // Create a new PriorityGenerator, lower prio means more important PriorityGenerator { // 'highpriority messages should be treated first if possible - case 'highpriority ⇒ 0 + case 'highpriority => 0 // 'lowpriority messages should be treated last if possible - case 'lowpriority ⇒ 2 + case 'lowpriority => 2 // PoisonPill when no other left - case PoisonPill ⇒ 3 + case PoisonPill => 3 // We default to 1, which is in between high and low - case otherwise ⇒ 1 + case otherwise => 1 }) //#prio-mailbox @@ -250,7 +250,7 @@ object DispatcherDocSpec { class MyActor extends Actor { def receive = { - case x ⇒ + case x => } } @@ -267,7 +267,7 @@ object DispatcherDocSpec { with RequiresMessageQueue[MyUnboundedMessageQueueSemantics] { //#require-mailbox-on-actor def receive = { - case _ ⇒ + case _ => } //#require-mailbox-on-actor // ... @@ -370,7 +370,7 @@ class DispatcherDocSpec extends AkkaSpec(DispatcherDocSpec.config) { self ! PoisonPill def receive = { - case x ⇒ log.info(x.toString) + case x => log.info(x.toString) } } val a = system.actorOf(Props(classOf[Logger], this).withDispatcher( @@ -389,7 +389,7 @@ class DispatcherDocSpec extends AkkaSpec(DispatcherDocSpec.config) { //#prio-dispatcher watch(a) - expectMsgPF() { case Terminated(`a`) ⇒ () } + expectMsgPF() { case Terminated(`a`) => () } } } @@ -407,7 +407,7 @@ class DispatcherDocSpec extends AkkaSpec(DispatcherDocSpec.config) { self ! PoisonPill def receive = { - case x ⇒ log.info(x.toString) + case x => log.info(x.toString) } } val a = system.actorOf(Props(classOf[Logger], this).withDispatcher( @@ -422,7 +422,7 @@ class DispatcherDocSpec extends AkkaSpec(DispatcherDocSpec.config) { //#control-aware-dispatcher watch(a) - expectMsgPF() { case Terminated(`a`) ⇒ () } + expectMsgPF() { case Terminated(`a`) => () } } } diff --git a/akka-docs/src/test/scala/docs/event/LoggingDocSpec.scala b/akka-docs/src/test/scala/docs/event/LoggingDocSpec.scala index 1291a6ed6c..4187690d3b 100644 --- a/akka-docs/src/test/scala/docs/event/LoggingDocSpec.scala +++ b/akka-docs/src/test/scala/docs/event/LoggingDocSpec.scala @@ -22,8 +22,8 @@ object LoggingDocSpec { reason.getMessage, message.getOrElse("")) } def receive = { - case "test" ⇒ log.info("Received test") - case x ⇒ log.warning("Received unknown message: {}", x) + case "test" => log.info("Received test") + case x => log.warning("Received unknown message: {}", x) } } //#my-actor @@ -34,7 +34,7 @@ object LoggingDocSpec { val log = Logging(this) def receive = { - case _ ⇒ { + case _ => { //#mdc val mdc = Map("requestId" -> 1234, "visitorId" -> 5678) log.mdc(mdc) @@ -60,14 +60,14 @@ object LoggingDocSpec { reqId += 1 val always = Map("requestId" -> reqId) val perMessage = currentMessage match { - case r: Req ⇒ Map("visitorId" -> r.visitorId) - case _ ⇒ Map() + case r: Req => Map("visitorId" -> r.visitorId) + case _ => Map() } always ++ perMessage } def receive: Receive = { - case r: Req ⇒ { + case r: Req => { log.info(s"Starting new request: ${r.work}") } } @@ -85,11 +85,11 @@ object LoggingDocSpec { class MyEventListener extends Actor { def receive = { - case InitializeLogger(_) ⇒ sender() ! LoggerInitialized - case Error(cause, logSource, logClass, message) ⇒ // ... - case Warning(logSource, logClass, message) ⇒ // ... - case Info(logSource, logClass, message) ⇒ // ... - case Debug(logSource, logClass, message) ⇒ // ... + case InitializeLogger(_) => sender() ! LoggerInitialized + case Error(cause, logSource, logClass, message) => // ... + case Warning(logSource, logClass, message) => // ... + case Info(logSource, logClass, message) => // ... + case Debug(logSource, logClass, message) => // ... } } //#my-event-listener @@ -121,7 +121,7 @@ object LoggingDocSpec { class DeadLetterListener extends Actor { def receive = { - case d: DeadLetter ⇒ println(d) + case d: DeadLetter => println(d) } } //#deadletters @@ -133,8 +133,8 @@ object LoggingDocSpec { class Listener extends Actor { def receive = { - case m: Jazz ⇒ println(s"${self.path.name} is listening to: ${m.artist}") - case m: Electronic ⇒ println(s"${self.path.name} is listening to: ${m.artist}") + case m: Jazz => println(s"${self.path.name} is listening to: ${m.artist}") + case m: Electronic => println(s"${self.path.name} is listening to: ${m.artist}") } } //#superclass-subscription-eventstream diff --git a/akka-docs/src/test/scala/docs/extension/ExtensionDocSpec.scala b/akka-docs/src/test/scala/docs/extension/ExtensionDocSpec.scala index 62c4d57c94..5381c0a5cc 100644 --- a/akka-docs/src/test/scala/docs/extension/ExtensionDocSpec.scala +++ b/akka-docs/src/test/scala/docs/extension/ExtensionDocSpec.scala @@ -61,7 +61,7 @@ object ExtensionDocSpec { class MyActor extends Actor { def receive = { - case someMessage ⇒ + case someMessage => CountExtension(context.system).increment() } } @@ -69,12 +69,12 @@ object ExtensionDocSpec { //#extension-usage-actor-trait - trait Counting { self: Actor ⇒ + trait Counting { self: Actor => def increment() = CountExtension(context.system).increment() } class MyCounterActor extends Actor with Counting { def receive = { - case someMessage ⇒ increment() + case someMessage => increment() } } //#extension-usage-actor-trait diff --git a/akka-docs/src/test/scala/docs/extension/SettingsExtensionDocSpec.scala b/akka-docs/src/test/scala/docs/extension/SettingsExtensionDocSpec.scala index cb7377ccc3..a9f329f9a3 100644 --- a/akka-docs/src/test/scala/docs/extension/SettingsExtensionDocSpec.scala +++ b/akka-docs/src/test/scala/docs/extension/SettingsExtensionDocSpec.scala @@ -67,7 +67,7 @@ object SettingsExtensionDocSpec { //#extension-usage-actor def receive = { - case someMessage ⇒ + case someMessage => } def connect(dbUri: String, circuitBreakerTimeout: Duration) = { diff --git a/akka-docs/src/test/scala/docs/faq/Faq.scala b/akka-docs/src/test/scala/docs/faq/Faq.scala index 8af4b5ef49..4e95a26333 100644 --- a/akka-docs/src/test/scala/docs/faq/Faq.scala +++ b/akka-docs/src/test/scala/docs/faq/Faq.scala @@ -21,12 +21,12 @@ object MyActor { class MyActor extends Actor { import MyActor._ def receive = { - case message: Message ⇒ message match { - case BarMessage(bar) ⇒ sender() ! BazMessage("Got " + bar) + case message: Message => message match { + case BarMessage(bar) => sender() ! BazMessage("Got " + bar) // warning here: // "match may not be exhaustive. It would fail on the following input: FooMessage(_)" //#exhaustiveness-check - case FooMessage(_) ⇒ // avoid the warning in our build logs + case FooMessage(_) => // avoid the warning in our build logs //#exhaustiveness-check } } diff --git a/akka-docs/src/test/scala/docs/future/FutureDocSpec.scala b/akka-docs/src/test/scala/docs/future/FutureDocSpec.scala index 0153e1c12f..724b6a8180 100644 --- a/akka-docs/src/test/scala/docs/future/FutureDocSpec.scala +++ b/akka-docs/src/test/scala/docs/future/FutureDocSpec.scala @@ -18,9 +18,9 @@ object FutureDocSpec { class MyActor extends Actor { def receive = { - case x: String ⇒ sender() ! x.toUpperCase - case x: Int if x < 0 ⇒ sender() ! Status.Failure(new ArithmeticException("Negative values not supported")) - case x: Int ⇒ sender() ! x + case x: String => sender() ! x.toUpperCase + case x: Int if x < 0 => sender() ! Status.Failure(new ArithmeticException("Negative values not supported")) + case x: Int => sender() ! x } } @@ -29,7 +29,7 @@ object FutureDocSpec { class OddActor extends Actor { var n = 1 def receive = { - case GetNext ⇒ + case GetNext => sender() ! n n += 2 } @@ -44,7 +44,7 @@ object FutureDocSpec { implicit val timeout: Timeout = 5.seconds def receive = { - case _ ⇒ + case _ => val future = target ? "some message" future pipeTo sender() // use the pipe pattern } @@ -64,7 +64,7 @@ object FutureDocSpec { var internalData: UserData = UserData("initial data") def receive = { - case Get ⇒ + case Get => sender() ! internalData } } @@ -85,7 +85,7 @@ object FutureDocSpec { implicit val ec: ExecutionContext = context.dispatcher def receive = { - case Get ⇒ + case Get => // user's historical activities are retrieved // via the separate repository repository.queryHistoricalActivities(userId) pipeTo sender() @@ -109,9 +109,9 @@ object FutureDocSpec { implicit val timeout = Timeout(5 seconds) def receive = { - case GetUserData ⇒ + case GetUserData => (userData ? UserDataActor.Get) pipeTo sender() - case GetUserActivities ⇒ + case GetUserActivities => (userActivities ? UserActivityActor.Get) pipeTo sender() } } @@ -131,7 +131,7 @@ class FutureDocSpec extends AkkaSpec { import FutureDocSpec._ import system.dispatcher - val println: PartialFunction[Any, Unit] = { case _ ⇒ } + val println: PartialFunction[Any, Unit] = { case _ => } "demonstrate usage custom ExecutionContext" in { val yourExecutorServiceGoesHere = java.util.concurrent.Executors.newSingleThreadExecutor() @@ -198,7 +198,7 @@ class FutureDocSpec extends AkkaSpec { val f1 = Future { "Hello" + "World" } - val f2 = f1 map { x ⇒ + val f2 = f1 map { x => x.length } f2 foreach println @@ -214,8 +214,8 @@ class FutureDocSpec extends AkkaSpec { "Hello" + "World" } val f2 = Future.successful(3) - val f3 = f1 map { x ⇒ - f2 map { y ⇒ + val f3 = f1 map { x => + f2 map { y => x.length * y } } @@ -230,8 +230,8 @@ class FutureDocSpec extends AkkaSpec { "Hello" + "World" } val f2 = Future.successful(3) - val f3 = f1 flatMap { x ⇒ - f2 map { y ⇒ + val f3 = f1 flatMap { x => + f2 map { y => x.length * y } } @@ -250,7 +250,7 @@ class FutureDocSpec extends AkkaSpec { val failedFilter = future1.filter(_ % 2 == 1).recover { // When filter fails, it will have a java.util.NoSuchElementException - case m: NoSuchElementException ⇒ 0 + case m: NoSuchElementException => 0 } failedFilter foreach println @@ -264,9 +264,9 @@ class FutureDocSpec extends AkkaSpec { "demonstrate usage of for comprehension" in { //#for-comprehension val f = for { - a ← Future(10 / 2) // 10 / 2 = 5 - b ← Future(a + 1) // 5 + 1 = 6 - c ← Future(a - 1) // 5 - 1 = 4 + a <- Future(10 / 2) // 10 / 2 = 5 + b <- Future(a + 1) // 5 + 1 = 6 + c <- Future(a - 1) // 5 - 1 = 4 if c > 3 // Future.filter } yield b * c // 6 * 4 = 24 @@ -318,9 +318,9 @@ class FutureDocSpec extends AkkaSpec { val f2 = ask(actor2, msg2) val f3 = for { - a ← f1.mapTo[Int] - b ← f2.mapTo[Int] - c ← ask(actor3, (a + b)).mapTo[Int] + a <- f1.mapTo[Int] + b <- f2.mapTo[Int] + c <- ask(actor3, (a + b)).mapTo[Int] } yield c f3 foreach println @@ -348,7 +348,7 @@ class FutureDocSpec extends AkkaSpec { "demonstrate usage of sequence" in { //#sequence - val futureList = Future.sequence((1 to 100).toList.map(x ⇒ Future(x * 2 - 1))) + val futureList = Future.sequence((1 to 100).toList.map(x => Future(x * 2 - 1))) val oddSum = futureList.map(_.sum) oddSum foreach println //#sequence @@ -357,7 +357,7 @@ class FutureDocSpec extends AkkaSpec { "demonstrate usage of traverse" in { //#traverse - val futureList = Future.traverse((1 to 100).toList)(x ⇒ Future(x * 2 - 1)) + val futureList = Future.traverse((1 to 100).toList)(x => Future(x * 2 - 1)) val oddSum = futureList.map(_.sum) oddSum foreach println //#traverse @@ -367,7 +367,7 @@ class FutureDocSpec extends AkkaSpec { "demonstrate usage of fold" in { //#fold // Create a sequence of Futures - val futures = for (i ← 1 to 1000) yield Future(i * 2) + val futures = for (i <- 1 to 1000) yield Future(i * 2) val futureSum = Future.fold(futures)(0)(_ + _) futureSum foreach println //#fold @@ -377,7 +377,7 @@ class FutureDocSpec extends AkkaSpec { "demonstrate usage of reduce" in { //#reduce // Create a sequence of Futures - val futures = for (i ← 1 to 1000) yield Future(i * 2) + val futures = for (i <- 1 to 1000) yield Future(i * 2) val futureSum = Future.reduce(futures)(_ + _) futureSum foreach println //#reduce @@ -390,7 +390,7 @@ class FutureDocSpec extends AkkaSpec { val msg1 = -1 //#recover val future = akka.pattern.ask(actor, msg1) recover { - case e: ArithmeticException ⇒ 0 + case e: ArithmeticException => 0 } future foreach println //#recover @@ -403,8 +403,8 @@ class FutureDocSpec extends AkkaSpec { val msg1 = -1 //#try-recover val future = akka.pattern.ask(actor, msg1) recoverWith { - case e: ArithmeticException ⇒ Future.successful(0) - case foo: IllegalArgumentException ⇒ + case e: ArithmeticException => Future.successful(0) + case foo: IllegalArgumentException => Future.failed[Int](new IllegalStateException("All br0ken!")) } future foreach println @@ -416,7 +416,7 @@ class FutureDocSpec extends AkkaSpec { val future1 = Future { "foo" } val future2 = Future { "bar" } //#zip - val future3 = future1 zip future2 map { case (a, b) ⇒ a + " " + b } + val future3 = future1 zip future2 map { case (a, b) => a + " " + b } future3 foreach println //#zip Await.result(future3, 3 seconds) should be("foo bar") @@ -429,9 +429,9 @@ class FutureDocSpec extends AkkaSpec { def watchSomeTV(): Unit = () //#and-then val result = Future { loadPage(url) } andThen { - case Failure(exception) ⇒ log(exception) + case Failure(exception) => log(exception) } andThen { - case _ ⇒ watchSomeTV() + case _ => watchSomeTV() } result foreach println //#and-then @@ -455,8 +455,8 @@ class FutureDocSpec extends AkkaSpec { def doSomethingOnFailure(t: Throwable) = () //#onComplete future onComplete { - case Success(result) ⇒ doSomethingOnSuccess(result) - case Failure(failure) ⇒ doSomethingOnFailure(failure) + case Success(result) => doSomethingOnSuccess(result) + case Failure(failure) => doSomethingOnFailure(failure) } //#onComplete Await.result(future, 3 seconds) should be("foo") @@ -505,7 +505,7 @@ class FutureDocSpec extends AkkaSpec { } //Return a new future that will retry up to 10 times val retried = akka.pattern.retry( - () ⇒ attempt(), + () => attempt(), 10, 100 milliseconds) //#retry @@ -520,7 +520,7 @@ class FutureDocSpec extends AkkaSpec { val f = Future("hello") def receive = { //#receive-omitted - case _ ⇒ + case _ => //#receive-omitted } } diff --git a/akka-docs/src/test/scala/docs/io/EchoServer.scala b/akka-docs/src/test/scala/docs/io/EchoServer.scala index d42df88c6e..b126ca7c44 100644 --- a/akka-docs/src/test/scala/docs/io/EchoServer.scala +++ b/akka-docs/src/test/scala/docs/io/EchoServer.scala @@ -53,15 +53,15 @@ class EchoManager(handlerClass: Class[_]) extends Actor with ActorLogging { override def postRestart(thr: Throwable): Unit = context stop self def receive = { - case Bound(localAddress) ⇒ + case Bound(localAddress) => log.info("listening on port {}", localAddress.getPort) - case CommandFailed(Bind(_, local, _, _, _)) ⇒ + case CommandFailed(Bind(_, local, _, _, _)) => log.warning(s"cannot bind to [$local]") context stop self //#echo-manager - case Connected(remote, local) ⇒ + case Connected(remote, local) => log.info("received connection from {}", remote) val handler = context.actorOf(Props(handlerClass, sender(), remote)) sender() ! Register(handler, keepOpenOnPeerClosed = true) @@ -92,18 +92,18 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress) //#writing def writing: Receive = { - case Received(data) ⇒ + case Received(data) => connection ! Write(data, Ack(currentOffset)) buffer(data) - case Ack(ack) ⇒ + case Ack(ack) => acknowledge(ack) - case CommandFailed(Write(_, Ack(ack))) ⇒ + case CommandFailed(Write(_, Ack(ack))) => connection ! ResumeWriting context become buffering(ack) - case PeerClosed ⇒ + case PeerClosed => if (storage.isEmpty) context stop self else context become closing } @@ -115,11 +115,11 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress) var peerClosed = false { - case Received(data) ⇒ buffer(data) - case WritingResumed ⇒ writeFirst() - case PeerClosed ⇒ peerClosed = true - case Ack(ack) if ack < nack ⇒ acknowledge(ack) - case Ack(ack) ⇒ + case Received(data) => buffer(data) + case WritingResumed => writeFirst() + case PeerClosed => peerClosed = true + case Ack(ack) if ack < nack => acknowledge(ack) + case Ack(ack) => acknowledge(ack) if (storage.nonEmpty) { if (toAck > 0) { @@ -139,19 +139,19 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress) //#closing def closing: Receive = { - case CommandFailed(_: Write) ⇒ + case CommandFailed(_: Write) => connection ! ResumeWriting context.become({ - case WritingResumed ⇒ + case WritingResumed => writeAll() context.unbecome() - case ack: Int ⇒ acknowledge(ack) + case ack: Int => acknowledge(ack) }, discardOld = false) - case Ack(ack) ⇒ + case Ack(ack) => acknowledge(ack) if (storage.isEmpty) context stop self } @@ -214,7 +214,7 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress) } private def writeAll(): Unit = { - for ((data, i) ← storage.zipWithIndex) { + for ((data, i) <- storage.zipWithIndex) { connection ! Write(data, Ack(storageOffset + i)) } } @@ -235,17 +235,17 @@ class SimpleEchoHandler(connection: ActorRef, remote: InetSocketAddress) case object Ack extends Event def receive = { - case Received(data) ⇒ + case Received(data) => buffer(data) connection ! Write(data, Ack) context.become({ - case Received(data) ⇒ buffer(data) - case Ack ⇒ acknowledge() - case PeerClosed ⇒ closing = true + case Received(data) => buffer(data) + case Ack => acknowledge() + case PeerClosed => closing = true }, discardOld = false) - case PeerClosed ⇒ context stop self + case PeerClosed => context stop self } //#storage-omitted diff --git a/akka-docs/src/test/scala/docs/io/IODocSpec.scala b/akka-docs/src/test/scala/docs/io/IODocSpec.scala index bf4c923703..b942c336b6 100644 --- a/akka-docs/src/test/scala/docs/io/IODocSpec.scala +++ b/akka-docs/src/test/scala/docs/io/IODocSpec.scala @@ -34,14 +34,14 @@ class Server extends Actor { IO(Tcp) ! Bind(self, new InetSocketAddress("localhost", 0)) def receive = { - case b @ Bound(localAddress) ⇒ + case b @ Bound(localAddress) => //#do-some-logging-or-setup context.parent ! b //#do-some-logging-or-setup - case CommandFailed(_: Bind) ⇒ context stop self + case CommandFailed(_: Bind) => context stop self - case c @ Connected(remote, local) ⇒ + case c @ Connected(remote, local) => //#server context.parent ! c //#server @@ -57,8 +57,8 @@ class Server extends Actor { class SimplisticHandler extends Actor { import Tcp._ def receive = { - case Received(data) ⇒ sender() ! Write(data) - case PeerClosed ⇒ context stop self + case Received(data) => sender() ! Write(data) + case PeerClosed => context stop self } } //#simplistic-handler @@ -77,25 +77,25 @@ class Client(remote: InetSocketAddress, listener: ActorRef) extends Actor { IO(Tcp) ! Connect(remote) def receive = { - case CommandFailed(_: Connect) ⇒ + case CommandFailed(_: Connect) => listener ! "connect failed" context stop self - case c @ Connected(remote, local) ⇒ + case c @ Connected(remote, local) => listener ! c val connection = sender() connection ! Register(self) context become { - case data: ByteString ⇒ + case data: ByteString => connection ! Write(data) - case CommandFailed(w: Write) ⇒ + case CommandFailed(w: Write) => // O/S buffer was full listener ! "write failed" - case Received(data) ⇒ + case Received(data) => listener ! data - case "close" ⇒ + case "close" => connection ! Close - case _: ConnectionClosed ⇒ + case _: ConnectionClosed => listener ! "connection closed" context stop self } @@ -108,7 +108,7 @@ class IODocSpec extends AkkaSpec { class Parent extends Actor { context.actorOf(Props[Server], "server") def receive = { - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } diff --git a/akka-docs/src/test/scala/docs/io/ReadBackPressure.scala b/akka-docs/src/test/scala/docs/io/ReadBackPressure.scala index d08407a71a..a996f55892 100644 --- a/akka-docs/src/test/scala/docs/io/ReadBackPressure.scala +++ b/akka-docs/src/test/scala/docs/io/ReadBackPressure.scala @@ -27,7 +27,7 @@ object PullReadingExample { def receive = { //#pull-accepting - case Bound(localAddress) ⇒ + case Bound(localAddress) => // Accept connections one by one sender() ! ResumeAccepting(batchSize = 1) context.become(listening(sender())) @@ -37,7 +37,7 @@ object PullReadingExample { //#pull-accepting-cont def listening(listener: ActorRef): Receive = { - case Connected(remote, local) ⇒ + case Connected(remote, local) => val handler = context.actorOf(Props(classOf[PullEcho], sender())) sender() ! Register(handler, keepOpenOnPeerClosed = true) listener ! ResumeAccepting(batchSize = 1) @@ -54,8 +54,8 @@ object PullReadingExample { override def preStart: Unit = connection ! ResumeReading def receive = { - case Received(data) ⇒ connection ! Write(data, Ack) - case Ack ⇒ connection ! ResumeReading + case Received(data) => connection ! Write(data, Ack) + case Ack => connection ! ResumeReading } //#pull-reading-echo } diff --git a/akka-docs/src/test/scala/docs/io/ScalaUdpMulticast.scala b/akka-docs/src/test/scala/docs/io/ScalaUdpMulticast.scala index b0f23bbcd2..4679b7e28a 100644 --- a/akka-docs/src/test/scala/docs/io/ScalaUdpMulticast.scala +++ b/akka-docs/src/test/scala/docs/io/ScalaUdpMulticast.scala @@ -38,10 +38,10 @@ class Listener(iface: String, group: String, port: Int, sink: ActorRef) extends //#bind def receive = { - case b @ Udp.Bound(to) ⇒ + case b @ Udp.Bound(to) => log.info("Bound to {}", to) sink ! (b) - case Udp.Received(data, remote) ⇒ + case Udp.Received(data, remote) => val msg = data.decodeString("utf-8") log.info("Received '{}' from {}", msg, remote) sink ! msg @@ -53,7 +53,7 @@ class Sender(iface: String, group: String, port: Int, msg: String) extends Actor IO(Udp) ! Udp.SimpleSender(List(Inet6ProtocolFamily())) def receive = { - case Udp.SimpleSenderReady ⇒ { + case Udp.SimpleSenderReady => { val remote = new InetSocketAddress(s"$group%$iface", port) log.info("Sending message to {}", remote) sender() ! Udp.Send(ByteString(msg), remote) diff --git a/akka-docs/src/test/scala/docs/io/ScalaUdpMulticastSpec.scala b/akka-docs/src/test/scala/docs/io/ScalaUdpMulticastSpec.scala index 76943a2acc..9bce625578 100644 --- a/akka-docs/src/test/scala/docs/io/ScalaUdpMulticastSpec.scala +++ b/akka-docs/src/test/scala/docs/io/ScalaUdpMulticastSpec.scala @@ -20,7 +20,7 @@ class ScalaUdpMulticastSpec extends TestKit(ActorSystem("ScalaUdpMulticastSpec") "listener" should { "send message back to sink" in { val ipv6ifaces = - NetworkInterface.getNetworkInterfaces.asScala.toSeq.filter(iface ⇒ + NetworkInterface.getNetworkInterfaces.asScala.toSeq.filter(iface => iface.supportsMulticast && iface.isUp && iface.getInetAddresses.asScala.exists(_.isInstanceOf[Inet6Address])) @@ -33,7 +33,7 @@ class ScalaUdpMulticastSpec extends TestKit(ActorSystem("ScalaUdpMulticastSpec") // on the platform (awsdl0 can't be used on OSX, docker[0-9] can't be used in a docker machine etc.) // therefore: try hard to find an interface that _does_ work, and only fail if there was any potentially // working interfaces but all failed - ipv6ifaces.exists { ipv6iface ⇒ + ipv6ifaces.exists { ipv6iface => // host assigned link local multicast address http://tools.ietf.org/html/rfc3307#section-4.3.2 // generate a random 32 bit multicast address with the high order bit set val randomAddress: String = (Random.nextInt().abs.toLong | (1L << 31)).toHexString.toUpperCase @@ -51,7 +51,7 @@ class ScalaUdpMulticastSpec extends TestKit(ActorSystem("ScalaUdpMulticastSpec") true } catch { - case _: AssertionError ⇒ + case _: AssertionError => system.log.info("Failed to run test on interface {}", ipv6iface.getDisplayName) false diff --git a/akka-docs/src/test/scala/docs/io/UdpDocSpec.scala b/akka-docs/src/test/scala/docs/io/UdpDocSpec.scala index 119c6cbe90..36adeb3100 100644 --- a/akka-docs/src/test/scala/docs/io/UdpDocSpec.scala +++ b/akka-docs/src/test/scala/docs/io/UdpDocSpec.scala @@ -25,7 +25,7 @@ object ScalaUdpDocSpec { IO(Udp) ! Udp.SimpleSender def receive = { - case Udp.SimpleSenderReady ⇒ + case Udp.SimpleSenderReady => context.become(ready(sender())) //#sender sender() ! Udp.Send(ByteString("hello"), remote) @@ -33,7 +33,7 @@ object ScalaUdpDocSpec { } def ready(send: ActorRef): Receive = { - case msg: String ⇒ + case msg: String => send ! Udp.Send(ByteString(msg), remote) //#sender if (msg == "world") send ! PoisonPill @@ -48,7 +48,7 @@ object ScalaUdpDocSpec { IO(Udp) ! Udp.Bind(self, new InetSocketAddress("localhost", 0)) def receive = { - case Udp.Bound(local) ⇒ + case Udp.Bound(local) => //#listener nextActor forward local //#listener @@ -56,15 +56,15 @@ object ScalaUdpDocSpec { } def ready(socket: ActorRef): Receive = { - case Udp.Received(data, remote) ⇒ + case Udp.Received(data, remote) => val processed = // parse data etc., e.g. using PipelineStage //#listener data.utf8String //#listener socket ! Udp.Send(data, remote) // example server echoes back nextActor ! processed - case Udp.Unbind ⇒ socket ! Udp.Unbind - case Udp.Unbound ⇒ context.stop(self) + case Udp.Unbind => socket ! Udp.Unbind + case Udp.Unbound => context.stop(self) } } //#listener @@ -75,7 +75,7 @@ object ScalaUdpDocSpec { IO(UdpConnected) ! UdpConnected.Connect(self, remote) def receive = { - case UdpConnected.Connected ⇒ + case UdpConnected.Connected => context.become(ready(sender())) //#connected sender() ! UdpConnected.Send(ByteString("hello")) @@ -83,17 +83,17 @@ object ScalaUdpDocSpec { } def ready(connection: ActorRef): Receive = { - case UdpConnected.Received(data) ⇒ + case UdpConnected.Received(data) => // process data, send it on, etc. //#connected if (data.utf8String == "hello") connection ! UdpConnected.Send(ByteString("world")) //#connected - case msg: String ⇒ + case msg: String => connection ! UdpConnected.Send(ByteString(msg)) - case UdpConnected.Disconnect ⇒ + case UdpConnected.Disconnect => connection ! UdpConnected.Disconnect - case UdpConnected.Disconnected ⇒ context.stop(self) + case UdpConnected.Disconnected => context.stop(self) } } //#connected diff --git a/akka-docs/src/test/scala/docs/pattern/BackoffSupervisorDocSpec.scala b/akka-docs/src/test/scala/docs/pattern/BackoffSupervisorDocSpec.scala index c2f1893bb3..6ce9f4a284 100644 --- a/akka-docs/src/test/scala/docs/pattern/BackoffSupervisorDocSpec.scala +++ b/akka-docs/src/test/scala/docs/pattern/BackoffSupervisorDocSpec.scala @@ -90,8 +90,8 @@ class BackoffSupervisorDocSpec { ).withAutoReset(10.seconds) // reset if the child does not throw any errors within 10 seconds .withSupervisorStrategy( OneForOneStrategy() { - case _: MyException ⇒ SupervisorStrategy.Restart - case _ ⇒ SupervisorStrategy.Escalate + case _: MyException => SupervisorStrategy.Restart + case _ => SupervisorStrategy.Escalate })) //#backoff-custom-fail diff --git a/akka-docs/src/test/scala/docs/persistence/PersistenceDocSpec.scala b/akka-docs/src/test/scala/docs/persistence/PersistenceDocSpec.scala index 5fe99ebdd9..2214e9410a 100644 --- a/akka-docs/src/test/scala/docs/persistence/PersistenceDocSpec.scala +++ b/akka-docs/src/test/scala/docs/persistence/PersistenceDocSpec.scala @@ -48,14 +48,14 @@ object PersistenceDocSpec { //#recovery-completed override def receiveRecover: Receive = { - case RecoveryCompleted ⇒ + case RecoveryCompleted => // perform init after recovery, before any other messages //... - case evt ⇒ //... + case evt => //... } override def receiveCommand: Receive = { - case msg ⇒ //... + case msg => //... } //#recovery-completed } @@ -84,10 +84,10 @@ object PersistenceDocSpec { //#persistence-id-override override def receiveRecover: Receive = { - case _ ⇒ + case _ => } override def receiveCommand: Receive = { - case _ ⇒ + case _ => } } } @@ -128,25 +128,25 @@ object PersistenceDocSpec { override def persistenceId: String = "persistence-id" override def receiveCommand: Receive = { - case s: String ⇒ persist(MsgSent(s))(updateState) - case Confirm(deliveryId) ⇒ persist(MsgConfirmed(deliveryId))(updateState) + case s: String => persist(MsgSent(s))(updateState) + case Confirm(deliveryId) => persist(MsgConfirmed(deliveryId))(updateState) } override def receiveRecover: Receive = { - case evt: Evt ⇒ updateState(evt) + case evt: Evt => updateState(evt) } def updateState(evt: Evt): Unit = evt match { - case MsgSent(s) ⇒ - deliver(destination)(deliveryId ⇒ Msg(deliveryId, s)) + case MsgSent(s) => + deliver(destination)(deliveryId => Msg(deliveryId, s)) - case MsgConfirmed(deliveryId) ⇒ confirmDelivery(deliveryId) + case MsgConfirmed(deliveryId) => confirmDelivery(deliveryId) } } class MyDestination extends Actor { def receive = { - case Msg(deliveryId, s) ⇒ + case Msg(deliveryId, s) => // ... sender() ! Confirm(deliveryId) } @@ -166,10 +166,10 @@ object PersistenceDocSpec { val snapShotInterval = 1000 override def receiveCommand: Receive = { - case SaveSnapshotSuccess(metadata) ⇒ // ... - case SaveSnapshotFailure(metadata, reason) ⇒ // ... - case cmd: String ⇒ - persist(s"evt-$cmd") { e ⇒ + case SaveSnapshotSuccess(metadata) => // ... + case SaveSnapshotFailure(metadata, reason) => // ... + case cmd: String => + persist(s"evt-$cmd") { e => updateState(e) if (lastSequenceNr % snapShotInterval == 0 && lastSequenceNr != 0) saveSnapshot(state) @@ -195,9 +195,9 @@ object PersistenceDocSpec { var state: Any = _ override def receiveRecover: Receive = { - case SnapshotOffer(metadata, offeredSnapshot) ⇒ state = offeredSnapshot - case RecoveryCompleted ⇒ - case event ⇒ // ... + case SnapshotOffer(metadata, offeredSnapshot) => state = offeredSnapshot + case RecoveryCompleted => + case event => // ... } //#snapshot-offer @@ -214,14 +214,14 @@ object PersistenceDocSpec { override def persistenceId = "my-stable-persistence-id" override def receiveRecover: Receive = { - case _ ⇒ // handle recovery here + case _ => // handle recovery here } override def receiveCommand: Receive = { - case c: String ⇒ { + case c: String => { sender() ! c - persistAsync(s"evt-$c-1") { e ⇒ sender() ! e } - persistAsync(s"evt-$c-2") { e ⇒ sender() ! e } + persistAsync(s"evt-$c-1") { e => sender() ! e } + persistAsync(s"evt-$c-2") { e => sender() ! e } } } } @@ -249,15 +249,15 @@ object PersistenceDocSpec { override def persistenceId = "my-stable-persistence-id" override def receiveRecover: Receive = { - case _ ⇒ // handle recovery here + case _ => // handle recovery here } override def receiveCommand: Receive = { - case c: String ⇒ { + case c: String => { sender() ! c - persistAsync(s"evt-$c-1") { e ⇒ sender() ! e } - persistAsync(s"evt-$c-2") { e ⇒ sender() ! e } - deferAsync(s"evt-$c-3") { e ⇒ sender() ! e } + persistAsync(s"evt-$c-1") { e => sender() ! e } + persistAsync(s"evt-$c-2") { e => sender() ! e } + deferAsync(s"evt-$c-3") { e => sender() ! e } } } } @@ -287,15 +287,15 @@ object PersistenceDocSpec { override def persistenceId = "my-stable-persistence-id" override def receiveRecover: Receive = { - case _ ⇒ // handle recovery here + case _ => // handle recovery here } override def receiveCommand: Receive = { - case c: String ⇒ { + case c: String => { sender() ! c - persist(s"evt-$c-1") { e ⇒ sender() ! e } - persist(s"evt-$c-2") { e ⇒ sender() ! e } - defer(s"evt-$c-3") { e ⇒ sender() ! e } + persist(s"evt-$c-1") { e => sender() ! e } + persist(s"evt-$c-2") { e => sender() ! e } + defer(s"evt-$c-3") { e => sender() ! e } } } } @@ -308,24 +308,24 @@ object PersistenceDocSpec { override def persistenceId = "my-stable-persistence-id" override def receiveRecover: Receive = { - case _ ⇒ // handle recovery here + case _ => // handle recovery here } //#nested-persist-persist override def receiveCommand: Receive = { - case c: String ⇒ + case c: String => sender() ! c - persist(s"$c-1-outer") { outer1 ⇒ + persist(s"$c-1-outer") { outer1 => sender() ! outer1 - persist(s"$c-1-inner") { inner1 ⇒ + persist(s"$c-1-inner") { inner1 => sender() ! inner1 } } - persist(s"$c-2-outer") { outer2 ⇒ + persist(s"$c-2-outer") { outer2 => sender() ! outer2 - persist(s"$c-2-inner") { inner2 ⇒ + persist(s"$c-2-inner") { inner2 => sender() ! inner2 } } @@ -356,20 +356,20 @@ object PersistenceDocSpec { override def persistenceId = "my-stable-persistence-id" override def receiveRecover: Receive = { - case _ ⇒ // handle recovery here + case _ => // handle recovery here } //#nested-persistAsync-persistAsync override def receiveCommand: Receive = { - case c: String ⇒ + case c: String => sender() ! c - persistAsync(c + "-outer-1") { outer ⇒ + persistAsync(c + "-outer-1") { outer => sender() ! outer - persistAsync(c + "-inner-1") { inner ⇒ sender() ! inner } + persistAsync(c + "-inner-1") { inner => sender() ! inner } } - persistAsync(c + "-outer-2") { outer ⇒ + persistAsync(c + "-outer-2") { outer => sender() ! outer - persistAsync(c + "-inner-2") { inner ⇒ sender() ! inner } + persistAsync(c + "-inner-2") { inner => sender() ! inner } } } //#nested-persistAsync-persistAsync @@ -408,15 +408,15 @@ object PersistenceDocSpec { override def persistenceId = "safe-actor" override def receiveCommand: Receive = { - case c: String ⇒ + case c: String => println(c) persist(s"handle-$c") { println(_) } - case Shutdown ⇒ + case Shutdown => context.stop(self) } override def receiveRecover: Receive = { - case _ ⇒ // handle recovery here + case _ => // handle recovery here } } //#safe-shutdown diff --git a/akka-docs/src/test/scala/docs/persistence/PersistenceEventAdapterDocSpec.scala b/akka-docs/src/test/scala/docs/persistence/PersistenceEventAdapterDocSpec.scala index 4b11ff6fa6..45be47b509 100644 --- a/akka-docs/src/test/scala/docs/persistence/PersistenceEventAdapterDocSpec.scala +++ b/akka-docs/src/test/scala/docs/persistence/PersistenceEventAdapterDocSpec.scala @@ -76,12 +76,12 @@ class PersistenceEventAdapterDocSpec(config: String) extends AkkaSpec(config) { override def journalPluginId: String = "akka.persistence.journal.auto-json-store" override def receiveRecover: Receive = { - case RecoveryCompleted ⇒ // ignore... - case e ⇒ p.ref ! e + case RecoveryCompleted => // ignore... + case e => p.ref ! e } override def receiveCommand: Receive = { - case c ⇒ persist(c) { e ⇒ p.ref ! e } + case c => persist(c) { e => p.ref ! e } } }) @@ -108,12 +108,12 @@ class PersistenceEventAdapterDocSpec(config: String) extends AkkaSpec(config) { override def journalPluginId: String = "akka.persistence.journal.manual-json-store" override def receiveRecover: Receive = { - case RecoveryCompleted ⇒ // ignore... - case e ⇒ p.ref ! e + case RecoveryCompleted => // ignore... + case e => p.ref ! e } override def receiveCommand: Receive = { - case c ⇒ persist(c) { e ⇒ p.ref ! e } + case c => persist(c) { e => p.ref ! e } } }) @@ -165,7 +165,7 @@ class MyAutoJsonEventAdapter(system: ExtendedActorSystem) extends EventAdapter { override def fromJournal(event: Any, manifest: String): EventSeq = EventSeq.single { event match { - case json: JsonElement ⇒ + case json: JsonElement => val clazz = system.dynamicAccess.getClassFor[Any](manifest).get gson.fromJson(json, clazz) } @@ -202,7 +202,7 @@ class MyManualJsonEventAdapter(system: ExtendedActorSystem) extends EventAdapter } override def fromJournal(event: Any, m: String): EventSeq = event match { - case json: JsonElement ⇒ + case json: JsonElement => val manifest = json.getAsJsonObject.get("_manifest").getAsString val clazz = system.dynamicAccess.getClassFor[Any](manifest).get @@ -214,14 +214,14 @@ class MyTaggingEventAdapter(system: ExtendedActorSystem) extends EventAdapter { override def manifest(event: Any): String = "" override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case j: MyTaggingJournalModel ⇒ EventSeq.single(j) + case j: MyTaggingJournalModel => EventSeq.single(j) } override def toJournal(event: Any): Any = { event match { - case Person(_, age) if age >= 18 ⇒ MyTaggingJournalModel(event, tags = Set("adult")) - case Person(_, age) ⇒ MyTaggingJournalModel(event, tags = Set("minor")) - case _ ⇒ MyTaggingJournalModel(event, tags = Set.empty) + case Person(_, age) if age >= 18 => MyTaggingJournalModel(event, tags = Set("adult")) + case Person(_, age) => MyTaggingJournalModel(event, tags = Set("minor")) + case _ => MyTaggingJournalModel(event, tags = Set.empty) } } } diff --git a/akka-docs/src/test/scala/docs/persistence/PersistencePluginDocSpec.scala b/akka-docs/src/test/scala/docs/persistence/PersistencePluginDocSpec.scala index f6512e06d8..52929e704f 100644 --- a/akka-docs/src/test/scala/docs/persistence/PersistencePluginDocSpec.scala +++ b/akka-docs/src/test/scala/docs/persistence/PersistencePluginDocSpec.scala @@ -129,7 +129,7 @@ object SharedLeveldbPluginDocSpec { } def receive = { - case ActorIdentity(1, Some(store)) ⇒ + case ActorIdentity(1, Some(store)) => SharedLeveldbJournal.setStore(store, context.system) } } @@ -161,7 +161,7 @@ class MyJournal extends AsyncWriteJournal { def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = ??? def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)( - replayCallback: (PersistentRepr) ⇒ Unit): Future[Unit] = ??? + replayCallback: (PersistentRepr) => Unit): Future[Unit] = ??? def asyncReadHighestSequenceNr( persistenceId: String, fromSequenceNr: Long): Future[Long] = ??? diff --git a/akka-docs/src/test/scala/docs/persistence/PersistenceSchemaEvolutionDocSpec.scala b/akka-docs/src/test/scala/docs/persistence/PersistenceSchemaEvolutionDocSpec.scala index 33805134c9..cc5f6b7a2e 100644 --- a/akka-docs/src/test/scala/docs/persistence/PersistenceSchemaEvolutionDocSpec.scala +++ b/akka-docs/src/test/scala/docs/persistence/PersistenceSchemaEvolutionDocSpec.scala @@ -53,10 +53,10 @@ class ProtobufReadOptional { sealed abstract class SeatType { def code: String } object SeatType { def fromString(s: String) = s match { - case Window.code ⇒ Window - case Aisle.code ⇒ Aisle - case Other.code ⇒ Other - case _ ⇒ Unknown + case Window.code => Window + case Aisle.code => Aisle + case Other.code => Other + case _ => Unknown } case object Window extends SeatType { override val code = "W" } case object Aisle extends SeatType { override val code = "A" } @@ -82,15 +82,15 @@ class ProtobufReadOptional { override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case SeatReservedManifest ⇒ + case SeatReservedManifest => // use generated protobuf serializer seatReserved(FlightAppModels.SeatReserved.parseFrom(bytes)) - case _ ⇒ + case _ => throw new NotSerializableException("Unable to handle manifest: " + manifest) } override def toBinary(o: AnyRef): Array[Byte] = o match { - case s: SeatReserved ⇒ + case s: SeatReserved => FlightAppModels.SeatReserved.newBuilder .setRow(s.row) .setLetter(s.letter) @@ -142,12 +142,12 @@ class RenamePlainJson { marshaller.toJson(event) override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case json: JsObject ⇒ EventSeq(marshaller.fromJson(manifest match { - case V1 ⇒ rename(json, "code", "seatNr") - case V2 ⇒ json // pass-through - case unknown ⇒ throw new IllegalArgumentException(s"Unknown manifest: $unknown") + case json: JsObject => EventSeq(marshaller.fromJson(manifest match { + case V1 => rename(json, "code", "seatNr") + case V2 => json // pass-through + case unknown => throw new IllegalArgumentException(s"Unknown manifest: $unknown") })) - case _ ⇒ + case _ => val c = event.getClass throw new IllegalArgumentException("Can only work with JSON, was: %s".format(c)) } @@ -189,19 +189,19 @@ object SimplestCustomSerializer { // serialize the object override def toBinary(obj: AnyRef): Array[Byte] = obj match { - case p: Person ⇒ s"""${p.name}|${p.surname}""".getBytes(Utf8) - case _ ⇒ throw new IllegalArgumentException( + case p: Person => s"""${p.name}|${p.surname}""".getBytes(Utf8) + case _ => throw new IllegalArgumentException( s"Unable to serialize to bytes, clazz was: ${obj.getClass}!") } // deserialize the object, using the manifest to indicate which logic to apply override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case PersonManifest ⇒ + case PersonManifest => val nameAndSurname = new String(bytes, Utf8) val Array(name, surname) = nameAndSurname.split("[|]") Person(name, surname) - case _ ⇒ throw new NotSerializableException( + case _ => throw new NotSerializableException( s"Unable to deserialize from bytes, manifest was: $manifest! Bytes length: " + bytes.length) } @@ -248,13 +248,13 @@ class UserEventsAdapter extends EventAdapter { override def manifest(event: Any): String = "" override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case UserDetailsChanged(null, address) ⇒ EventSeq(UserAddressChanged(address)) - case UserDetailsChanged(name, null) ⇒ EventSeq(UserNameChanged(name)) - case UserDetailsChanged(name, address) ⇒ + case UserDetailsChanged(null, address) => EventSeq(UserAddressChanged(address)) + case UserDetailsChanged(name, null) => EventSeq(UserNameChanged(name)) + case UserDetailsChanged(name, address) => EventSeq( UserNameChanged(name), UserAddressChanged(address)) - case event: V2 ⇒ EventSeq(event) + case event: V2 => EventSeq(event) } override def toJournal(event: Any): Any = event @@ -277,15 +277,15 @@ class RemovedEventsAwareSerializer extends SerializerWithStringManifest { override def manifest(o: AnyRef): String = o.getClass.getName override def toBinary(o: AnyRef): Array[Byte] = o match { - case _ ⇒ o.toString.getBytes(utf8) // example serialization + case _ => o.toString.getBytes(utf8) // example serialization } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case m if SkipEventManifestsEvents.contains(m) ⇒ + case m if SkipEventManifestsEvents.contains(m) => EventDeserializationSkipped - case other ⇒ new String(bytes, utf8) + case other => new String(bytes, utf8) } } //#string-serializer-skip-deleved-event-by-manifest @@ -296,8 +296,8 @@ class SkippedEventsAwareAdapter extends EventAdapter { override def toJournal(event: Any) = event override def fromJournal(event: Any, manifest: String) = event match { - case EventDeserializationSkipped ⇒ EventSeq.empty - case _ ⇒ EventSeq(event) + case EventDeserializationSkipped => EventSeq.empty + case _ => EventSeq(event) } } //#string-serializer-skip-deleved-event-by-manifest-adapter @@ -313,15 +313,15 @@ class RenamedEventAwareSerializer extends SerializerWithStringManifest { override def manifest(o: AnyRef): String = o.getClass.getName override def toBinary(o: AnyRef): Array[Byte] = o match { - case SamplePayload(data) ⇒ s"""$data""".getBytes(Utf8) + case SamplePayload(data) => s"""$data""".getBytes(Utf8) // previously also handled "old" events here. } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case OldPayloadClassName ⇒ SamplePayload(new String(bytes, Utf8)) - case MyPayloadClassName ⇒ SamplePayload(new String(bytes, Utf8)) - case other ⇒ throw new NotSerializableException(s"unexpected manifest [$other]") + case OldPayloadClassName => SamplePayload(new String(bytes, Utf8)) + case MyPayloadClassName => SamplePayload(new String(bytes, Utf8)) + case other => throw new NotSerializableException(s"unexpected manifest [$other]") } } //#string-serializer-handle-rename @@ -348,11 +348,11 @@ class DetachedModelsAdapter extends EventAdapter { override def manifest(event: Any): String = "" override def toJournal(event: Any): Any = event match { - case DomainModel.SeatBooked(code, customer) ⇒ + case DomainModel.SeatBooked(code, customer) => DataModel.SeatBooked(code, customer.name) } override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case DataModel.SeatBooked(code, customerName) ⇒ + case DataModel.SeatBooked(code, customerName) => EventSeq(DomainModel.SeatBooked(code, DomainModel.Customer(customerName))) } } @@ -374,9 +374,9 @@ class JsonDataModelAdapter extends EventAdapter { marshaller.toJson(event) override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case json: JsObject ⇒ + case json: JsObject => EventSeq(marshaller.fromJson(json)) - case _ ⇒ + case _ => throw new IllegalArgumentException( "Unable to fromJournal a non-JSON object! Was: " + event.getClass) } diff --git a/akka-docs/src/test/scala/docs/persistence/PersistentActorExample.scala b/akka-docs/src/test/scala/docs/persistence/PersistentActorExample.scala index 1e38fdcd2f..f6c0823fa1 100644 --- a/akka-docs/src/test/scala/docs/persistence/PersistentActorExample.scala +++ b/akka-docs/src/test/scala/docs/persistence/PersistentActorExample.scala @@ -29,20 +29,20 @@ class ExamplePersistentActor extends PersistentActor { state.size val receiveRecover: Receive = { - case evt: Evt ⇒ updateState(evt) - case SnapshotOffer(_, snapshot: ExampleState) ⇒ state = snapshot + case evt: Evt => updateState(evt) + case SnapshotOffer(_, snapshot: ExampleState) => state = snapshot } val snapShotInterval = 1000 val receiveCommand: Receive = { - case Cmd(data) ⇒ - persist(Evt(s"${data}-${numEvents}")) { event ⇒ + case Cmd(data) => + persist(Evt(s"${data}-${numEvents}")) { event => updateState(event) context.system.eventStream.publish(event) if (lastSequenceNr % snapShotInterval == 0 && lastSequenceNr != 0) saveSnapshot(state) } - case "print" ⇒ println(state) + case "print" => println(state) } } diff --git a/akka-docs/src/test/scala/docs/persistence/query/LeveldbPersistenceQueryDocSpec.scala b/akka-docs/src/test/scala/docs/persistence/query/LeveldbPersistenceQueryDocSpec.scala index 19ded40204..dedc4582cf 100644 --- a/akka-docs/src/test/scala/docs/persistence/query/LeveldbPersistenceQueryDocSpec.scala +++ b/akka-docs/src/test/scala/docs/persistence/query/LeveldbPersistenceQueryDocSpec.scala @@ -24,13 +24,13 @@ object LeveldbPersistenceQueryDocSpec { class MyTaggingEventAdapter extends WriteEventAdapter { val colors = Set("green", "black", "blue") override def toJournal(event: Any): Any = event match { - case s: String ⇒ - var tags = colors.foldLeft(Set.empty[String]) { (acc, c) ⇒ + case s: String => + var tags = colors.foldLeft(Set.empty[String]) { (acc, c) => if (s.contains(c)) acc + c else acc } if (tags.isEmpty) event else Tagged(event, tags) - case _ ⇒ event + case _ => event } override def manifest(event: Any): String = "" diff --git a/akka-docs/src/test/scala/docs/persistence/query/MyEventsByTagPublisher.scala b/akka-docs/src/test/scala/docs/persistence/query/MyEventsByTagPublisher.scala index 91f2708fd4..317a6ba95a 100644 --- a/akka-docs/src/test/scala/docs/persistence/query/MyEventsByTagPublisher.scala +++ b/akka-docs/src/test/scala/docs/persistence/query/MyEventsByTagPublisher.scala @@ -39,11 +39,11 @@ class MyEventsByTagPublisher(tag: String, offset: Long, refreshInterval: FiniteD } def receive = { - case _: Request | Continue ⇒ + case _: Request | Continue => query() deliverBuf() - case Cancel ⇒ + case Cancel => context.stop(self) } @@ -79,12 +79,12 @@ class MyEventsByTagPublisher(tag: String, offset: Long, refreshInterval: FiniteD val serialization = SerializationExtension(context.system) buf = result.map { - case (id, bytes) ⇒ + case (id, bytes) => val p = serialization.deserialize(bytes, classOf[PersistentRepr]).get EventEnvelope(offset = Sequence(id), p.persistenceId, p.sequenceNr, p.payload) } } catch { - case e: Exception ⇒ + case e: Exception => onErrorThenStop(e) } } diff --git a/akka-docs/src/test/scala/docs/persistence/query/PersistenceQueryDocSpec.scala b/akka-docs/src/test/scala/docs/persistence/query/PersistenceQueryDocSpec.scala index 830a3d1f00..a52f2303ca 100644 --- a/akka-docs/src/test/scala/docs/persistence/query/PersistenceQueryDocSpec.scala +++ b/akka-docs/src/test/scala/docs/persistence/query/PersistenceQueryDocSpec.scala @@ -67,12 +67,12 @@ object PersistenceQueryDocSpec { */ override def eventsByTag( tag: String, offset: Offset): Source[EventEnvelope, NotUsed] = offset match { - case Sequence(offsetValue) ⇒ + case Sequence(offsetValue) => val props = MyEventsByTagPublisher.props(tag, offsetValue, refreshInterval) Source.actorPublisher[EventEnvelope](props) - .mapMaterializedValue(_ ⇒ NotUsed) - case NoOffset ⇒ eventsByTag(tag, Sequence(0L)) //recursive - case _ ⇒ + .mapMaterializedValue(_ => NotUsed) + case NoOffset => eventsByTag(tag, Sequence(0L)) //recursive + case _ => throw new IllegalArgumentException("LevelDB does not support " + offset.getClass.getName + " offsets") } @@ -166,7 +166,7 @@ object PersistenceQueryDocSpec { // Using an example (Reactive Streams) Database driver readJournal .eventsByPersistenceId("user-1337", fromSequenceNr = 0L, toSequenceNr = Long.MaxValue) - .map(envelope ⇒ envelope.event) + .map(envelope => envelope.event) .map(convertToReadSideTypes) // convert to datatype .grouped(20) // batch inserts into groups of 20 .runWith(Sink.fromSubscriber(dbBatchWriter)) // write batches to read-side database @@ -180,7 +180,7 @@ object PersistenceQueryDocSpec { var state: ComplexState = ComplexState() def receive = { - case m ⇒ + case m => state = updateState(state, m) if (state.readyToSave) store.save(Record(state)) } @@ -223,7 +223,7 @@ class PersistenceQueryDocSpec(s: String) extends AkkaSpec(s) { // materialize stream, consuming events implicit val mat = ActorMaterializer() - source.runForeach { event ⇒ println("Event: " + event) } + source.runForeach { event => println("Event: " + event) } //#basic-usage //#all-persistence-ids-live @@ -261,12 +261,12 @@ class PersistenceQueryDocSpec(s: String) extends AkkaSpec(s) { readJournal.byTagsWithMeta(Set("red", "blue")) query - .mapMaterializedValue { meta ⇒ + .mapMaterializedValue { meta => println(s"The query is: " + s"ordered deterministically: ${meta.deterministicOrder}, " + s"infinite: ${meta.infinite}") } - .map { event ⇒ println(s"Event payload: ${event.payload}") } + .map { event => println(s"Event payload: ${event.payload}") } .runWith(Sink.ignore) //#advanced-journal-query-usage @@ -293,11 +293,11 @@ class PersistenceQueryDocSpec(s: String) extends AkkaSpec(s) { val writerProps = Props(classOf[TheOneWhoWritesToQueryJournal], "bid") val writer = system.actorOf(writerProps, "bid-projection-writer") - bidProjection.latestOffset.foreach { startFromOffset ⇒ + bidProjection.latestOffset.foreach { startFromOffset => readJournal .eventsByTag("bid", Sequence(startFromOffset)) - .mapAsync(8) { envelope ⇒ (writer ? envelope.event).map(_ ⇒ envelope.offset) } - .mapAsync(1) { offset ⇒ bidProjection.saveProgress(offset) } + .mapAsync(8) { envelope => (writer ? envelope.event).map(_ => envelope.offset) } + .mapAsync(1) { offset => bidProjection.saveProgress(offset) } .runWith(Sink.ignore) } //#projection-into-different-store-actor-run @@ -319,7 +319,7 @@ class PersistenceQueryDocSpec(s: String) extends AkkaSpec(s) { readJournal .eventsByTag("bid", NoOffset) - .mapAsync(1) { e ⇒ store.save(e) } + .mapAsync(1) { e => store.save(e) } .runWith(Sink.ignore) //#projection-into-different-store-simple } diff --git a/akka-docs/src/test/scala/docs/remoting/RemoteDeploymentDocSpec.scala b/akka-docs/src/test/scala/docs/remoting/RemoteDeploymentDocSpec.scala index 0504271011..1c74604352 100644 --- a/akka-docs/src/test/scala/docs/remoting/RemoteDeploymentDocSpec.scala +++ b/akka-docs/src/test/scala/docs/remoting/RemoteDeploymentDocSpec.scala @@ -14,7 +14,7 @@ import akka.remote.RemoteScope object RemoteDeploymentDocSpec { class SampleActor extends Actor { - def receive = { case _ ⇒ sender() ! self } + def receive = { case _ => sender() ! self } } } diff --git a/akka-docs/src/test/scala/docs/routing/ConsistentHashingRouterDocSpec.scala b/akka-docs/src/test/scala/docs/routing/ConsistentHashingRouterDocSpec.scala index 1d1868b919..7ce4b54d04 100644 --- a/akka-docs/src/test/scala/docs/routing/ConsistentHashingRouterDocSpec.scala +++ b/akka-docs/src/test/scala/docs/routing/ConsistentHashingRouterDocSpec.scala @@ -19,9 +19,9 @@ object ConsistentHashingRouterDocSpec { var cache = Map.empty[String, String] def receive = { - case Entry(key, value) ⇒ cache += (key -> value) - case Get(key) ⇒ sender() ! cache.get(key) - case Evict(key) ⇒ cache -= key + case Entry(key, value) => cache += (key -> value) + case Get(key) => sender() ! cache.get(key) + case Evict(key) => cache -= key } } @@ -51,7 +51,7 @@ class ConsistentHashingRouterDocSpec extends AkkaSpec with ImplicitSender { import akka.routing.ConsistentHashingRouter.ConsistentHashableEnvelope def hashMapping: ConsistentHashMapping = { - case Evict(key) ⇒ key + case Evict(key) => key } val cache: ActorRef = diff --git a/akka-docs/src/test/scala/docs/routing/CustomRouterDocSpec.scala b/akka-docs/src/test/scala/docs/routing/CustomRouterDocSpec.scala index 8a081156b6..b71808b9ee 100644 --- a/akka-docs/src/test/scala/docs/routing/CustomRouterDocSpec.scala +++ b/akka-docs/src/test/scala/docs/routing/CustomRouterDocSpec.scala @@ -51,7 +51,7 @@ akka.actor.deployment { class RedundancyRoutingLogic(nbrCopies: Int) extends RoutingLogic { val roundRobin = RoundRobinRoutingLogic() def select(message: Any, routees: immutable.IndexedSeq[Routee]): Routee = { - val targets = (1 to nbrCopies).map(_ ⇒ roundRobin.select(message, routees)) + val targets = (1 to nbrCopies).map(_ => roundRobin.select(message, routees)) SeveralRoutees(targets) } } @@ -59,7 +59,7 @@ akka.actor.deployment { class Storage extends Actor { def receive = { - case x ⇒ sender() ! x + case x => sender() ! x } } @@ -102,7 +102,7 @@ class CustomRouterDocSpec extends AkkaSpec(CustomRouterDocSpec.config) with Impl //#unit-test-logic val logic = new RedundancyRoutingLogic(nbrCopies = 3) - val routees = for (n ← 1 to 7) yield TestRoutee(n) + val routees = for (n <- 1 to 7) yield TestRoutee(n) val r1 = logic.select("msg", routees) r1.asInstanceOf[SeveralRoutees].routees should be( @@ -121,9 +121,9 @@ class CustomRouterDocSpec extends AkkaSpec(CustomRouterDocSpec.config) with Impl "demonstrate usage of custom router" in { //#usage-1 - for (n ← 1 to 10) system.actorOf(Props[Storage], "s" + n) + for (n <- 1 to 10) system.actorOf(Props[Storage], "s" + n) - val paths = for (n ← 1 to 10) yield ("/user/s" + n) + val paths = for (n <- 1 to 10) yield ("/user/s" + n) val redundancy1: ActorRef = system.actorOf( RedundancyGroup(paths, nbrCopies = 3).props(), @@ -131,7 +131,7 @@ class CustomRouterDocSpec extends AkkaSpec(CustomRouterDocSpec.config) with Impl redundancy1 ! "important" //#usage-1 - for (_ ← 1 to 3) expectMsg("important") + for (_ <- 1 to 3) expectMsg("important") //#usage-2 val redundancy2: ActorRef = system.actorOf( @@ -140,7 +140,7 @@ class CustomRouterDocSpec extends AkkaSpec(CustomRouterDocSpec.config) with Impl redundancy2 ! "very important" //#usage-2 - for (_ ← 1 to 5) expectMsg("very important") + for (_ <- 1 to 5) expectMsg("very important") } diff --git a/akka-docs/src/test/scala/docs/routing/RouterDocSpec.scala b/akka-docs/src/test/scala/docs/routing/RouterDocSpec.scala index 576b945bb5..7f1aa6a001 100644 --- a/akka-docs/src/test/scala/docs/routing/RouterDocSpec.scala +++ b/akka-docs/src/test/scala/docs/routing/RouterDocSpec.scala @@ -307,9 +307,9 @@ router-dispatcher {} } def receive = { - case w: Work ⇒ + case w: Work => router.route(w, sender()) - case Terminated(a) ⇒ + case Terminated(a) => router = router.removeRoutee(a) val r = context.actorOf(Props[Worker]) context watch r @@ -320,7 +320,7 @@ router-dispatcher {} class Worker extends Actor { def receive = { - case _ ⇒ + case _ => } } @@ -333,7 +333,7 @@ router-dispatcher {} //#create-worker-actors def receive = { - case _ ⇒ + case _ => } } @@ -397,7 +397,7 @@ router-dispatcher {} val router10b: ActorRef = context.actorOf(BalancingPool(20).props(Props[Worker]), "router10b") //#balancing-pool-3 - for (i ← 1 to 100) router10b ! i + for (i <- 1 to 100) router10b ! i val threads10b = Thread.getAllStackTraces.keySet.asScala.filter { _.getName contains "router10b" } val threads10bNr = threads10b.size require(threads10bNr == 5, s"Expected 5 threads for router10b, had $threads10bNr! Got: ${threads10b.map(_.getName)}") @@ -519,14 +519,14 @@ router-dispatcher {} //#optimal-size-exploring-resize-pool def receive = { - case _ ⇒ + case _ => } } class Echo extends Actor { def receive = { - case m ⇒ sender() ! m + case m => sender() ! m } } } diff --git a/akka-docs/src/test/scala/docs/serialization/SerializationDocSpec.scala b/akka-docs/src/test/scala/docs/serialization/SerializationDocSpec.scala index bccf1cbf7b..c5c892bd72 100644 --- a/akka-docs/src/test/scala/docs/serialization/SerializationDocSpec.scala +++ b/akka-docs/src/test/scala/docs/serialization/SerializationDocSpec.scala @@ -70,16 +70,16 @@ package docs.serialization { // Use `""` if manifest is not needed. def manifest(obj: AnyRef): String = obj match { - case _: Customer ⇒ CustomerManifest - case _: User ⇒ UserManifest + case _: Customer => CustomerManifest + case _: User => UserManifest } // "toBinary" serializes the given object to an Array of Bytes def toBinary(obj: AnyRef): Array[Byte] = { // Put the real code that serializes the object here obj match { - case Customer(name) ⇒ name.getBytes(UTF_8) - case User(name) ⇒ name.getBytes(UTF_8) + case Customer(name) => name.getBytes(UTF_8) + case User(name) => name.getBytes(UTF_8) } } @@ -88,9 +88,9 @@ package docs.serialization { def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { // Put the real code that deserializes here manifest match { - case CustomerManifest ⇒ + case CustomerManifest => Customer(new String(bytes, UTF_8)) - case UserManifest ⇒ + case UserManifest => User(new String(bytes, UTF_8)) } } diff --git a/akka-docs/src/test/scala/docs/stream/ActorPublisherDocSpec.scala b/akka-docs/src/test/scala/docs/stream/ActorPublisherDocSpec.scala index 468d92e993..29e2b1493f 100644 --- a/akka-docs/src/test/scala/docs/stream/ActorPublisherDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/ActorPublisherDocSpec.scala @@ -30,9 +30,9 @@ object ActorPublisherDocSpec { var buf = Vector.empty[Job] def receive = { - case job: Job if buf.size == MaxBufferSize ⇒ + case job: Job if buf.size == MaxBufferSize => sender() ! JobDenied - case job: Job ⇒ + case job: Job => sender() ! JobAccepted if (buf.isEmpty && totalDemand > 0) onNext(job) @@ -40,9 +40,9 @@ object ActorPublisherDocSpec { buf :+= job deliverBuf() } - case Request(_) ⇒ + case Request(_) => deliverBuf() - case Cancel ⇒ + case Cancel => context.stop(self) } @@ -80,7 +80,7 @@ class ActorPublisherDocSpec extends AkkaSpec { val jobManagerSource = Source.actorPublisher[JobManager.Job](JobManager.props) val ref = Flow[JobManager.Job] .map(_.payload.toUpperCase) - .map { elem ⇒ println(elem); elem } + .map { elem => println(elem); elem } .to(Sink.ignore) .runWith(jobManagerSource) diff --git a/akka-docs/src/test/scala/docs/stream/ActorSubscriberDocSpec.scala b/akka-docs/src/test/scala/docs/stream/ActorSubscriberDocSpec.scala index 45bcfa8710..55117418e1 100644 --- a/akka-docs/src/test/scala/docs/stream/ActorSubscriberDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/ActorSubscriberDocSpec.scala @@ -49,17 +49,17 @@ object ActorSubscriberDocSpec { } def receive = { - case OnNext(Msg(id, replyTo)) ⇒ + case OnNext(Msg(id, replyTo)) => queue += (id -> replyTo) assert(queue.size <= MaxQueueSize, s"queued too many: ${queue.size}") router.route(Work(id), self) - case Reply(id) ⇒ + case Reply(id) => queue(id) ! Done(id) queue -= id if (canceled && queue.isEmpty) { context.stop(self) } - case OnComplete ⇒ + case OnComplete => if (queue.isEmpty) { context.stop(self) } @@ -69,7 +69,7 @@ object ActorSubscriberDocSpec { class Worker extends Actor { import WorkerPool._ def receive = { - case Work(id) ⇒ + case Work(id) => // ... sender() ! Reply(id) } diff --git a/akka-docs/src/test/scala/docs/stream/BidiFlowDocSpec.scala b/akka-docs/src/test/scala/docs/stream/BidiFlowDocSpec.scala index 7507fe76ea..62798d7a9b 100644 --- a/akka-docs/src/test/scala/docs/stream/BidiFlowDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/BidiFlowDocSpec.scala @@ -24,8 +24,8 @@ object BidiFlowDocSpec { //#implementation-details-elided implicit val order = ByteOrder.LITTLE_ENDIAN msg match { - case Ping(id) ⇒ ByteString.newBuilder.putByte(1).putInt(id).result() - case Pong(id) ⇒ ByteString.newBuilder.putByte(2).putInt(id).result() + case Ping(id) => ByteString.newBuilder.putByte(1).putInt(id).result() + case Pong(id) => ByteString.newBuilder.putByte(2).putInt(id).result() } //#implementation-details-elided } @@ -35,15 +35,15 @@ object BidiFlowDocSpec { implicit val order = ByteOrder.LITTLE_ENDIAN val it = bytes.iterator it.getByte match { - case 1 ⇒ Ping(it.getInt) - case 2 ⇒ Pong(it.getInt) - case other ⇒ throw new RuntimeException(s"parse error: expected 1|2 got $other") + case 1 => Ping(it.getInt) + case 2 => Pong(it.getInt) + case other => throw new RuntimeException(s"parse error: expected 1|2 got $other") } //#implementation-details-elided } //#codec-impl - val codecVerbose = BidiFlow.fromGraph(GraphDSL.create() { b ⇒ + val codecVerbose = BidiFlow.fromGraph(GraphDSL.create() { b => // construct and add the top flow, going outbound val outbound = b.add(Flow[Message].map(toBytes)) // construct and add the bottom flow, going inbound @@ -57,7 +57,7 @@ object BidiFlowDocSpec { //#codec //#framing - val framing = BidiFlow.fromGraph(GraphDSL.create() { b ⇒ + val framing = BidiFlow.fromGraph(GraphDSL.create() { b => implicit val order = ByteOrder.LITTLE_ENDIAN def addLengthHeader(bytes: ByteString) = { @@ -134,12 +134,12 @@ object BidiFlowDocSpec { }) //#framing - val chopUp = BidiFlow.fromGraph(GraphDSL.create() { b ⇒ + val chopUp = BidiFlow.fromGraph(GraphDSL.create() { b => val f = Flow[ByteString].mapConcat(_.map(ByteString(_))) BidiShape.fromFlows(b.add(f), b.add(f)) }) - val accumulate = BidiFlow.fromGraph(GraphDSL.create() { b ⇒ + val accumulate = BidiFlow.fromGraph(GraphDSL.create() { b => val f = Flow[ByteString].grouped(1000).map(_.fold(ByteString.empty)(_ ++ _)) BidiShape.fromFlows(b.add(f), b.add(f)) }) @@ -168,7 +168,7 @@ class BidiFlowDocSpec extends AkkaSpec { val stack = codec.atop(framing) // test it by plugging it into its own inverse and closing the right end - val pingpong = Flow[Message].collect { case Ping(id) ⇒ Pong(id) } + val pingpong = Flow[Message].collect { case Ping(id) => Pong(id) } val flow = stack.atop(stack.reversed).join(pingpong) val result = Source((0 to 9).map(Ping)).via(flow).limit(20).runWith(Sink.seq) Await.result(result, 1.second) should ===((0 to 9).map(Pong)) @@ -177,14 +177,14 @@ class BidiFlowDocSpec extends AkkaSpec { "work when chopped up" in { val stack = codec.atop(framing) - val flow = stack.atop(chopUp).atop(stack.reversed).join(Flow[Message].map { case Ping(id) ⇒ Pong(id) }) + val flow = stack.atop(chopUp).atop(stack.reversed).join(Flow[Message].map { case Ping(id) => Pong(id) }) val f = Source((0 to 9).map(Ping)).via(flow).limit(20).runWith(Sink.seq) Await.result(f, 1.second) should ===((0 to 9).map(Pong)) } "work when accumulated" in { val stack = codec.atop(framing) - val flow = stack.atop(accumulate).atop(stack.reversed).join(Flow[Message].map { case Ping(id) ⇒ Pong(id) }) + val flow = stack.atop(accumulate).atop(stack.reversed).join(Flow[Message].map { case Ping(id) => Pong(id) }) val f = Source((0 to 9).map(Ping)).via(flow).limit(20).runWith(Sink.seq) Await.result(f, 1.second) should ===((0 to 9).map(Pong)) } diff --git a/akka-docs/src/test/scala/docs/stream/CompositionDocSpec.scala b/akka-docs/src/test/scala/docs/stream/CompositionDocSpec.scala index b6027982a4..d5ab488aa4 100644 --- a/akka-docs/src/test/scala/docs/stream/CompositionDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/CompositionDocSpec.scala @@ -169,7 +169,7 @@ class CompositionDocSpec extends AkkaSpec { "closed graph" in { //#embed-closed val closed1 = Source.single(0).to(Sink.foreach(println)) - val closed2 = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder ⇒ + val closed2 = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder => val embeddedClosed: ClosedShape = builder.add(closed1) // … embeddedClosed @@ -192,7 +192,7 @@ class CompositionDocSpec extends AkkaSpec { //#mat-combine-2 // Materializes to NotUsed (orange) - val flow2: Flow[Int, ByteString, NotUsed] = Flow[Int].map { i ⇒ ByteString(i.toString) } + val flow2: Flow[Int, ByteString, NotUsed] = Flow[Int].map { i => ByteString(i.toString) } // Materializes to Future[OutgoingConnection] (yellow) val flow3: Flow[ByteString, ByteString, Future[OutgoingConnection]] = diff --git a/akka-docs/src/test/scala/docs/stream/FlowDocSpec.scala b/akka-docs/src/test/scala/docs/stream/FlowDocSpec.scala index 9769642fbd..94815ad7fa 100644 --- a/akka-docs/src/test/scala/docs/stream/FlowDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/FlowDocSpec.scala @@ -27,10 +27,10 @@ class FlowDocSpec extends AkkaSpec with CompileOnlySpec { "source is immutable" in { //#source-immutable val source = Source(1 to 10) - source.map(_ ⇒ 0) // has no effect on source, since it's immutable + source.map(_ => 0) // has no effect on source, since it's immutable source.runWith(Sink.fold(0)(_ + _)) // 55 - val zeroes = source.map(_ ⇒ 0) // returns new Source[Int], with `map()` appended + val zeroes = source.map(_ => 0) // returns new Source[Int], with `map()` appended zeroes.runWith(Sink.fold(0)(_ + _)) // 0 //#source-immutable } @@ -81,12 +81,12 @@ class FlowDocSpec extends AkkaSpec with CompileOnlySpec { import scala.concurrent.duration._ case object Tick - val timer = Source.tick(initialDelay = 1.second, interval = 1.seconds, tick = () ⇒ Tick) + val timer = Source.tick(initialDelay = 1.second, interval = 1.seconds, tick = () => Tick) val timerCancel: Cancellable = Sink.ignore.runWith(timer) timerCancel.cancel() - val timerMap = timer.map(tick ⇒ "tick") + val timerMap = timer.map(tick => "tick") // materialize the flow and retrieve the timers Cancellable val timerCancellable = Sink.ignore.runWith(timerMap) timerCancellable.cancel() @@ -152,7 +152,7 @@ class FlowDocSpec extends AkkaSpec with CompileOnlySpec { "various ways of transforming materialized values" in { import scala.concurrent.duration._ - val throttler = Flow.fromGraph(GraphDSL.create(Source.tick(1.second, 1.second, "test")) { implicit builder ⇒ tickSource ⇒ + val throttler = Flow.fromGraph(GraphDSL.create(Source.tick(1.second, 1.second, "test")) { implicit builder => tickSource => import GraphDSL.Implicits._ val zip = builder.add(ZipWith[String, Int, Int](Keep.right)) tickSource ~> zip.in0 @@ -200,7 +200,7 @@ class FlowDocSpec extends AkkaSpec with CompileOnlySpec { // doubly nested pair, but we want to flatten it out val r11: RunnableGraph[(Promise[Option[Int]], Cancellable, Future[Int])] = r9.mapMaterializedValue { - case ((promise, cancellable), future) ⇒ + case ((promise, cancellable), future) => (promise, cancellable, future) } @@ -214,7 +214,7 @@ class FlowDocSpec extends AkkaSpec with CompileOnlySpec { // The result of r11 can be also achieved by using the Graph API val r12: RunnableGraph[(Promise[Option[Int]], Cancellable, Future[Int])] = - RunnableGraph.fromGraph(GraphDSL.create(source, flow, sink)((_, _, _)) { implicit builder ⇒ (src, f, dst) ⇒ + RunnableGraph.fromGraph(GraphDSL.create(source, flow, sink)((_, _, _)) { implicit builder => (src, f, dst) => import GraphDSL.Implicits._ src ~> f ~> dst ClosedShape @@ -263,12 +263,12 @@ object FlowDocSpec { Source.maybe .runWith(Sink.onComplete { - case Success(done) ⇒ println(s"Completed: $done") - case Failure(ex) ⇒ println(s"Failed: ${ex.getMessage}") + case Success(done) => println(s"Completed: $done") + case Failure(ex) => println(s"Failed: ${ex.getMessage}") }) def receive = { - case "boom" ⇒ + case "boom" => context.stop(self) // will also terminate the stream } } @@ -279,12 +279,12 @@ object FlowDocSpec { Source.maybe .runWith(Sink.onComplete { - case Success(done) ⇒ println(s"Completed: $done") - case Failure(ex) ⇒ println(s"Failed: ${ex.getMessage}") + case Success(done) => println(s"Completed: $done") + case Failure(ex) => println(s"Failed: ${ex.getMessage}") }) def receive = { - case "boom" ⇒ + case "boom" => context.stop(self) // will NOT terminate the stream (it's bound to the system!) } } diff --git a/akka-docs/src/test/scala/docs/stream/FlowErrorDocSpec.scala b/akka-docs/src/test/scala/docs/stream/FlowErrorDocSpec.scala index 1c6ac6aff6..1340d7915b 100644 --- a/akka-docs/src/test/scala/docs/stream/FlowErrorDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/FlowErrorDocSpec.scala @@ -33,8 +33,8 @@ class FlowErrorDocSpec extends AkkaSpec { "demonstrate resume stream" in { //#resume val decider: Supervision.Decider = { - case _: ArithmeticException ⇒ Supervision.Resume - case _ ⇒ Supervision.Stop + case _: ArithmeticException => Supervision.Resume + case _ => Supervision.Stop } implicit val materializer = ActorMaterializer( ActorMaterializerSettings(system).withSupervisionStrategy(decider)) @@ -51,11 +51,11 @@ class FlowErrorDocSpec extends AkkaSpec { //#resume-section implicit val materializer = ActorMaterializer() val decider: Supervision.Decider = { - case _: ArithmeticException ⇒ Supervision.Resume - case _ ⇒ Supervision.Stop + case _: ArithmeticException => Supervision.Resume + case _ => Supervision.Stop } val flow = Flow[Int] - .filter(100 / _ < 50).map(elem ⇒ 100 / (5 - elem)) + .filter(100 / _ < 50).map(elem => 100 / (5 - elem)) .withAttributes(ActorAttributes.supervisionStrategy(decider)) val source = Source(0 to 5).via(flow) @@ -71,11 +71,11 @@ class FlowErrorDocSpec extends AkkaSpec { //#restart-section implicit val materializer = ActorMaterializer() val decider: Supervision.Decider = { - case _: IllegalArgumentException ⇒ Supervision.Restart - case _ ⇒ Supervision.Stop + case _: IllegalArgumentException => Supervision.Restart + case _ => Supervision.Stop } val flow = Flow[Int] - .scan(0) { (acc, elem) ⇒ + .scan(0) { (acc, elem) => if (elem < 0) throw new IllegalArgumentException("negative not allowed") else acc + elem } @@ -93,11 +93,11 @@ class FlowErrorDocSpec extends AkkaSpec { "demonstrate recover" in { implicit val materializer = ActorMaterializer() //#recover - Source(0 to 6).map(n ⇒ + Source(0 to 6).map(n => if (n < 5) n.toString else throw new RuntimeException("Boom!") ).recover { - case _: RuntimeException ⇒ "stream truncated" + case _: RuntimeException => "stream truncated" }.runForeach(println) //#recover @@ -119,11 +119,11 @@ stream truncated //#recoverWithRetries val planB = Source(List("five", "six", "seven", "eight")) - Source(0 to 10).map(n ⇒ + Source(0 to 10).map(n => if (n < 5) n.toString else throw new RuntimeException("Boom!") ).recoverWithRetries(attempts = 1, { - case _: RuntimeException ⇒ planB + case _: RuntimeException => planB }).runForeach(println) //#recoverWithRetries diff --git a/akka-docs/src/test/scala/docs/stream/FlowParallelismDocSpec.scala b/akka-docs/src/test/scala/docs/stream/FlowParallelismDocSpec.scala index b2fedfc5d8..81a3192fad 100644 --- a/akka-docs/src/test/scala/docs/stream/FlowParallelismDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/FlowParallelismDocSpec.scala @@ -41,9 +41,9 @@ class FlowParallelismDocSpec extends AkkaSpec { "Demonstrate parallel processing" in { //#parallelism val fryingPan: Flow[ScoopOfBatter, Pancake, NotUsed] = - Flow[ScoopOfBatter].map { batter ⇒ Pancake() } + Flow[ScoopOfBatter].map { batter => Pancake() } - val pancakeChef: Flow[ScoopOfBatter, Pancake, NotUsed] = Flow.fromGraph(GraphDSL.create() { implicit builder ⇒ + val pancakeChef: Flow[ScoopOfBatter, Pancake, NotUsed] = Flow.fromGraph(GraphDSL.create() { implicit builder => val dispatchBatter = builder.add(Balance[ScoopOfBatter](2)) val mergePancakes = builder.add(Merge[Pancake](2)) @@ -64,7 +64,7 @@ class FlowParallelismDocSpec extends AkkaSpec { "Demonstrate parallelized pipelines" in { //#parallel-pipeline val pancakeChef: Flow[ScoopOfBatter, Pancake, NotUsed] = - Flow.fromGraph(GraphDSL.create() { implicit builder ⇒ + Flow.fromGraph(GraphDSL.create() { implicit builder => val dispatchBatter = builder.add(Balance[ScoopOfBatter](2)) val mergePancakes = builder.add(Merge[Pancake](2)) @@ -82,7 +82,7 @@ class FlowParallelismDocSpec extends AkkaSpec { "Demonstrate pipelined parallel processing" in { //#pipelined-parallel val pancakeChefs1: Flow[ScoopOfBatter, HalfCookedPancake, NotUsed] = - Flow.fromGraph(GraphDSL.create() { implicit builder ⇒ + Flow.fromGraph(GraphDSL.create() { implicit builder => val dispatchBatter = builder.add(Balance[ScoopOfBatter](2)) val mergeHalfPancakes = builder.add(Merge[HalfCookedPancake](2)) @@ -95,7 +95,7 @@ class FlowParallelismDocSpec extends AkkaSpec { }) val pancakeChefs2: Flow[HalfCookedPancake, Pancake, NotUsed] = - Flow.fromGraph(GraphDSL.create() { implicit builder ⇒ + Flow.fromGraph(GraphDSL.create() { implicit builder => val dispatchHalfPancakes = builder.add(Balance[HalfCookedPancake](2)) val mergePancakes = builder.add(Merge[Pancake](2)) diff --git a/akka-docs/src/test/scala/docs/stream/FlowStreamRefsDocSpec.scala b/akka-docs/src/test/scala/docs/stream/FlowStreamRefsDocSpec.scala index 0d6b4a30e0..a67fc7f4ec 100644 --- a/akka-docs/src/test/scala/docs/stream/FlowStreamRefsDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/FlowStreamRefsDocSpec.scala @@ -27,7 +27,7 @@ class FlowStreamRefsDocSpec extends AkkaSpec with CompileOnlySpec { implicit val mat = ActorMaterializer()(context) def receive = { - case RequestLogs(streamId) ⇒ + case RequestLogs(streamId) => // obtain the source you want to offer: val source: Source[String, NotUsed] = streamLogs(streamId) @@ -74,7 +74,7 @@ class FlowStreamRefsDocSpec extends AkkaSpec with CompileOnlySpec { implicit val mat = ActorMaterializer()(context) def receive = { - case PrepareUpload(nodeId) ⇒ + case PrepareUpload(nodeId) => // obtain the source you want to offer: val sink: Sink[String, NotUsed] = logsSinkFor(nodeId) diff --git a/akka-docs/src/test/scala/docs/stream/GraphCyclesSpec.scala b/akka-docs/src/test/scala/docs/stream/GraphCyclesSpec.scala index fbf0fe3053..74db079e10 100644 --- a/akka-docs/src/test/scala/docs/stream/GraphCyclesSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/GraphCyclesSpec.scala @@ -13,7 +13,7 @@ class GraphCyclesSpec extends AkkaSpec { implicit val materializer = ActorMaterializer() "Cycle demonstration" must { - val source = Source.fromIterator(() ⇒ Iterator.from(0)) + val source = Source.fromIterator(() => Iterator.from(0)) "include a deadlocked cycle" in { diff --git a/akka-docs/src/test/scala/docs/stream/GraphDSLDocSpec.scala b/akka-docs/src/test/scala/docs/stream/GraphDSLDocSpec.scala index 007fc2b74c..bb79a3c056 100644 --- a/akka-docs/src/test/scala/docs/stream/GraphDSLDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/GraphDSLDocSpec.scala @@ -47,7 +47,7 @@ class GraphDSLDocSpec extends AkkaSpec { "flow connection errors" in { intercept[IllegalStateException] { //#simple-graph - RunnableGraph.fromGraph(GraphDSL.create() { implicit builder ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit builder => import GraphDSL.Implicits._ val source1 = Source(1 to 10) val source2 = Source(1 to 10) @@ -125,7 +125,7 @@ class GraphDSLDocSpec extends AkkaSpec { worker: Flow[In, Out, Any], workerCount: Int): Graph[PriorityWorkerPoolShape[In, Out], NotUsed] = { - GraphDSL.create() { implicit b ⇒ + GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val priorityMerge = b.add(MergePreferred[In](1)) @@ -137,7 +137,7 @@ class GraphDSLDocSpec extends AkkaSpec { // Wire up each of the outputs of the balancer to a worker flow // then merge them back - for (i ← 0 until workerCount) + for (i <- 0 until workerCount) balance.out(i) ~> worker ~> resultsMerge.in(i) // We now expose the input ports of the priorityMerge and the output @@ -160,7 +160,7 @@ class GraphDSLDocSpec extends AkkaSpec { val worker1 = Flow[String].map("step 1 " + _) val worker2 = Flow[String].map("step 2 " + _) - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val priorityPool1 = b.add(PriorityWorkerPool(worker1, 4)) @@ -195,7 +195,7 @@ class GraphDSLDocSpec extends AkkaSpec { "access to materialized value" in { //#graph-dsl-matvalue import GraphDSL.Implicits._ - val foldFlow: Flow[Int, Int, Future[Int]] = Flow.fromGraph(GraphDSL.create(Sink.fold[Int, Int](0)(_ + _)) { implicit builder ⇒ fold ⇒ + val foldFlow: Flow[Int, Int, Future[Int]] = Flow.fromGraph(GraphDSL.create(Sink.fold[Int, Int](0)(_ + _)) { implicit builder => fold => FlowShape(fold.in, builder.materializedValue.mapAsync(4)(identity).outlet) }) //#graph-dsl-matvalue @@ -205,7 +205,7 @@ class GraphDSLDocSpec extends AkkaSpec { //#graph-dsl-matvalue-cycle import GraphDSL.Implicits._ // This cannot produce any value: - val cyclicFold: Source[Int, Future[Int]] = Source.fromGraph(GraphDSL.create(Sink.fold[Int, Int](0)(_ + _)) { implicit builder ⇒ fold ⇒ + val cyclicFold: Source[Int, Future[Int]] = Source.fromGraph(GraphDSL.create(Sink.fold[Int, Int](0)(_ + _)) { implicit builder => fold => // - Fold cannot complete until its upstream mapAsync completes // - mapAsync cannot complete until the materialized Future produced by // fold completes diff --git a/akka-docs/src/test/scala/docs/stream/GraphStageDocSpec.scala b/akka-docs/src/test/scala/docs/stream/GraphStageDocSpec.scala index ce50ed91da..45d1fb943f 100644 --- a/akka-docs/src/test/scala/docs/stream/GraphStageDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/GraphStageDocSpec.scala @@ -121,7 +121,7 @@ class GraphStageDocSpec extends AkkaSpec { } //#one-to-one - class Map[A, B](f: A ⇒ B) extends GraphStage[FlowShape[A, B]] { + class Map[A, B](f: A => B) extends GraphStage[FlowShape[A, B]] { val in = Inlet[A]("Map.in") val out = Outlet[B]("Map.out") @@ -151,13 +151,13 @@ class GraphStageDocSpec extends AkkaSpec { val result = Source(Vector("one", "two", "three")) .via(stringLength) - .runFold(Seq.empty[Int])((elem, acc) ⇒ elem :+ acc) + .runFold(Seq.empty[Int])((elem, acc) => elem :+ acc) Await.result(result, 3.seconds) should ===(Seq(3, 3, 5)) } //#many-to-one - class Filter[A](p: A ⇒ Boolean) extends GraphStage[FlowShape[A, A]] { + class Filter[A](p: A => Boolean) extends GraphStage[FlowShape[A, A]] { val in = Inlet[A]("Filter.in") val out = Outlet[A]("Filter.out") @@ -190,7 +190,7 @@ class GraphStageDocSpec extends AkkaSpec { val result = Source(Vector(1, 2, 3, 4, 5, 6)) .via(evenFilter) - .runFold(Seq.empty[Int])((elem, acc) ⇒ elem :+ acc) + .runFold(Seq.empty[Int])((elem, acc) => elem :+ acc) Await.result(result, 3.seconds) should ===(Seq(2, 4, 6)) } @@ -243,7 +243,7 @@ class GraphStageDocSpec extends AkkaSpec { val result = Source(Vector(1, 2, 3)) .via(duplicator) - .runFold(Seq.empty[Int])((elem, acc) ⇒ elem :+ acc) + .runFold(Seq.empty[Int])((elem, acc) => elem :+ acc) Await.result(result, 3.seconds) should ===(Seq(1, 1, 2, 2, 3, 3)) } @@ -283,14 +283,14 @@ class GraphStageDocSpec extends AkkaSpec { val result = Source(Vector(1, 2, 3)) .via(duplicator) - .runFold(Seq.empty[Int])((elem, acc) ⇒ elem :+ acc) + .runFold(Seq.empty[Int])((elem, acc) => elem :+ acc) Await.result(result, 3.seconds) should ===(Seq(1, 1, 2, 2, 3, 3)) } "Demonstrate chaining of graph stages" in { - val sink = Sink.fold[List[Int], Int](List.empty[Int])((acc, n) ⇒ acc :+ n) + val sink = Sink.fold[List[Int], Int](List.empty[Int])((acc, n) => acc :+ n) //#graph-operator-chain val resultFuture = Source(1 to 5) @@ -320,7 +320,7 @@ class GraphStageDocSpec extends AkkaSpec { new GraphStageLogic(shape) { override def preStart(): Unit = { - val callback = getAsyncCallback[Unit] { (_) ⇒ + val callback = getAsyncCallback[Unit] { (_) => completeStage() } switch.foreach(callback.invoke) @@ -407,7 +407,7 @@ class GraphStageDocSpec extends AkkaSpec { Source(Vector(1, 2, 3)) .via(new TimedGate[Int](2.second)) .takeWithin(250.millis) - .runFold(Seq.empty[Int])((elem, acc) ⇒ elem :+ acc) + .runFold(Seq.empty[Int])((elem, acc) => elem :+ acc) Await.result(result, 3.seconds) should ===(Seq(1)) } @@ -532,7 +532,7 @@ class GraphStageDocSpec extends AkkaSpec { // tests: val result1 = Source(Vector(1, 2, 3)) .via(new TwoBuffer) - .runFold(Vector.empty[Int])((acc, n) ⇒ acc :+ n) + .runFold(Vector.empty[Int])((acc, n) => acc :+ n) Await.result(result1, 3.seconds) should ===(Vector(1, 2, 3)) diff --git a/akka-docs/src/test/scala/docs/stream/HubsDocSpec.scala b/akka-docs/src/test/scala/docs/stream/HubsDocSpec.scala index bf4337a6ce..a43e44212e 100644 --- a/akka-docs/src/test/scala/docs/stream/HubsDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/HubsDocSpec.scala @@ -61,8 +61,8 @@ class HubsDocSpec extends AkkaSpec with CompileOnlySpec { val fromProducer: Source[String, NotUsed] = runnableGraph.run() // Print out messages from the producer in two independent consumers - fromProducer.runForeach(msg ⇒ println("consumer1: " + msg)) - fromProducer.runForeach(msg ⇒ println("consumer2: " + msg)) + fromProducer.runForeach(msg => println("consumer1: " + msg)) + fromProducer.runForeach(msg => println("consumer2: " + msg)) //#broadcast-hub } @@ -110,7 +110,7 @@ class HubsDocSpec extends AkkaSpec with CompileOnlySpec { //#partition-hub // A simple producer that publishes a new "message-" every second val producer = Source.tick(1.second, 1.second, "message") - .zipWith(Source(1 to 100))((a, b) ⇒ s"$a-$b") + .zipWith(Source(1 to 100))((a, b) => s"$a-$b") // Attach a PartitionHub Sink to the producer. This will materialize to a // corresponding Source. @@ -118,7 +118,7 @@ class HubsDocSpec extends AkkaSpec with CompileOnlySpec { // value to the left is used) val runnableGraph: RunnableGraph[Source[String, NotUsed]] = producer.toMat(PartitionHub.sink( - (size, elem) ⇒ math.abs(elem.hashCode % size), + (size, elem) => math.abs(elem.hashCode % size), startAfterNrOfConsumers = 2, bufferSize = 256))(Keep.right) // By running/materializing the producer, we get back a Source, which @@ -126,8 +126,8 @@ class HubsDocSpec extends AkkaSpec with CompileOnlySpec { val fromProducer: Source[String, NotUsed] = runnableGraph.run() // Print out messages from the producer in two independent consumers - fromProducer.runForeach(msg ⇒ println("consumer1: " + msg)) - fromProducer.runForeach(msg ⇒ println("consumer2: " + msg)) + fromProducer.runForeach(msg => println("consumer1: " + msg)) + fromProducer.runForeach(msg => println("consumer2: " + msg)) //#partition-hub } @@ -135,14 +135,14 @@ class HubsDocSpec extends AkkaSpec with CompileOnlySpec { //#partition-hub-stateful // A simple producer that publishes a new "message-" every second val producer = Source.tick(1.second, 1.second, "message") - .zipWith(Source(1 to 100))((a, b) ⇒ s"$a-$b") + .zipWith(Source(1 to 100))((a, b) => s"$a-$b") // New instance of the partitioner function and its state is created // for each materialization of the PartitionHub. - def roundRobin(): (PartitionHub.ConsumerInfo, String) ⇒ Long = { + def roundRobin(): (PartitionHub.ConsumerInfo, String) => Long = { var i = -1L - (info, elem) ⇒ { + (info, elem) => { i += 1 info.consumerIdByIdx((i % info.size).toInt) } @@ -154,7 +154,7 @@ class HubsDocSpec extends AkkaSpec with CompileOnlySpec { // value to the left is used) val runnableGraph: RunnableGraph[Source[String, NotUsed]] = producer.toMat(PartitionHub.statefulSink( - () ⇒ roundRobin(), + () => roundRobin(), startAfterNrOfConsumers = 2, bufferSize = 256))(Keep.right) // By running/materializing the producer, we get back a Source, which @@ -162,8 +162,8 @@ class HubsDocSpec extends AkkaSpec with CompileOnlySpec { val fromProducer: Source[String, NotUsed] = runnableGraph.run() // Print out messages from the producer in two independent consumers - fromProducer.runForeach(msg ⇒ println("consumer1: " + msg)) - fromProducer.runForeach(msg ⇒ println("consumer2: " + msg)) + fromProducer.runForeach(msg => println("consumer1: " + msg)) + fromProducer.runForeach(msg => println("consumer2: " + msg)) //#partition-hub-stateful } @@ -175,14 +175,14 @@ class HubsDocSpec extends AkkaSpec with CompileOnlySpec { // Note that this is a moving target since the elements are consumed concurrently. val runnableGraph: RunnableGraph[Source[Int, NotUsed]] = producer.toMat(PartitionHub.statefulSink( - () ⇒ (info, elem) ⇒ info.consumerIds.minBy(id ⇒ info.queueSize(id)), + () => (info, elem) => info.consumerIds.minBy(id => info.queueSize(id)), startAfterNrOfConsumers = 2, bufferSize = 16))(Keep.right) val fromProducer: Source[Int, NotUsed] = runnableGraph.run() - fromProducer.runForeach(msg ⇒ println("consumer1: " + msg)) + fromProducer.runForeach(msg => println("consumer1: " + msg)) fromProducer.throttle(10, 100.millis) - .runForeach(msg ⇒ println("consumer2: " + msg)) + .runForeach(msg => println("consumer2: " + msg)) //#partition-hub-fastest } diff --git a/akka-docs/src/test/scala/docs/stream/IntegrationDocSpec.scala b/akka-docs/src/test/scala/docs/stream/IntegrationDocSpec.scala index 08d5b91501..7b31fb3771 100644 --- a/akka-docs/src/test/scala/docs/stream/IntegrationDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/IntegrationDocSpec.scala @@ -92,7 +92,7 @@ object IntegrationDocSpec { class DatabaseService(probe: ActorRef) extends Actor { override def receive = { - case Save(tweet: Tweet) ⇒ + case Save(tweet: Tweet) => probe ! tweet.author.handle sender() ! SaveDone } @@ -123,7 +123,7 @@ object IntegrationDocSpec { //#ask-actor class Translator extends Actor { def receive = { - case word: String ⇒ + case word: String => // ... process message val reply = word.toUpperCase sender() ! reply // reply to the ask @@ -169,14 +169,14 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { //#email-addresses-mapAsync val emailAddresses: Source[String, NotUsed] = authors - .mapAsync(4)(author ⇒ addressSystem.lookupEmail(author.handle)) - .collect { case Some(emailAddress) ⇒ emailAddress } + .mapAsync(4)(author => addressSystem.lookupEmail(author.handle)) + .collect { case Some(emailAddress) => emailAddress } //#email-addresses-mapAsync //#send-emails val sendEmails: RunnableGraph[NotUsed] = emailAddresses - .mapAsync(4)(address ⇒ { + .mapAsync(4)(address => { emailServer.send( Email(to = address, title = "Akka", body = "I like your tweet")) }) @@ -205,7 +205,7 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { // sent from stream to actor to indicate start, end or failure of stream: val InitMessage = AckingReceiver.StreamInitialized val OnCompleteMessage = AckingReceiver.StreamCompleted - val onErrorMessage = (ex: Throwable) ⇒ AckingReceiver.StreamFailure(ex) + val onErrorMessage = (ex: Throwable) => AckingReceiver.StreamFailure(ex) val probe = TestProbe() val receiver = system.actorOf( @@ -242,20 +242,20 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { import AckingReceiver._ def receive: Receive = { - case StreamInitialized ⇒ + case StreamInitialized => log.info("Stream initialized!") probe ! "Stream initialized!" sender() ! Ack // ack to allow the stream to proceed sending more elements - case el: String ⇒ + case el: String => log.info("Received element: {}", el) probe ! el sender() ! Ack // ack to allow the stream to proceed sending more elements - case StreamCompleted ⇒ + case StreamCompleted => log.info("Stream completed!") probe ! "Stream completed!" - case StreamFailure(ex) ⇒ + case StreamFailure(ex) => log.error(ex, "Stream failed!") } } @@ -272,7 +272,7 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { val emailAddresses: Source[String, NotUsed] = authors.via( - Flow[Author].mapAsync(4)(author ⇒ addressSystem.lookupEmail(author.handle)) + Flow[Author].mapAsync(4)(author => addressSystem.lookupEmail(author.handle)) .withAttributes(supervisionStrategy(resumingDecider))) //#email-addresses-mapAsync-supervision } @@ -288,12 +288,12 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { val emailAddresses: Source[String, NotUsed] = authors - .mapAsyncUnordered(4)(author ⇒ addressSystem.lookupEmail(author.handle)) - .collect { case Some(emailAddress) ⇒ emailAddress } + .mapAsyncUnordered(4)(author => addressSystem.lookupEmail(author.handle)) + .collect { case Some(emailAddress) => emailAddress } val sendEmails: RunnableGraph[NotUsed] = emailAddresses - .mapAsyncUnordered(4)(address ⇒ { + .mapAsyncUnordered(4)(address => { emailServer.send( Email(to = address, title = "Akka", body = "I like your tweet")) }) @@ -320,15 +320,15 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { val authors = tweets.filter(_.hashtags.contains(akkaTag)).map(_.author) val phoneNumbers = - authors.mapAsync(4)(author ⇒ addressSystem.lookupPhoneNumber(author.handle)) - .collect { case Some(phoneNo) ⇒ phoneNo } + authors.mapAsync(4)(author => addressSystem.lookupPhoneNumber(author.handle)) + .collect { case Some(phoneNo) => phoneNo } //#blocking-mapAsync val blockingExecutionContext = system.dispatchers.lookup("blocking-dispatcher") val sendTextMessages: RunnableGraph[NotUsed] = phoneNumbers - .mapAsync(4)(phoneNo ⇒ { + .mapAsync(4)(phoneNo => { Future { smsServer.send( TextMessage(to = phoneNo, body = "I like your tweet")) @@ -357,12 +357,12 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { val authors = tweets.filter(_.hashtags.contains(akkaTag)).map(_.author) val phoneNumbers = - authors.mapAsync(4)(author ⇒ addressSystem.lookupPhoneNumber(author.handle)) - .collect { case Some(phoneNo) ⇒ phoneNo } + authors.mapAsync(4)(author => addressSystem.lookupPhoneNumber(author.handle)) + .collect { case Some(phoneNo) => phoneNo } //#blocking-map val send = Flow[String] - .map { phoneNo ⇒ + .map { phoneNo => smsServer.send(TextMessage(to = phoneNo, body = "I like your tweet")) } .withAttributes(ActorAttributes.dispatcher("blocking-dispatcher")) @@ -393,7 +393,7 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { implicit val timeout = Timeout(3.seconds) val saveTweets: RunnableGraph[NotUsed] = akkaTweets - .mapAsync(4)(tweet ⇒ database ? Save(tweet)) + .mapAsync(4)(tweet => database ? Save(tweet)) .to(Sink.ignore) //#save-tweets @@ -423,9 +423,9 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { ActorMaterializerSettings(system).withInputBuffer(initialSize = 4, maxSize = 4)) Source(List("a", "B", "C", "D", "e", "F", "g", "H", "i", "J")) - .map(elem ⇒ { println(s"before: $elem"); elem }) + .map(elem => { println(s"before: $elem"); elem }) .mapAsync(4)(service.convert) - .runForeach(elem ⇒ println(s"after: $elem")) + .runForeach(elem => println(s"after: $elem")) //#sometimes-slow-mapAsync probe.expectMsg("after: A") @@ -455,9 +455,9 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { ActorMaterializerSettings(system).withInputBuffer(initialSize = 4, maxSize = 4)) Source(List("a", "B", "C", "D", "e", "F", "g", "H", "i", "J")) - .map(elem ⇒ { println(s"before: $elem"); elem }) + .map(elem => { println(s"before: $elem"); elem }) .mapAsyncUnordered(4)(service.convert) - .runForeach(elem ⇒ println(s"after: $elem")) + .runForeach(elem => println(s"after: $elem")) //#sometimes-slow-mapAsyncUnordered probe.receiveN(10).toSet should be(Set( @@ -481,19 +481,19 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { val queue = Source .queue[Int](bufferSize, OverflowStrategy.backpressure) .throttle(elementsToProcess, 3.second) - .map(x ⇒ x * x) - .toMat(Sink.foreach(x ⇒ println(s"completed $x")))(Keep.left) + .map(x => x * x) + .toMat(Sink.foreach(x => println(s"completed $x")))(Keep.left) .run() val source = Source(1 to 10) implicit val ec = system.dispatcher - source.mapAsync(1)(x ⇒ { + source.mapAsync(1)(x => { queue.offer(x).map { - case QueueOfferResult.Enqueued ⇒ println(s"enqueued $x") - case QueueOfferResult.Dropped ⇒ println(s"dropped $x") - case QueueOfferResult.Failure(ex) ⇒ println(s"Offer failed ${ex.getMessage}") - case QueueOfferResult.QueueClosed ⇒ println("Source Queue closed") + case QueueOfferResult.Enqueued => println(s"enqueued $x") + case QueueOfferResult.Dropped => println(s"dropped $x") + case QueueOfferResult.Failure(ex) => println(s"Offer failed ${ex.getMessage}") + case QueueOfferResult.QueueClosed => println("Source Queue closed") } }).runWith(Sink.ignore) //#source-queue @@ -505,8 +505,8 @@ class IntegrationDocSpec extends AkkaSpec(IntegrationDocSpec.config) { val ref = Source .actorRef[Int](bufferSize, OverflowStrategy.fail) // note: backpressure is not supported - .map(x ⇒ x * x) - .toMat(Sink.foreach(x ⇒ println(s"completed $x")))(Keep.left) + .map(x => x * x) + .toMat(Sink.foreach(x => println(s"completed $x")))(Keep.left) .run() ref ! 1 diff --git a/akka-docs/src/test/scala/docs/stream/MigrationsScala.scala b/akka-docs/src/test/scala/docs/stream/MigrationsScala.scala index fda0eec515..6d17de0887 100644 --- a/akka-docs/src/test/scala/docs/stream/MigrationsScala.scala +++ b/akka-docs/src/test/scala/docs/stream/MigrationsScala.scala @@ -16,7 +16,7 @@ class MigrationsScala extends AkkaSpec { Flow[Int].expand(Iterator.continually(_)) //#expand-continually //#expand-state - Flow[Int].expand(i ⇒ { + Flow[Int].expand(i => { var state = 0 Iterator.continually({ state += 1 diff --git a/akka-docs/src/test/scala/docs/stream/QuickStartDocSpec.scala b/akka-docs/src/test/scala/docs/stream/QuickStartDocSpec.scala index 69c73c07b2..6085d95e95 100644 --- a/akka-docs/src/test/scala/docs/stream/QuickStartDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/QuickStartDocSpec.scala @@ -43,15 +43,15 @@ class QuickStartDocSpec extends WordSpec with BeforeAndAfterAll with ScalaFuture //#create-source //#run-source - source.runForeach(i ⇒ println(i))(materializer) + source.runForeach(i => println(i))(materializer) //#run-source //#transform-source - val factorials = source.scan(BigInt(1))((acc, next) ⇒ acc * next) + val factorials = source.scan(BigInt(1))((acc, next) => acc * next) val result: Future[IOResult] = factorials - .map(num ⇒ ByteString(s"$num\n")) + .map(num => ByteString(s"$num\n")) .runWith(FileIO.toPath(Paths.get("factorials.txt"))) //#transform-source @@ -61,7 +61,7 @@ class QuickStartDocSpec extends WordSpec with BeforeAndAfterAll with ScalaFuture //#add-streams factorials - .zipWith(Source(0 to 100))((num, idx) ⇒ s"$idx! = $num") + .zipWith(Source(0 to 100))((num, idx) => s"$idx! = $num") .throttle(1, 1.second) //#add-streams .take(3) @@ -70,10 +70,10 @@ class QuickStartDocSpec extends WordSpec with BeforeAndAfterAll with ScalaFuture //#add-streams //#run-source-and-terminate - val done: Future[Done] = source.runForeach(i ⇒ println(i))(materializer) + val done: Future[Done] = source.runForeach(i => println(i))(materializer) implicit val ec = system.dispatcher - done.onComplete(_ ⇒ system.terminate()) + done.onComplete(_ => system.terminate()) //#run-source-and-terminate done.futureValue @@ -82,7 +82,7 @@ class QuickStartDocSpec extends WordSpec with BeforeAndAfterAll with ScalaFuture //#transform-sink def lineSink(filename: String): Sink[String, Future[IOResult]] = Flow[String] - .map(s ⇒ ByteString(s + "\n")) + .map(s => ByteString(s + "\n")) .toMat(FileIO.toPath(Paths.get(filename)))(Keep.right) //#transform-sink diff --git a/akka-docs/src/test/scala/docs/stream/RateTransformationDocSpec.scala b/akka-docs/src/test/scala/docs/stream/RateTransformationDocSpec.scala index 919649a379..36d4465df8 100644 --- a/akka-docs/src/test/scala/docs/stream/RateTransformationDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/RateTransformationDocSpec.scala @@ -24,15 +24,15 @@ class RateTransformationDocSpec extends AkkaSpec { //#conflate-summarize val statsFlow = Flow[Double] .conflateWithSeed(immutable.Seq(_))(_ :+ _) - .map { s ⇒ + .map { s => val μ = s.sum / s.size - val se = s.map(x ⇒ pow(x - μ, 2)) + val se = s.map(x => pow(x - μ, 2)) val σ = sqrt(se.sum / se.size) (σ, μ, s.size) } //#conflate-summarize - val fut = Source.fromIterator(() ⇒ Iterator.continually(Random.nextGaussian)) + val fut = Source.fromIterator(() => Iterator.continually(Random.nextGaussian)) .via(statsFlow) .grouped(10) .runWith(Sink.head) @@ -45,8 +45,8 @@ class RateTransformationDocSpec extends AkkaSpec { val p = 0.01 val sampleFlow = Flow[Double] .conflateWithSeed(immutable.Seq(_)) { - case (acc, elem) if Random.nextDouble < p ⇒ acc :+ elem - case (acc, _) ⇒ acc + case (acc, elem) if Random.nextDouble < p => acc :+ elem + case (acc, _) => acc } .mapConcat(identity) //#conflate-sample @@ -97,11 +97,11 @@ class RateTransformationDocSpec extends AkkaSpec { "extrapolate should track drift" in { //#extrapolate-drift val driftFlow = Flow[Double].map(_ -> 0) - .extrapolate[(Double, Int)] { case (i, _) ⇒ Iterator.from(1).map(i -> _) } + .extrapolate[(Double, Int)] { case (i, _) => Iterator.from(1).map(i -> _) } //#extrapolate-drift val latch = TestLatch(2) - val realDriftFlow = Flow[Double].map(d ⇒ { latch.countDown(); d -> 0; }) - .extrapolate[(Double, Int)] { case (d, _) ⇒ latch.countDown(); Iterator.from(1).map(d -> _) } + val realDriftFlow = Flow[Double].map(d => { latch.countDown(); d -> 0; }) + .extrapolate[(Double, Int)] { case (d, _) => latch.countDown(); Iterator.from(1).map(d -> _) } val (pub, sub) = TestSource.probe[Double] .via(realDriftFlow) @@ -123,11 +123,11 @@ class RateTransformationDocSpec extends AkkaSpec { "expand should track drift" in { //#expand-drift val driftFlow = Flow[Double] - .expand(i ⇒ Iterator.from(0).map(i -> _)) + .expand(i => Iterator.from(0).map(i -> _)) //#expand-drift val latch = TestLatch(2) val realDriftFlow = Flow[Double] - .expand(d ⇒ { latch.countDown(); Iterator.from(0).map(d -> _) }) + .expand(d => { latch.countDown(); Iterator.from(0).map(d -> _) }) val (pub, sub) = TestSource.probe[Double] .via(realDriftFlow) diff --git a/akka-docs/src/test/scala/docs/stream/ReactiveStreamsDocSpec.scala b/akka-docs/src/test/scala/docs/stream/ReactiveStreamsDocSpec.scala index 13ad14b4f0..bec12ec8de 100644 --- a/akka-docs/src/test/scala/docs/stream/ReactiveStreamsDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/ReactiveStreamsDocSpec.scala @@ -142,7 +142,7 @@ class ReactiveStreamsDocSpec extends AkkaSpec { // An example Processor factory def createProcessor: Processor[Int, Int] = Flow[Int].toProcessor.run() - val flow: Flow[Int, Int, NotUsed] = Flow.fromProcessor(() ⇒ createProcessor) + val flow: Flow[Int, Int, NotUsed] = Flow.fromProcessor(() => createProcessor) //#use-processor } diff --git a/akka-docs/src/test/scala/docs/stream/RestartDocSpec.scala b/akka-docs/src/test/scala/docs/stream/RestartDocSpec.scala index 3f90169535..0676f229ce 100644 --- a/akka-docs/src/test/scala/docs/stream/RestartDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/RestartDocSpec.scala @@ -40,7 +40,7 @@ class RestartDocSpec extends AkkaSpec with CompileOnlySpec { maxBackoff = 30.seconds, randomFactor = 0.2, // adds 20% "noise" to vary the intervals slightly maxRestarts = 20 // limits the amount of restarts to 20 - ) { () ⇒ + ) { () => // Create a source from a future of a source Source.fromFutureSource { // Make a single request with akka-http @@ -56,7 +56,7 @@ class RestartDocSpec extends AkkaSpec with CompileOnlySpec { //#with-kill-switch val killSwitch = restartSource .viaMat(KillSwitches.single)(Keep.right) - .toMat(Sink.foreach(event ⇒ println(s"Got event: $event")))(Keep.left) + .toMat(Sink.foreach(event => println(s"Got event: $event")))(Keep.left) .run() doSomethingElse() diff --git a/akka-docs/src/test/scala/docs/stream/StreamBuffersRateSpec.scala b/akka-docs/src/test/scala/docs/stream/StreamBuffersRateSpec.scala index a24e6d2d3c..bcf5f29155 100644 --- a/akka-docs/src/test/scala/docs/stream/StreamBuffersRateSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/StreamBuffersRateSpec.scala @@ -16,9 +16,9 @@ class StreamBuffersRateSpec extends AkkaSpec { def println(s: Any) = () //#pipelining Source(1 to 3) - .map { i ⇒ println(s"A: $i"); i }.async - .map { i ⇒ println(s"B: $i"); i }.async - .map { i ⇒ println(s"C: $i"); i }.async + .map { i => println(s"A: $i"); i }.async + .map { i => println(s"B: $i"); i }.async + .map { i => println(s"C: $i"); i }.async .runWith(Sink.ignore) //#pipelining } @@ -44,16 +44,16 @@ class StreamBuffersRateSpec extends AkkaSpec { import scala.concurrent.duration._ case class Tick() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ // this is the asynchronous stage in this graph - val zipper = b.add(ZipWith[Tick, Int, Int]((tick, count) ⇒ count).async) + val zipper = b.add(ZipWith[Tick, Int, Int]((tick, count) => count).async) Source.tick(initialDelay = 3.second, interval = 3.second, Tick()) ~> zipper.in0 Source.tick(initialDelay = 1.second, interval = 1.second, "message!") - .conflateWithSeed(seed = (_) ⇒ 1)((count, _) ⇒ count + 1) ~> zipper.in1 + .conflateWithSeed(seed = (_) => 1)((count, _) => count + 1) ~> zipper.in1 zipper.out ~> Sink.foreach(println) ClosedShape diff --git a/akka-docs/src/test/scala/docs/stream/StreamPartialGraphDSLDocSpec.scala b/akka-docs/src/test/scala/docs/stream/StreamPartialGraphDSLDocSpec.scala index c76d64feee..9c5edf753e 100644 --- a/akka-docs/src/test/scala/docs/stream/StreamPartialGraphDSLDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/StreamPartialGraphDSLDocSpec.scala @@ -20,7 +20,7 @@ class StreamPartialGraphDSLDocSpec extends AkkaSpec { "build with open ports" in { //#simple-partial-graph-dsl - val pickMaxOfThree = GraphDSL.create() { implicit b ⇒ + val pickMaxOfThree = GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val zip1 = b.add(ZipWith[Int, Int, Int](math.max _)) @@ -32,7 +32,7 @@ class StreamPartialGraphDSLDocSpec extends AkkaSpec { val resultSink = Sink.head[Int] - val g = RunnableGraph.fromGraph(GraphDSL.create(resultSink) { implicit b ⇒ sink ⇒ + val g = RunnableGraph.fromGraph(GraphDSL.create(resultSink) { implicit b => sink => import GraphDSL.Implicits._ // importing the partial graph will return its shape (inlets & outlets) @@ -52,12 +52,12 @@ class StreamPartialGraphDSLDocSpec extends AkkaSpec { "build source from partial graph" in { //#source-from-partial-graph-dsl - val pairs = Source.fromGraph(GraphDSL.create() { implicit b ⇒ + val pairs = Source.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ // prepare graph elements val zip = b.add(Zip[Int, Int]()) - def ints = Source.fromIterator(() ⇒ Iterator.from(1)) + def ints = Source.fromIterator(() => Iterator.from(1)) // connect the graph ints.filter(_ % 2 != 0) ~> zip.in0 @@ -75,7 +75,7 @@ class StreamPartialGraphDSLDocSpec extends AkkaSpec { "build flow from partial graph" in { //#flow-from-partial-graph-dsl val pairUpWithToString = - Flow.fromGraph(GraphDSL.create() { implicit b ⇒ + Flow.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ // prepare graph elements @@ -117,7 +117,7 @@ class StreamPartialGraphDSLDocSpec extends AkkaSpec { val actorRef: ActorRef = testActor //#sink-combine val sendRmotely = Sink.actorRef(actorRef, "Done") - val localProcessing = Sink.foreach[Int](_ ⇒ /* do something useful */ ()) + val localProcessing = Sink.foreach[Int](_ => /* do something useful */ ()) val sink = Sink.combine(sendRmotely, localProcessing)(Broadcast[Int](_)) diff --git a/akka-docs/src/test/scala/docs/stream/StreamTestKitDocSpec.scala b/akka-docs/src/test/scala/docs/stream/StreamTestKitDocSpec.scala index 200417ecf4..4ec39bd90b 100644 --- a/akka-docs/src/test/scala/docs/stream/StreamTestKitDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/StreamTestKitDocSpec.scala @@ -138,7 +138,7 @@ class StreamTestKitDocSpec extends AkkaSpec { "test source and a sink" in { import system.dispatcher //#test-source-and-sink - val flowUnderTest = Flow[Int].mapAsyncUnordered(2) { sleep ⇒ + val flowUnderTest = Flow[Int].mapAsyncUnordered(2) { sleep => pattern.after(10.millis * sleep, using = system.scheduler)(Future.successful(sleep)) } diff --git a/akka-docs/src/test/scala/docs/stream/SubstreamDocSpec.scala b/akka-docs/src/test/scala/docs/stream/SubstreamDocSpec.scala index 8785d5b388..938b4db610 100644 --- a/akka-docs/src/test/scala/docs/stream/SubstreamDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/SubstreamDocSpec.scala @@ -57,7 +57,7 @@ class SubstreamDocSpec extends AkkaSpec { val charCount = Source(text.toList) .splitAfter { _ == '\n' } .filter(_ != '\n') - .map(_ ⇒ 1) + .map(_ => 1) .reduce(_ + _) .to(Sink.foreach(println)) .run() @@ -67,13 +67,13 @@ class SubstreamDocSpec extends AkkaSpec { "generate substreams by flatMapConcat and flatMapMerge" in { //#flatMapConcat Source(1 to 2) - .flatMapConcat(i ⇒ Source(List.fill(3)(i))) + .flatMapConcat(i => Source(List.fill(3)(i))) .runWith(Sink.ignore) //#flatMapConcat //#flatMapMerge Source(1 to 2) - .flatMapMerge(2, i ⇒ Source(List.fill(3)(i))) + .flatMapMerge(2, i => Source(List.fill(3)(i))) .runWith(Sink.ignore) //#flatMapMerge } diff --git a/akka-docs/src/test/scala/docs/stream/TwitterStreamQuickstartDocSpec.scala b/akka-docs/src/test/scala/docs/stream/TwitterStreamQuickstartDocSpec.scala index d70943ee2a..ea7bf4320f 100644 --- a/akka-docs/src/test/scala/docs/stream/TwitterStreamQuickstartDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/TwitterStreamQuickstartDocSpec.scala @@ -32,7 +32,7 @@ object TwitterStreamQuickstartDocSpec { final case class Tweet(author: Author, timestamp: Long, body: String) { def hashtags: Set[Hashtag] = body.split(" ").collect { - case t if t.startsWith("#") ⇒ Hashtag(t.replaceAll("[^#\\w]", "")) + case t if t.startsWith("#") => Hashtag(t.replaceAll("[^#\\w]", "")) }.toSet } @@ -100,7 +100,7 @@ class TwitterStreamQuickstartDocSpec extends AkkaSpec { trait Example3 { //#authors-collect val authors: Source[Author, NotUsed] = - tweets.collect { case t if t.hashtags.contains(akkaTag) ⇒ t.author } + tweets.collect { case t if t.hashtags.contains(akkaTag) => t.author } //#authors-collect } @@ -185,8 +185,8 @@ class TwitterStreamQuickstartDocSpec extends AkkaSpec { //#backpressure-by-readline val completion: Future[Done] = Source(1 to 10) - .map(i ⇒ { println(s"map => $i"); i }) - .runForeach { i ⇒ readLine(s"Element = $i; continue reading? [press enter]\n") } + .map(i => { println(s"map => $i"); i }) + .runForeach { i => readLine(s"Element = $i; continue reading? [press enter]\n") } Await.ready(completion, 1.minute) //#backpressure-by-readline @@ -195,7 +195,7 @@ class TwitterStreamQuickstartDocSpec extends AkkaSpec { "count elements on finite stream" in { //#tweets-fold-count - val count: Flow[Tweet, Int, NotUsed] = Flow[Tweet].map(_ ⇒ 1) + val count: Flow[Tweet, Int, NotUsed] = Flow[Tweet].map(_ => 1) val sumSink: Sink[Int, Future[Int]] = Sink.fold[Int, Int](0)(_ + _) @@ -206,12 +206,12 @@ class TwitterStreamQuickstartDocSpec extends AkkaSpec { val sum: Future[Int] = counterGraph.run() - sum.foreach(c ⇒ println(s"Total tweets processed: $c")) + sum.foreach(c => println(s"Total tweets processed: $c")) //#tweets-fold-count new AnyRef { //#tweets-fold-count-oneline - val sum: Future[Int] = tweets.map(t ⇒ 1).runWith(sumSink) + val sum: Future[Int] = tweets.map(t => 1).runWith(sumSink) //#tweets-fold-count-oneline } } @@ -224,7 +224,7 @@ class TwitterStreamQuickstartDocSpec extends AkkaSpec { val counterRunnableGraph: RunnableGraph[Future[Int]] = tweetsInMinuteFromNow .filter(_.hashtags contains akkaTag) - .map(t ⇒ 1) + .map(t => 1) .toMat(sumSink)(Keep.right) // materialize the stream once in the morning @@ -236,7 +236,7 @@ class TwitterStreamQuickstartDocSpec extends AkkaSpec { val sum: Future[Int] = counterRunnableGraph.run() - sum.map { c ⇒ println(s"Total tweets processed: $c") } + sum.map { c => println(s"Total tweets processed: $c") } } } diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeAdhocSource.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeAdhocSource.scala index 6f0eb258d1..c5f4a1713d 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeAdhocSource.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeAdhocSource.scala @@ -19,9 +19,9 @@ class RecipeAdhocSource extends RecipeSpec { //#adhoc-source def adhocSource[T](source: Source[T, _], timeout: FiniteDuration, maxRetries: Int): Source[T, _] = Source.lazily( - () ⇒ source.backpressureTimeout(timeout).recoverWithRetries(maxRetries, { - case t: TimeoutException ⇒ - Source.lazily(() ⇒ source.backpressureTimeout(timeout)).mapMaterializedValue(_ ⇒ NotUsed) + () => source.backpressureTimeout(timeout).recoverWithRetries(maxRetries, { + case t: TimeoutException => + Source.lazily(() => source.backpressureTimeout(timeout)).mapMaterializedValue(_ => NotUsed) }) ) //#adhoc-source @@ -29,7 +29,7 @@ class RecipeAdhocSource extends RecipeSpec { "Recipe for adhoc source" must { "not start the source if there is no demand" taggedAs TimingTest in { val isStarted = new AtomicBoolean() - adhocSource(Source.empty.mapMaterializedValue(_ ⇒ isStarted.set(true)), 200.milliseconds, 3) + adhocSource(Source.empty.mapMaterializedValue(_ => isStarted.set(true)), 200.milliseconds, 3) .runWith(TestSink.probe[Int]) Thread.sleep(300) isStarted.get() should be(false) @@ -44,7 +44,7 @@ class RecipeAdhocSource extends RecipeSpec { "shut down the source when the next demand times out" taggedAs TimingTest in { val shutdown = Promise[Done]() val sink = adhocSource( - Source.repeat("a").watchTermination() { (_, term) ⇒ + Source.repeat("a").watchTermination() { (_, term) => shutdown.completeWith(term) }, 200.milliseconds, 3) .runWith(TestSink.probe[String]) @@ -57,7 +57,7 @@ class RecipeAdhocSource extends RecipeSpec { "not shut down the source when there are still demands" taggedAs TimingTest in { val shutdown = Promise[Done]() val sink = adhocSource( - Source.repeat("a").watchTermination() { (_, term) ⇒ + Source.repeat("a").watchTermination() { (_, term) => shutdown.completeWith(term) }, 200.milliseconds, 3) .runWith(TestSink.probe[String]) @@ -81,10 +81,10 @@ class RecipeAdhocSource extends RecipeSpec { val startedCount = new AtomicInteger(0) val source = Source - .empty.mapMaterializedValue(_ ⇒ startedCount.incrementAndGet()) + .empty.mapMaterializedValue(_ => startedCount.incrementAndGet()) .concat(Source.repeat("a")) - val sink = adhocSource(source.watchTermination() { (_, term) ⇒ + val sink = adhocSource(source.watchTermination() { (_, term) => shutdown.completeWith(term) }, 200.milliseconds, 3) .runWith(TestSink.probe[String]) @@ -100,10 +100,10 @@ class RecipeAdhocSource extends RecipeSpec { val startedCount = new AtomicInteger(0) val source = Source - .empty.mapMaterializedValue(_ ⇒ startedCount.incrementAndGet()) + .empty.mapMaterializedValue(_ => startedCount.incrementAndGet()) .concat(Source.repeat("a")) - val sink = adhocSource(source.watchTermination() { (_, term) ⇒ + val sink = adhocSource(source.watchTermination() { (_, term) => shutdown.completeWith(term) }, 200.milliseconds, 3) .runWith(TestSink.probe[String]) diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeDroppyBroadcast.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeDroppyBroadcast.scala index 073c06111e..15fd0cb416 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeDroppyBroadcast.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeDroppyBroadcast.scala @@ -24,7 +24,7 @@ class RecipeDroppyBroadcast extends RecipeSpec { val mySink3 = Sink.fromSubscriber(sub3) //#droppy-bcast - val graph = RunnableGraph.fromGraph(GraphDSL.create(mySink1, mySink2, mySink3)((_, _, _)) { implicit b ⇒ (sink1, sink2, sink3) ⇒ + val graph = RunnableGraph.fromGraph(GraphDSL.create(mySink1, mySink2, mySink3)((_, _, _)) { implicit b => (sink1, sink2, sink3) => import GraphDSL.Implicits._ val bcast = b.add(Broadcast[Int](3)) @@ -40,7 +40,7 @@ class RecipeDroppyBroadcast extends RecipeSpec { graph.run() sub3.request(100) - for (i ← 1 to 100) { + for (i <- 1 to 100) { pub.sendNext(i) sub3.expectNext(i) } @@ -50,7 +50,7 @@ class RecipeDroppyBroadcast extends RecipeSpec { sub1.expectSubscription().request(10) sub2.expectSubscription().request(10) - for (i ← 91 to 100) { + for (i <- 91 to 100) { sub1.expectNext(i) sub2.expectNext(i) } diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeGlobalRateLimit.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeGlobalRateLimit.scala index 570317e885..649b10789d 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeGlobalRateLimit.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeGlobalRateLimit.scala @@ -49,19 +49,19 @@ class RecipeGlobalRateLimit extends RecipeSpec { override def receive: Receive = open val open: Receive = { - case ReplenishTokens ⇒ + case ReplenishTokens => permitTokens = math.min(permitTokens + tokenRefreshAmount, maxAvailableTokens) - case WantToPass ⇒ + case WantToPass => permitTokens -= 1 sender() ! MayPass if (permitTokens == 0) context.become(closed) } val closed: Receive = { - case ReplenishTokens ⇒ + case ReplenishTokens => permitTokens = math.min(permitTokens + tokenRefreshAmount, maxAvailableTokens) releaseWaiting() - case WantToPass ⇒ + case WantToPass => waitQueue = waitQueue.enqueue(sender()) } @@ -86,11 +86,11 @@ class RecipeGlobalRateLimit extends RecipeSpec { def limitGlobal[T](limiter: ActorRef, maxAllowedWait: FiniteDuration): Flow[T, T, NotUsed] = { import akka.pattern.ask import akka.util.Timeout - Flow[T].mapAsync(4)((element: T) ⇒ { + Flow[T].mapAsync(4)((element: T) => { import system.dispatcher implicit val triggerTimeout = Timeout(maxAllowedWait) val limiterTriggerFuture = limiter ? Limiter.WantToPass - limiterTriggerFuture.map((_) ⇒ element) + limiterTriggerFuture.map((_) => element) }) } @@ -99,12 +99,12 @@ class RecipeGlobalRateLimit extends RecipeSpec { // Use a large period and emulate the timer by hand instead val limiter = system.actorOf(Limiter.props(2, 100.days, 1), "limiter") - val source1 = Source.fromIterator(() ⇒ Iterator.continually("E1")).via(limitGlobal(limiter, 2.seconds.dilated)) - val source2 = Source.fromIterator(() ⇒ Iterator.continually("E2")).via(limitGlobal(limiter, 2.seconds.dilated)) + val source1 = Source.fromIterator(() => Iterator.continually("E1")).via(limitGlobal(limiter, 2.seconds.dilated)) + val source2 = Source.fromIterator(() => Iterator.continually("E2")).via(limitGlobal(limiter, 2.seconds.dilated)) val probe = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val merge = b.add(Merge[String](2)) source1 ~> merge ~> Sink.fromSubscriber(probe) @@ -123,7 +123,7 @@ class RecipeGlobalRateLimit extends RecipeSpec { probe.expectNoMsg(500.millis) var resultSet = Set.empty[String] - for (_ ← 1 to 100) { + for (_ <- 1 to 100) { limiter ! Limiter.ReplenishTokens resultSet += probe.expectNext() } diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeKeepAlive.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeKeepAlive.scala index fce5ab73a1..109e5d7bc4 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeKeepAlive.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeKeepAlive.scala @@ -18,7 +18,7 @@ class RecipeKeepAlive extends RecipeSpec { //#inject-keepalive import scala.concurrent.duration._ val injectKeepAlive: Flow[ByteString, ByteString, NotUsed] = - Flow[ByteString].keepAlive(1.second, () ⇒ keepaliveMessage) + Flow[ByteString].keepAlive(1.second, () => keepaliveMessage) //#inject-keepalive // No need to test, this is a built-in stage with proper tests diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeLoggingElements.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeLoggingElements.scala index 2ac63741a4..b0dfe241bb 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeLoggingElements.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeLoggingElements.scala @@ -20,7 +20,7 @@ class RecipeLoggingElements extends RecipeSpec { val mySource = Source(List("1", "2", "3")) //#println-debug - val loggedSource = mySource.map { elem ⇒ println(elem); elem } + val loggedSource = mySource.map { elem => println(elem); elem } //#println-debug loggedSource.runWith(Sink.ignore) diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeManualTrigger.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeManualTrigger.scala index 6d0815d31e..37f8d88051 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeManualTrigger.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeManualTrigger.scala @@ -23,12 +23,12 @@ class RecipeManualTrigger extends RecipeSpec { val sink = Sink.fromSubscriber(sub) //#manually-triggered-stream - val graph = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder ⇒ + val graph = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder => import GraphDSL.Implicits._ val zip = builder.add(Zip[Message, Trigger]()) elements ~> zip.in0 triggerSource ~> zip.in1 - zip.out ~> Flow[(Message, Trigger)].map { case (msg, trigger) ⇒ msg } ~> sink + zip.out ~> Flow[(Message, Trigger)].map { case (msg, trigger) => msg } ~> sink ClosedShape }) //#manually-triggered-stream @@ -62,9 +62,9 @@ class RecipeManualTrigger extends RecipeSpec { val sink = Sink.fromSubscriber(sub) //#manually-triggered-stream-zipwith - val graph = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder ⇒ + val graph = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder => import GraphDSL.Implicits._ - val zip = builder.add(ZipWith((msg: Message, trigger: Trigger) ⇒ msg)) + val zip = builder.add(ZipWith((msg: Message, trigger: Trigger) => msg)) elements ~> zip.in0 triggerSource ~> zip.in1 diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeMissedTicks.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeMissedTicks.scala index 59e0153e51..afce91828c 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeMissedTicks.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeMissedTicks.scala @@ -25,13 +25,13 @@ class RecipeMissedTicks extends RecipeSpec { //#missed-ticks val missedTicks: Flow[Tick, Int, NotUsed] = - Flow[Tick].conflateWithSeed(seed = (_) ⇒ 0)( - (missedTicks, tick) ⇒ missedTicks + 1) + Flow[Tick].conflateWithSeed(seed = (_) => 0)( + (missedTicks, tick) => missedTicks + 1) //#missed-ticks val latch = TestLatch(3) val realMissedTicks: Flow[Tick, Int, NotUsed] = - Flow[Tick].conflateWithSeed(seed = (_) ⇒ 0)( - (missedTicks, tick) ⇒ { latch.countDown(); missedTicks + 1 }) + Flow[Tick].conflateWithSeed(seed = (_) => 0)( + (missedTicks, tick) => { latch.countDown(); missedTicks + 1 }) tickStream.via(realMissedTicks).to(sink).run() diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeMultiGroupBy.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeMultiGroupBy.scala index 930e446bf5..258053d17b 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeMultiGroupBy.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeMultiGroupBy.scala @@ -20,15 +20,15 @@ class RecipeMultiGroupBy extends RecipeSpec { case class Topic(name: String) val elems = Source(List("1: a", "1: b", "all: c", "all: d", "1: e")) - val extractTopics = { msg: Message ⇒ + val extractTopics = { msg: Message => if (msg.startsWith("1")) List(Topic("1")) else List(Topic("1"), Topic("2")) } //#multi-groupby - val topicMapper: (Message) ⇒ immutable.Seq[Topic] = extractTopics + val topicMapper: (Message) => immutable.Seq[Topic] = extractTopics - val messageAndTopic: Source[(Message, Topic), NotUsed] = elems.mapConcat { msg: Message ⇒ + val messageAndTopic: Source[(Message, Topic), NotUsed] = elems.mapConcat { msg: Message => val topicsForMessage = topicMapper(msg) // Create a (Msg, Topic) pair for each of the topics // the message belongs to @@ -37,7 +37,7 @@ class RecipeMultiGroupBy extends RecipeSpec { val multiGroups = messageAndTopic .groupBy(2, _._2).map { - case (msg, topic) ⇒ + case (msg, topic) => // do what needs to be done //#multi-groupby (msg, topic) @@ -48,7 +48,7 @@ class RecipeMultiGroupBy extends RecipeSpec { val result = multiGroups .grouped(10) .mergeSubstreams - .map(g ⇒ g.head._2.name + g.map(_._1).mkString("[", ", ", "]")) + .map(g => g.head._2.name + g.map(_._1).mkString("[", ", ", "]")) .limit(10) .runWith(Sink.seq) diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeReduceByKey.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeReduceByKey.scala index 9618d13962..d1b883c07a 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeReduceByKey.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeReduceByKey.scala @@ -26,7 +26,7 @@ class RecipeReduceByKey extends RecipeSpec { //transform each element to pair with number of words in it .map(_ -> 1) // add counting logic to the streams - .reduce((l, r) ⇒ (l._1, l._2 + r._2)) + .reduce((l, r) => (l._1, l._2 + r._2)) // get a stream of word counts .mergeSubstreams //#word-count @@ -47,21 +47,21 @@ class RecipeReduceByKey extends RecipeSpec { //#reduce-by-key-general def reduceByKey[In, K, Out]( maximumGroupSize: Int, - groupKey: (In) ⇒ K, - map: (In) ⇒ Out)(reduce: (Out, Out) ⇒ Out): Flow[In, (K, Out), NotUsed] = { + groupKey: (In) => K, + map: (In) => Out)(reduce: (Out, Out) => Out): Flow[In, (K, Out), NotUsed] = { Flow[In] .groupBy[K](maximumGroupSize, groupKey) - .map(e ⇒ groupKey(e) -> map(e)) - .reduce((l, r) ⇒ l._1 -> reduce(l._2, r._2)) + .map(e => groupKey(e) -> map(e)) + .reduce((l, r) => l._1 -> reduce(l._2, r._2)) .mergeSubstreams } val wordCounts = words.via( reduceByKey( MaximumDistinctWords, - groupKey = (word: String) ⇒ word, - map = (word: String) ⇒ 1)((left: Int, right: Int) ⇒ left + right)) + groupKey = (word: String) => word, + map = (word: String) => 1)((left: Int, right: Int) => left + right)) //#reduce-by-key-general Await.result(wordCounts.limit(10).runWith(Sink.seq), 3.seconds).toSet should be(Set( diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeSimpleDrop.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeSimpleDrop.scala index 6b8c3dbf26..a4b7c79f85 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeSimpleDrop.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeSimpleDrop.scala @@ -19,11 +19,11 @@ class RecipeSimpleDrop extends RecipeSpec { //#simple-drop val droppyStream: Flow[Message, Message, NotUsed] = - Flow[Message].conflate((lastMessage, newMessage) ⇒ newMessage) + Flow[Message].conflate((lastMessage, newMessage) => newMessage) //#simple-drop val latch = TestLatch(2) val realDroppyStream = - Flow[Message].conflate((lastMessage, newMessage) ⇒ { latch.countDown(); newMessage }) + Flow[Message].conflate((lastMessage, newMessage) => { latch.countDown(); newMessage }) val pub = TestPublisher.probe[Message]() val sub = TestSubscriber.manualProbe[Message]() diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeSourceFromFunction.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeSourceFromFunction.scala index 52f25b27e5..43412607f4 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeSourceFromFunction.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeSourceFromFunction.scala @@ -17,7 +17,7 @@ class RecipeSourceFromFunction extends RecipeSpec { def builderFunction(): String = UUID.randomUUID.toString //#source-from-function - val source = Source.repeat(NotUsed).map(_ ⇒ builderFunction()) + val source = Source.repeat(NotUsed).map(_ => builderFunction()) //#source-from-function val f = source.take(2).runWith(Sink.seq) diff --git a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeWorkerPool.scala b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeWorkerPool.scala index 8c87cad634..d15851ca37 100644 --- a/akka-docs/src/test/scala/docs/stream/cookbook/RecipeWorkerPool.scala +++ b/akka-docs/src/test/scala/docs/stream/cookbook/RecipeWorkerPool.scala @@ -25,11 +25,11 @@ class RecipeWorkerPool extends RecipeSpec { def balancer[In, Out](worker: Flow[In, Out, Any], workerCount: Int): Flow[In, Out, NotUsed] = { import GraphDSL.Implicits._ - Flow.fromGraph(GraphDSL.create() { implicit b ⇒ + Flow.fromGraph(GraphDSL.create() { implicit b => val balancer = b.add(Balance[In](workerCount, waitForAllDownstreams = true)) val merge = b.add(Merge[Out](workerCount)) - for (_ ← 1 to workerCount) { + for (_ <- 1 to workerCount) { // for each worker, add an edge from the balancer to the worker, then wire // it to the merge element balancer ~> worker.async ~> merge diff --git a/akka-docs/src/test/scala/docs/stream/io/StreamFileDocSpec.scala b/akka-docs/src/test/scala/docs/stream/io/StreamFileDocSpec.scala index ce60b37734..188b85e90e 100644 --- a/akka-docs/src/test/scala/docs/stream/io/StreamFileDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/io/StreamFileDocSpec.scala @@ -69,7 +69,7 @@ class StreamFileDocSpec extends AkkaSpec(UnboundedMailboxConfig) { //#file-sink val text = Source.single("Hello Akka Stream!") val result: Future[IOResult] = text - .map(t ⇒ ByteString(t)) + .map(t => ByteString(t)) .runWith(FileIO.toPath(file)) //#file-sink } diff --git a/akka-docs/src/test/scala/docs/stream/io/StreamTcpDocSpec.scala b/akka-docs/src/test/scala/docs/stream/io/StreamTcpDocSpec.scala index 8541b31bb9..62871755a9 100644 --- a/akka-docs/src/test/scala/docs/stream/io/StreamTcpDocSpec.scala +++ b/akka-docs/src/test/scala/docs/stream/io/StreamTcpDocSpec.scala @@ -30,9 +30,9 @@ class StreamTcpDocSpec extends AkkaSpec { val binding: Future[ServerBinding] = Tcp().bind("127.0.0.1", 8888).to(Sink.ignore).run() - binding.map { b ⇒ + binding.map { b => b.unbind() onComplete { - case _ ⇒ // ... + case _ => // ... } } //#echo-server-simple-bind @@ -44,7 +44,7 @@ class StreamTcpDocSpec extends AkkaSpec { val connections: Source[IncomingConnection, Future[ServerBinding]] = Tcp().bind(host, port) - connections runForeach { connection ⇒ + connections runForeach { connection => println(s"New connection from: ${connection.remoteAddress}") val echo = Flow[ByteString] @@ -71,7 +71,7 @@ class StreamTcpDocSpec extends AkkaSpec { import akka.stream.scaladsl.Framing val binding = //#welcome-banner-chat-server - connections.to(Sink.foreach { connection ⇒ + connections.to(Sink.foreach { connection => // server logic, parses incoming commands val commandParser = Flow[String].takeWhile(_ != "BYE").map(_ + "!") @@ -87,7 +87,7 @@ class StreamTcpDocSpec extends AkkaSpec { allowTruncation = true)) .map(_.utf8String) //#welcome-banner-chat-server - .map { command ⇒ serverProbe.ref ! command; command } + .map { command => serverProbe.ref ! command; command } //#welcome-banner-chat-server .via(commandParser) // merge in the initial banner after parser @@ -107,8 +107,8 @@ class StreamTcpDocSpec extends AkkaSpec { val input = new AtomicReference("Hello world" :: "What a lovely day" :: Nil) def readLine(prompt: String): String = { input.get() match { - case all @ cmd :: tail if input.compareAndSet(all, tail) ⇒ cmd - case _ ⇒ "q" + case all @ cmd :: tail if input.compareAndSet(all, tail) => cmd + case _ => "q" } } @@ -126,7 +126,7 @@ class StreamTcpDocSpec extends AkkaSpec { val replParser = Flow[String].takeWhile(_ != "q") .concat(Source.single("BYE")) - .map(elem ⇒ ByteString(s"$elem\n")) + .map(elem => ByteString(s"$elem\n")) val repl = Flow[ByteString] .via(Framing.delimiter( @@ -134,8 +134,8 @@ class StreamTcpDocSpec extends AkkaSpec { maximumFrameLength = 256, allowTruncation = true)) .map(_.utf8String) - .map(text ⇒ println("Server: " + text)) - .map(_ ⇒ readLine("> ")) + .map(text => println("Server: " + text)) + .map(_ => readLine("> ")) .via(replParser) val connected = connection.join(repl).run() diff --git a/akka-docs/src/test/scala/docs/stream/operators/Map.scala b/akka-docs/src/test/scala/docs/stream/operators/Map.scala index afdd1b5456..21248419f9 100644 --- a/akka-docs/src/test/scala/docs/stream/operators/Map.scala +++ b/akka-docs/src/test/scala/docs/stream/operators/Map.scala @@ -14,6 +14,6 @@ object Map { //#map val source: Source[Int, NotUsed] = Source(1 to 10) - val mapped: Source[String, NotUsed] = source.map(elem ⇒ elem.toString) + val mapped: Source[String, NotUsed] = source.map(elem => elem.toString) //#map } diff --git a/akka-docs/src/test/scala/docs/stream/operators/SourceOperators.scala b/akka-docs/src/test/scala/docs/stream/operators/SourceOperators.scala index 6aa9e1e806..9ccf83e4a2 100644 --- a/akka-docs/src/test/scala/docs/stream/operators/SourceOperators.scala +++ b/akka-docs/src/test/scala/docs/stream/operators/SourceOperators.scala @@ -23,7 +23,7 @@ object SourceOperators { implicit val materializer: ActorMaterializer = ActorMaterializer() val source: Source[Int, NotUsed] = Source.fromFuture(Future.successful(10)) - val sink: Sink[Int, Future[Done]] = Sink.foreach((i: Int) ⇒ println(i)) + val sink: Sink[Int, Future[Done]] = Sink.foreach((i: Int) => println(i)) val done: Future[Done] = source.runWith(sink) //10 //#sourceFromFuture diff --git a/akka-docs/src/test/scala/docs/stream/operators/SourceOrFlow.scala b/akka-docs/src/test/scala/docs/stream/operators/SourceOrFlow.scala index f1ce3a2024..08a67b271f 100644 --- a/akka-docs/src/test/scala/docs/stream/operators/SourceOrFlow.scala +++ b/akka-docs/src/test/scala/docs/stream/operators/SourceOrFlow.scala @@ -30,9 +30,9 @@ object SourceOrFlow { //#conflate import scala.concurrent.duration._ - Source.cycle(() ⇒ List(1, 10, 100, 1000).iterator) + Source.cycle(() => List(1, 10, 100, 1000).iterator) .throttle(10, per = 1.second) // faster upstream - .conflate((acc, el) ⇒ acc + el) // acc: Int, el: Int + .conflate((acc, el) => acc + el) // acc: Int, el: Int .throttle(1, per = 1.second) // slow downstream //#conflate } @@ -45,9 +45,9 @@ object SourceOrFlow { def sum(other: Summed) = Summed(this.i + other.i) } - Source.cycle(() ⇒ List(1, 10, 100, 1000).iterator) + Source.cycle(() => List(1, 10, 100, 1000).iterator) .throttle(10, per = 1.second) // faster upstream - .conflateWithSeed(el ⇒ Summed(el))((acc, el) ⇒ acc sum Summed(el)) // (Summed, Int) => Summed + .conflateWithSeed(el => Summed(el))((acc, el) => acc sum Summed(el)) // (Summed, Int) => Summed .throttle(1, per = 1.second) // slow downstream //#conflateWithSeed } @@ -61,7 +61,7 @@ object SourceOrFlow { //#scan val source = Source(1 to 5) - source.scan(0)((acc, x) ⇒ acc + x).runForeach(println) + source.scan(0)((acc, x) => acc + x).runForeach(println) // 0 (= 0) // 1 (= 0 + 1) // 3 (= 0 + 1 + 2) diff --git a/akka-docs/src/test/scala/docs/testkit/ParentChildSpec.scala b/akka-docs/src/test/scala/docs/testkit/ParentChildSpec.scala index b37f741251..e6a61bd9bd 100644 --- a/akka-docs/src/test/scala/docs/testkit/ParentChildSpec.scala +++ b/akka-docs/src/test/scala/docs/testkit/ParentChildSpec.scala @@ -27,14 +27,14 @@ class Parent extends Actor { var ponged = false def receive = { - case "pingit" ⇒ child ! "ping" - case "pong" ⇒ ponged = true + case "pingit" => child ! "ping" + case "pong" => ponged = true } } class Child extends Actor { def receive = { - case "ping" ⇒ context.parent ! "pong" + case "ping" => context.parent ! "pong" } } //#test-example @@ -42,7 +42,7 @@ class Child extends Actor { //#test-dependentchild class DependentChild(parent: ActorRef) extends Actor { def receive = { - case "ping" ⇒ parent ! "pong" + case "ping" => parent ! "pong" } } //#test-dependentchild @@ -52,18 +52,18 @@ class DependentParent(childProps: Props, probe: ActorRef) extends Actor { val child = context.actorOf(childProps, "child") def receive = { - case "pingit" ⇒ child ! "ping" - case "pong" ⇒ probe ! "ponged" + case "pingit" => child ! "ping" + case "pong" => probe ! "ponged" } } -class GenericDependentParent(childMaker: ActorRefFactory ⇒ ActorRef) extends Actor { +class GenericDependentParent(childMaker: ActorRefFactory => ActorRef) extends Actor { val child = childMaker(context) var ponged = false def receive = { - case "pingit" ⇒ child ! "ping" - case "pong" ⇒ ponged = true + case "pingit" => child ! "ping" + case "pong" => ponged = true } } //#test-dependentparent @@ -74,7 +74,7 @@ class GenericDependentParent(childMaker: ActorRefFactory ⇒ ActorRef) extends A class MockedChild extends Actor { def receive = { - case "ping" ⇒ sender ! "pong" + case "ping" => sender ! "pong" } } @@ -109,7 +109,7 @@ class ParentChildSpec extends WordSpec with Matchers with TestKitBase with Befor "be tested with a child probe" in { val probe = TestProbe() //#child-maker-test - val maker = (_: ActorRefFactory) ⇒ probe.ref + val maker = (_: ActorRefFactory) => probe.ref val parent = system.actorOf(Props(new GenericDependentParent(maker))) //#child-maker-test probe.send(parent, "pingit") @@ -118,7 +118,7 @@ class ParentChildSpec extends WordSpec with Matchers with TestKitBase with Befor "demonstrate production version of child creator" in { //#child-maker-prod - val maker = (f: ActorRefFactory) ⇒ f.actorOf(Props(new Child)) + val maker = (f: ActorRefFactory) => f.actorOf(Props(new Child)) val parent = system.actorOf(Props(new GenericDependentParent(maker))) //#child-maker-prod } @@ -142,8 +142,8 @@ class ParentChildSpec extends WordSpec with Matchers with TestKitBase with Befor val parent = system.actorOf(Props(new Actor { val child = context.actorOf(Props(new Child), "child") def receive = { - case x if sender == child ⇒ proxy.ref forward x - case x ⇒ child forward x + case x if sender == child => proxy.ref forward x + case x => child forward x } })) diff --git a/akka-docs/src/test/scala/docs/testkit/TestKitUsageSpec.scala b/akka-docs/src/test/scala/docs/testkit/TestKitUsageSpec.scala index d357fb2294..3e6e989cae 100644 --- a/akka-docs/src/test/scala/docs/testkit/TestKitUsageSpec.scala +++ b/akka-docs/src/test/scala/docs/testkit/TestKitUsageSpec.scala @@ -79,7 +79,7 @@ class TestKitUsageSpec filterRef ! 1 receiveWhile(500 millis) { - case msg: String ⇒ messages = msg +: messages + case msg: String => messages = msg +: messages } } messages.length should be(3) @@ -90,12 +90,12 @@ class TestKitUsageSpec "receive an interesting message at some point " in { within(500 millis) { ignoreMsg { - case msg: String ⇒ msg != "something" + case msg: String => msg != "something" } seqRef ! "something" expectMsg("something") ignoreMsg { - case msg: String ⇒ msg == "1" + case msg: String => msg == "1" } expectNoMsg ignoreNoMsg @@ -117,7 +117,7 @@ object TestKitUsageSpec { */ class ForwardingActor(next: ActorRef) extends Actor { def receive = { - case msg ⇒ next ! msg + case msg => next ! msg } } @@ -126,8 +126,8 @@ object TestKitUsageSpec { */ class FilteringActor(next: ActorRef) extends Actor { def receive = { - case msg: String ⇒ next ! msg - case _ ⇒ None + case msg: String => next ! msg + case _ => None } } @@ -140,7 +140,7 @@ object TestKitUsageSpec { class SequencingActor(next: ActorRef, head: immutable.Seq[String], tail: immutable.Seq[String]) extends Actor { def receive = { - case msg ⇒ { + case msg => { head foreach { next ! _ } next ! msg tail foreach { next ! _ } diff --git a/akka-docs/src/test/scala/docs/testkit/TestkitDocSpec.scala b/akka-docs/src/test/scala/docs/testkit/TestkitDocSpec.scala index 666c7c6d23..7fca0ba83c 100644 --- a/akka-docs/src/test/scala/docs/testkit/TestkitDocSpec.scala +++ b/akka-docs/src/test/scala/docs/testkit/TestkitDocSpec.scala @@ -24,18 +24,18 @@ object TestKitDocSpec { class MyActor extends Actor { def receive = { - case Say42 ⇒ sender() ! 42 - case "some work" ⇒ sender() ! "some result" + case Say42 => sender() ! 42 + case "some work" => sender() ! "some result" } } class TestFsmActor extends Actor with FSM[Int, String] { startWith(1, "") when(1) { - case Event("go", _) ⇒ goto(2) using "go" + case Event("go", _) => goto(2) using "go" } when(2) { - case Event("back", _) ⇒ goto(1) using "back" + case Event("back", _) => goto(1) using "back" } } @@ -44,10 +44,10 @@ object TestKitDocSpec { var dest1: ActorRef = _ var dest2: ActorRef = _ def receive = { - case (d1: ActorRef, d2: ActorRef) ⇒ + case (d1: ActorRef, d2: ActorRef) => dest1 = d1 dest2 = d2 - case x ⇒ + case x => dest1 ! x dest2 ! x } @@ -58,13 +58,13 @@ object TestKitDocSpec { //#test-probe-forward-actors class Source(target: ActorRef) extends Actor { def receive = { - case "start" ⇒ target ! "work" + case "start" => target ! "work" } } class Destination extends Actor { def receive = { - case x ⇒ // Do something.. + case x => // Do something.. } } @@ -78,7 +78,7 @@ object TestKitDocSpec { class TestTimerActor extends Actor with Timers { override def receive = { - case TriggerScheduling(foo) ⇒ triggerScheduling(ScheduledMessage(foo)) + case TriggerScheduling(foo) => triggerScheduling(ScheduledMessage(foo)) } def triggerScheduling(msg: ScheduledMessage) = @@ -90,10 +90,10 @@ object TestKitDocSpec { //#logging-receive import akka.event.LoggingReceive def receive = LoggingReceive { - case msg ⇒ // Do something ... + case msg => // Do something ... } def otherState: Receive = LoggingReceive.withLabel("other") { - case msg ⇒ // Do something else ... + case msg => // Do something else ... } //#logging-receive } @@ -191,7 +191,7 @@ class TestKitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val actorRef = TestActorRef(new Actor { def receive = { - case "hello" ⇒ throw new IllegalArgumentException("boom") + case "hello" => throw new IllegalArgumentException("boom") } }) intercept[IllegalArgumentException] { actorRef.receive("hello") } @@ -239,7 +239,7 @@ class TestKitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { val probe = new TestProbe(system) { def expectUpdate(x: Int) = { expectMsgPF() { - case Update(id, _) if id == x ⇒ () + case Update(id, _) if id == x => () } sender() ! "ACK" } @@ -346,7 +346,7 @@ class TestKitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { //#put-your-test-code-here val probe = TestProbe() probe.send(testActor, "hello") - try expectMsg("hello") catch { case NonFatal(e) ⇒ system.terminate(); throw e } + try expectMsg("hello") catch { case NonFatal(e) => system.terminate(); throw e } //#put-your-test-code-here shutdown(system) diff --git a/akka-docs/src/test/scala/tutorial_1/ActorHierarchyExperiments.scala b/akka-docs/src/test/scala/tutorial_1/ActorHierarchyExperiments.scala index b0af32684d..d86b91af1f 100644 --- a/akka-docs/src/test/scala/tutorial_1/ActorHierarchyExperiments.scala +++ b/akka-docs/src/test/scala/tutorial_1/ActorHierarchyExperiments.scala @@ -18,7 +18,7 @@ object PrintMyActorRefActor { class PrintMyActorRefActor extends Actor { override def receive: Receive = { - case "printit" ⇒ + case "printit" => val secondRef = context.actorOf(Props.empty, "second-actor") println(s"Second: $secondRef") } @@ -41,7 +41,7 @@ class StartStopActor1 extends Actor { override def postStop(): Unit = println("first stopped") override def receive: Receive = { - case "stop" ⇒ context.stop(self) + case "stop" => context.stop(self) } } @@ -70,7 +70,7 @@ class SupervisingActor extends Actor { val child = context.actorOf(SupervisedActor.props, "supervised-actor") override def receive: Receive = { - case "failChild" ⇒ child ! "fail" + case "failChild" => child ! "fail" } } @@ -84,7 +84,7 @@ class SupervisedActor extends Actor { override def postStop(): Unit = println("supervised actor stopped") override def receive: Receive = { - case "fail" ⇒ + case "fail" => println("supervised actor fails now") throw new Exception("I failed!") } diff --git a/akka-docs/src/test/scala/tutorial_3/Device.scala b/akka-docs/src/test/scala/tutorial_3/Device.scala index 6a37e71be5..22013c008e 100644 --- a/akka-docs/src/test/scala/tutorial_3/Device.scala +++ b/akka-docs/src/test/scala/tutorial_3/Device.scala @@ -25,12 +25,12 @@ class Device(groupId: String, deviceId: String) extends Actor with ActorLogging override def postStop(): Unit = log.info("Device actor {}-{} stopped", groupId, deviceId) override def receive: Receive = { - case RecordTemperature(id, value) ⇒ + case RecordTemperature(id, value) => log.info("Recorded temperature reading {} with {}", value, id) lastTemperatureReading = Some(value) sender() ! TemperatureRecorded(id) - case ReadTemperature(id) ⇒ + case ReadTemperature(id) => sender() ! RespondTemperature(id, lastTemperatureReading) } } diff --git a/akka-docs/src/test/scala/tutorial_3/DeviceInProgress.scala b/akka-docs/src/test/scala/tutorial_3/DeviceInProgress.scala index 465ea8baaf..ca4662a9bc 100644 --- a/akka-docs/src/test/scala/tutorial_3/DeviceInProgress.scala +++ b/akka-docs/src/test/scala/tutorial_3/DeviceInProgress.scala @@ -38,7 +38,7 @@ object DeviceInProgress2 { override def postStop(): Unit = log.info("Device actor {}-{} stopped", groupId, deviceId) override def receive: Receive = { - case ReadTemperature(id) ⇒ + case ReadTemperature(id) => sender() ! RespondTemperature(id, lastTemperatureReading) } diff --git a/akka-docs/src/test/scala/tutorial_4/Device.scala b/akka-docs/src/test/scala/tutorial_4/Device.scala index 21fc516f48..1a8cc3645b 100644 --- a/akka-docs/src/test/scala/tutorial_4/Device.scala +++ b/akka-docs/src/test/scala/tutorial_4/Device.scala @@ -27,21 +27,21 @@ class Device(groupId: String, deviceId: String) extends Actor with ActorLogging override def postStop(): Unit = log.info("Device actor {}-{} stopped", groupId, deviceId) override def receive: Receive = { - case DeviceManager.RequestTrackDevice(`groupId`, `deviceId`) ⇒ + case DeviceManager.RequestTrackDevice(`groupId`, `deviceId`) => sender() ! DeviceManager.DeviceRegistered - case DeviceManager.RequestTrackDevice(groupId, deviceId) ⇒ + case DeviceManager.RequestTrackDevice(groupId, deviceId) => log.warning( "Ignoring TrackDevice request for {}-{}.This actor is responsible for {}-{}.", groupId, deviceId, this.groupId, this.deviceId ) - case RecordTemperature(id, value) ⇒ + case RecordTemperature(id, value) => log.info("Recorded temperature reading {} with {}", value, id) lastTemperatureReading = Some(value) sender() ! TemperatureRecorded(id) - case ReadTemperature(id) ⇒ + case ReadTemperature(id) => sender() ! RespondTemperature(id, lastTemperatureReading) } } diff --git a/akka-docs/src/test/scala/tutorial_4/DeviceGroup.scala b/akka-docs/src/test/scala/tutorial_4/DeviceGroup.scala index 5938982b99..5dc03f1e32 100644 --- a/akka-docs/src/test/scala/tutorial_4/DeviceGroup.scala +++ b/akka-docs/src/test/scala/tutorial_4/DeviceGroup.scala @@ -35,11 +35,11 @@ class DeviceGroup(groupId: String) extends Actor with ActorLogging { override def postStop(): Unit = log.info("DeviceGroup {} stopped", groupId) override def receive: Receive = { - case trackMsg @ RequestTrackDevice(`groupId`, _) ⇒ + case trackMsg @ RequestTrackDevice(`groupId`, _) => deviceIdToActor.get(trackMsg.deviceId) match { - case Some(deviceActor) ⇒ + case Some(deviceActor) => deviceActor forward trackMsg - case None ⇒ + case None => log.info("Creating device actor for {}", trackMsg.deviceId) val deviceActor = context.actorOf(Device.props(groupId, trackMsg.deviceId), s"device-${trackMsg.deviceId}") //#device-group-register @@ -50,7 +50,7 @@ class DeviceGroup(groupId: String) extends Actor with ActorLogging { deviceActor forward trackMsg } - case RequestTrackDevice(groupId, deviceId) ⇒ + case RequestTrackDevice(groupId, deviceId) => log.warning( "Ignoring TrackDevice request for {}. This actor is responsible for {}.", groupId, this.groupId @@ -58,11 +58,11 @@ class DeviceGroup(groupId: String) extends Actor with ActorLogging { //#device-group-register //#device-group-remove - case RequestDeviceList(requestId) ⇒ + case RequestDeviceList(requestId) => sender() ! ReplyDeviceList(requestId, deviceIdToActor.keySet) //#device-group-remove - case Terminated(deviceActor) ⇒ + case Terminated(deviceActor) => val deviceId = actorToDeviceId(deviceActor) log.info("Device actor for {} has been terminated", deviceId) actorToDeviceId -= deviceActor diff --git a/akka-docs/src/test/scala/tutorial_4/DeviceManager.scala b/akka-docs/src/test/scala/tutorial_4/DeviceManager.scala index fbd7144022..c19eb7f3e7 100644 --- a/akka-docs/src/test/scala/tutorial_4/DeviceManager.scala +++ b/akka-docs/src/test/scala/tutorial_4/DeviceManager.scala @@ -26,11 +26,11 @@ class DeviceManager extends Actor with ActorLogging { override def postStop(): Unit = log.info("DeviceManager stopped") override def receive = { - case trackMsg @ RequestTrackDevice(groupId, _) ⇒ + case trackMsg @ RequestTrackDevice(groupId, _) => groupIdToActor.get(groupId) match { - case Some(ref) ⇒ + case Some(ref) => ref forward trackMsg - case None ⇒ + case None => log.info("Creating device group actor for {}", groupId) val groupActor = context.actorOf(DeviceGroup.props(groupId), "group-" + groupId) context.watch(groupActor) @@ -39,7 +39,7 @@ class DeviceManager extends Actor with ActorLogging { actorToGroupId += groupActor -> groupId } - case Terminated(groupActor) ⇒ + case Terminated(groupActor) => val groupId = actorToGroupId(groupActor) log.info("Device group actor for {} has been terminated", groupId) actorToGroupId -= groupActor diff --git a/akka-docs/src/test/scala/tutorial_5/Device.scala b/akka-docs/src/test/scala/tutorial_5/Device.scala index 536c069691..7b4202c475 100644 --- a/akka-docs/src/test/scala/tutorial_5/Device.scala +++ b/akka-docs/src/test/scala/tutorial_5/Device.scala @@ -27,21 +27,21 @@ class Device(groupId: String, deviceId: String) extends Actor with ActorLogging override def postStop(): Unit = log.info("Device actor {}-{} stopped", groupId, deviceId) override def receive: Receive = { - case DeviceManager.RequestTrackDevice(`groupId`, `deviceId`) ⇒ + case DeviceManager.RequestTrackDevice(`groupId`, `deviceId`) => sender() ! DeviceManager.DeviceRegistered - case DeviceManager.RequestTrackDevice(groupId, deviceId) ⇒ + case DeviceManager.RequestTrackDevice(groupId, deviceId) => log.warning( "Ignoring TrackDevice request for {}-{}.This actor is responsible for {}-{}.", groupId, deviceId, this.groupId, this.deviceId ) - case RecordTemperature(id, value) ⇒ + case RecordTemperature(id, value) => log.info("Recorded temperature reading {} with {}", value, id) lastTemperatureReading = Some(value) sender() ! TemperatureRecorded(id) - case ReadTemperature(id) ⇒ + case ReadTemperature(id) => sender() ! RespondTemperature(id, lastTemperatureReading) } } diff --git a/akka-docs/src/test/scala/tutorial_5/DeviceGroup.scala b/akka-docs/src/test/scala/tutorial_5/DeviceGroup.scala index 367e0b7d49..73eb314f8c 100644 --- a/akka-docs/src/test/scala/tutorial_5/DeviceGroup.scala +++ b/akka-docs/src/test/scala/tutorial_5/DeviceGroup.scala @@ -40,11 +40,11 @@ class DeviceGroup(groupId: String) extends Actor with ActorLogging { override def receive: Receive = { //#query-added - case trackMsg @ RequestTrackDevice(`groupId`, _) ⇒ + case trackMsg @ RequestTrackDevice(`groupId`, _) => deviceIdToActor.get(trackMsg.deviceId) match { - case Some(ref) ⇒ + case Some(ref) => ref forward trackMsg - case None ⇒ + case None => log.info("Creating device actor for {}", trackMsg.deviceId) val deviceActor = context.actorOf(Device.props(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId) context.watch(deviceActor) @@ -53,16 +53,16 @@ class DeviceGroup(groupId: String) extends Actor with ActorLogging { actorToDeviceId += deviceActor -> trackMsg.deviceId } - case RequestTrackDevice(groupId, deviceId) ⇒ + case RequestTrackDevice(groupId, deviceId) => log.warning( "Ignoring TrackDevice request for {}. This actor is responsible for {}.", groupId, this.groupId ) - case RequestDeviceList(requestId) ⇒ + case RequestDeviceList(requestId) => sender() ! ReplyDeviceList(requestId, deviceIdToActor.keySet) - case Terminated(deviceActor) ⇒ + case Terminated(deviceActor) => val deviceId = actorToDeviceId(deviceActor) log.info("Device actor for {} has been terminated", deviceId) actorToDeviceId -= deviceActor @@ -71,7 +71,7 @@ class DeviceGroup(groupId: String) extends Actor with ActorLogging { //#query-added // ... other cases omitted - case RequestAllTemperatures(requestId) ⇒ + case RequestAllTemperatures(requestId) => context.actorOf(DeviceGroupQuery.props( actorToDeviceId = actorToDeviceId, requestId = requestId, diff --git a/akka-docs/src/test/scala/tutorial_5/DeviceGroupQuery.scala b/akka-docs/src/test/scala/tutorial_5/DeviceGroupQuery.scala index f3708d0f2a..48abacc4ff 100644 --- a/akka-docs/src/test/scala/tutorial_5/DeviceGroupQuery.scala +++ b/akka-docs/src/test/scala/tutorial_5/DeviceGroupQuery.scala @@ -34,7 +34,7 @@ class DeviceGroupQuery( val queryTimeoutTimer = context.system.scheduler.scheduleOnce(timeout, self, CollectionTimeout) override def preStart(): Unit = { - actorToDeviceId.keysIterator.foreach { deviceActor ⇒ + actorToDeviceId.keysIterator.foreach { deviceActor => context.watch(deviceActor) deviceActor ! Device.ReadTemperature(0) } @@ -56,20 +56,20 @@ class DeviceGroupQuery( repliesSoFar: Map[String, DeviceGroup.TemperatureReading], stillWaiting: Set[ActorRef] ): Receive = { - case Device.RespondTemperature(0, valueOption) ⇒ + case Device.RespondTemperature(0, valueOption) => val deviceActor = sender() val reading = valueOption match { - case Some(value) ⇒ DeviceGroup.Temperature(value) - case None ⇒ DeviceGroup.TemperatureNotAvailable + case Some(value) => DeviceGroup.Temperature(value) + case None => DeviceGroup.TemperatureNotAvailable } receivedResponse(deviceActor, reading, stillWaiting, repliesSoFar) - case Terminated(deviceActor) ⇒ + case Terminated(deviceActor) => receivedResponse(deviceActor, DeviceGroup.DeviceNotAvailable, stillWaiting, repliesSoFar) - case CollectionTimeout ⇒ + case CollectionTimeout => val timedOutReplies = - stillWaiting.map { deviceActor ⇒ + stillWaiting.map { deviceActor => val deviceId = actorToDeviceId(deviceActor) deviceId -> DeviceGroup.DeviceTimedOut } diff --git a/akka-docs/src/test/scala/tutorial_5/DeviceManager.scala b/akka-docs/src/test/scala/tutorial_5/DeviceManager.scala index a0f5097ce9..f253e95e78 100644 --- a/akka-docs/src/test/scala/tutorial_5/DeviceManager.scala +++ b/akka-docs/src/test/scala/tutorial_5/DeviceManager.scala @@ -23,11 +23,11 @@ class DeviceManager extends Actor with ActorLogging { override def postStop(): Unit = log.info("DeviceManager stopped") override def receive = { - case trackMsg @ RequestTrackDevice(groupId, _) ⇒ + case trackMsg @ RequestTrackDevice(groupId, _) => groupIdToActor.get(groupId) match { - case Some(ref) ⇒ + case Some(ref) => ref forward trackMsg - case None ⇒ + case None => log.info("Creating device group actor for {}", groupId) val groupActor = context.actorOf(DeviceGroup.props(groupId), "group-" + groupId) context.watch(groupActor) @@ -36,7 +36,7 @@ class DeviceManager extends Actor with ActorLogging { actorToGroupId += groupActor -> groupId } - case Terminated(groupActor) ⇒ + case Terminated(groupActor) => val groupId = actorToGroupId(groupActor) log.info("Device group actor for {} has been terminated", groupId) actorToGroupId -= groupActor diff --git a/akka-docs/src/test/scala/typed/tutorial_1/ActorHierarchyExperiments.scala b/akka-docs/src/test/scala/typed/tutorial_1/ActorHierarchyExperiments.scala index 3cb3166344..6aca175a89 100644 --- a/akka-docs/src/test/scala/typed/tutorial_1/ActorHierarchyExperiments.scala +++ b/akka-docs/src/test/scala/typed/tutorial_1/ActorHierarchyExperiments.scala @@ -20,14 +20,14 @@ import akka.actor.typed.scaladsl.Behaviors object PrintMyActorRefActor { def apply(): Behavior[String] = - Behaviors.setup(context ⇒ new PrintMyActorRefActor(context)) + Behaviors.setup(context => new PrintMyActorRefActor(context)) } class PrintMyActorRefActor(context: ActorContext[String]) extends AbstractBehavior[String] { override def onMessage(msg: String): Behavior[String] = msg match { - case "printit" ⇒ + case "printit" => val secondRef = context.spawn(Behaviors.empty[String], "second-actor") println(s"Second: $secondRef") this @@ -38,7 +38,7 @@ class PrintMyActorRefActor(context: ActorContext[String]) extends AbstractBehavi //#start-stop object StartStopActor1 { def apply(): Behavior[String] = - Behaviors.setup(context ⇒ new StartStopActor1(context)) + Behaviors.setup(context => new StartStopActor1(context)) } class StartStopActor1(context: ActorContext[String]) extends AbstractBehavior[String] { @@ -47,11 +47,11 @@ class StartStopActor1(context: ActorContext[String]) extends AbstractBehavior[St override def onMessage(msg: String): Behavior[String] = msg match { - case "stop" ⇒ Behaviors.stopped + case "stop" => Behaviors.stopped } override def onSignal: PartialFunction[Signal, Behavior[String]] = { - case PostStop ⇒ + case PostStop => println("first stopped") this } @@ -60,7 +60,7 @@ class StartStopActor1(context: ActorContext[String]) extends AbstractBehavior[St object StartStopActor2 { def apply(): Behavior[String] = - Behaviors.setup(_ ⇒ new StartStopActor2) + Behaviors.setup(_ => new StartStopActor2) } class StartStopActor2 extends AbstractBehavior[String] { @@ -72,7 +72,7 @@ class StartStopActor2 extends AbstractBehavior[String] { } override def onSignal: PartialFunction[Signal, Behavior[String]] = { - case PostStop ⇒ + case PostStop => println("second stopped") this } @@ -83,7 +83,7 @@ class StartStopActor2 extends AbstractBehavior[String] { //#supervise object SupervisingActor { def apply(): Behavior[String] = - Behaviors.setup(context ⇒ new SupervisingActor(context)) + Behaviors.setup(context => new SupervisingActor(context)) } class SupervisingActor(context: ActorContext[String]) extends AbstractBehavior[String] { @@ -93,7 +93,7 @@ class SupervisingActor(context: ActorContext[String]) extends AbstractBehavior[S override def onMessage(msg: String): Behavior[String] = msg match { - case "failChild" ⇒ + case "failChild" => child ! "fail" this } @@ -101,7 +101,7 @@ class SupervisingActor(context: ActorContext[String]) extends AbstractBehavior[S object SupervisedActor { def apply(): Behavior[String] = - Behaviors.setup(_ ⇒ new SupervisedActor) + Behaviors.setup(_ => new SupervisedActor) } class SupervisedActor extends AbstractBehavior[String] { @@ -109,16 +109,16 @@ class SupervisedActor extends AbstractBehavior[String] { override def onMessage(msg: String): Behavior[String] = msg match { - case "fail" ⇒ + case "fail" => println("supervised actor fails now") throw new Exception("I failed!") } override def onSignal: PartialFunction[Signal, Behavior[String]] = { - case PreRestart ⇒ + case PreRestart => println("supervised actor will be restarted") this - case PostStop ⇒ + case PostStop => println("supervised actor stopped") this } @@ -130,14 +130,14 @@ class SupervisedActor extends AbstractBehavior[String] { object Main { def apply(): Behavior[String] = - Behaviors.setup(context ⇒ new Main(context)) + Behaviors.setup(context => new Main(context)) } class Main(context: ActorContext[String]) extends AbstractBehavior[String] { override def onMessage(msg: String): Behavior[String] = msg match { - case "start" ⇒ + case "start" => val firstRef = context.spawn(PrintMyActorRefActor(), "first-actor") println(s"First: $firstRef") firstRef ! "printit" diff --git a/akka-docs/src/test/scala/typed/tutorial_2/IotSupervisor.scala b/akka-docs/src/test/scala/typed/tutorial_2/IotSupervisor.scala index 2a0f87ebad..0506149f7f 100644 --- a/akka-docs/src/test/scala/typed/tutorial_2/IotSupervisor.scala +++ b/akka-docs/src/test/scala/typed/tutorial_2/IotSupervisor.scala @@ -14,7 +14,7 @@ import akka.actor.typed.scaladsl.Behaviors object IotSupervisor { def apply(): Behavior[Nothing] = - Behaviors.setup[Nothing](context ⇒ new IotSupervisor(context)) + Behaviors.setup[Nothing](context => new IotSupervisor(context)) } class IotSupervisor(context: ActorContext[Nothing]) extends AbstractBehavior[Nothing] { @@ -26,7 +26,7 @@ class IotSupervisor(context: ActorContext[Nothing]) extends AbstractBehavior[Not } override def onSignal: PartialFunction[Signal, Behavior[Nothing]] = { - case PostStop ⇒ + case PostStop => context.log.info("IoT Application stopped") this } diff --git a/akka-docs/src/test/scala/typed/tutorial_3/Device.scala b/akka-docs/src/test/scala/typed/tutorial_3/Device.scala index 00f3ef819c..84312479e4 100644 --- a/akka-docs/src/test/scala/typed/tutorial_3/Device.scala +++ b/akka-docs/src/test/scala/typed/tutorial_3/Device.scala @@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors object Device { def apply(groupId: String, deviceId: String): Behavior[DeviceMessage] = - Behaviors.setup(context ⇒ new Device(context, groupId, deviceId)) + Behaviors.setup(context => new Device(context, groupId, deviceId)) sealed trait DeviceMessage @@ -40,20 +40,20 @@ class Device(context: ActorContext[Device.DeviceMessage], groupId: String, devic override def onMessage(msg: DeviceMessage): Behavior[DeviceMessage] = { msg match { - case RecordTemperature(id, value, replyTo) ⇒ + case RecordTemperature(id, value, replyTo) => context.log.info("Recorded temperature reading {} with {}", value, id) lastTemperatureReading = Some(value) replyTo ! TemperatureRecorded(id) this - case ReadTemperature(id, replyTo) ⇒ + case ReadTemperature(id, replyTo) => replyTo ! RespondTemperature(id, lastTemperatureReading) this } } override def onSignal: PartialFunction[Signal, Behavior[DeviceMessage]] = { - case PostStop ⇒ + case PostStop => context.log.info("Device actor {}-{} stopped", groupId, deviceId) this } diff --git a/akka-docs/src/test/scala/typed/tutorial_3/DeviceInProgress.scala b/akka-docs/src/test/scala/typed/tutorial_3/DeviceInProgress.scala index 58a09f3492..098b96a231 100644 --- a/akka-docs/src/test/scala/typed/tutorial_3/DeviceInProgress.scala +++ b/akka-docs/src/test/scala/typed/tutorial_3/DeviceInProgress.scala @@ -33,7 +33,7 @@ object DeviceInProgress2 { object Device { def apply(groupId: String, deviceId: String): Behavior[DeviceMessage] = - Behaviors.setup(context ⇒ new Device(context, groupId, deviceId)) + Behaviors.setup(context => new Device(context, groupId, deviceId)) //#read-protocol-2 sealed trait DeviceMessage @@ -53,14 +53,14 @@ object DeviceInProgress2 { override def onMessage(msg: DeviceMessage): Behavior[DeviceMessage] = { msg match { - case ReadTemperature(id, replyTo) ⇒ + case ReadTemperature(id, replyTo) => replyTo ! RespondTemperature(id, lastTemperatureReading) this } } override def onSignal: PartialFunction[Signal, Behavior[DeviceMessage]] = { - case PostStop ⇒ + case PostStop => context.log.info("Device actor {}-{} stopped", groupId, deviceId) this } diff --git a/akka-docs/src/test/scala/typed/tutorial_4/Device.scala b/akka-docs/src/test/scala/typed/tutorial_4/Device.scala index c69ddb24ec..2873401aef 100644 --- a/akka-docs/src/test/scala/typed/tutorial_4/Device.scala +++ b/akka-docs/src/test/scala/typed/tutorial_4/Device.scala @@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors object Device { def apply(groupId: String, deviceId: String): Behavior[DeviceMessage] = - Behaviors.setup(context ⇒ new Device(context, groupId, deviceId)) + Behaviors.setup(context => new Device(context, groupId, deviceId)) sealed trait DeviceMessage @@ -42,23 +42,23 @@ class Device(context: ActorContext[Device.DeviceMessage], groupId: String, devic override def onMessage(msg: DeviceMessage): Behavior[DeviceMessage] = { msg match { - case RecordTemperature(id, value, replyTo) ⇒ + case RecordTemperature(id, value, replyTo) => context.log.info("Recorded temperature reading {} with {}", value, id) lastTemperatureReading = Some(value) replyTo ! TemperatureRecorded(id) this - case ReadTemperature(id, replyTo) ⇒ + case ReadTemperature(id, replyTo) => replyTo ! RespondTemperature(id, lastTemperatureReading) this - case Passivate ⇒ + case Passivate => Behaviors.stopped } } override def onSignal: PartialFunction[Signal, Behavior[DeviceMessage]] = { - case PostStop ⇒ + case PostStop => context.log.info("Device actor {}-{} stopped", groupId, deviceId) this } diff --git a/akka-docs/src/test/scala/typed/tutorial_4/DeviceGroup.scala b/akka-docs/src/test/scala/typed/tutorial_4/DeviceGroup.scala index 810b4bf7b0..cc7c4a675f 100644 --- a/akka-docs/src/test/scala/typed/tutorial_4/DeviceGroup.scala +++ b/akka-docs/src/test/scala/typed/tutorial_4/DeviceGroup.scala @@ -16,7 +16,7 @@ import akka.actor.typed.scaladsl.Behaviors //#device-group-register object DeviceGroup { def apply(groupId: String): Behavior[DeviceGroupMessage] = - Behaviors.setup(context ⇒ new DeviceGroup(context, groupId)) + Behaviors.setup(context => new DeviceGroup(context, groupId)) trait DeviceGroupMessage @@ -41,11 +41,11 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId override def onMessage(msg: DeviceGroupMessage): Behavior[DeviceGroupMessage] = msg match { - case trackMsg @ RequestTrackDevice(`groupId`, deviceId, replyTo) ⇒ + case trackMsg @ RequestTrackDevice(`groupId`, deviceId, replyTo) => deviceIdToActor.get(deviceId) match { - case Some(deviceActor) ⇒ + case Some(deviceActor) => replyTo ! DeviceRegistered(deviceActor) - case None ⇒ + case None => context.log.info("Creating device actor for {}", trackMsg.deviceId) val deviceActor = context.spawn(Device(groupId, deviceId), s"device-$deviceId") //#device-group-register @@ -56,7 +56,7 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId } this - case RequestTrackDevice(gId, _, _) ⇒ + case RequestTrackDevice(gId, _, _) => context.log.warning( "Ignoring TrackDevice request for {}. This actor is responsible for {}.", gId, groupId @@ -65,7 +65,7 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId //#device-group-register //#device-group-remove - case RequestDeviceList(requestId, gId, replyTo) ⇒ + case RequestDeviceList(requestId, gId, replyTo) => if (gId == groupId) { replyTo ! ReplyDeviceList(requestId, deviceIdToActor.keySet) this @@ -73,7 +73,7 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId Behaviors.unhandled //#device-group-remove - case DeviceTerminated(_, _, deviceId) ⇒ + case DeviceTerminated(_, _, deviceId) => context.log.info("Device actor for {} has been terminated", deviceId) deviceIdToActor -= deviceId this @@ -82,7 +82,7 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId } override def onSignal: PartialFunction[Signal, Behavior[DeviceGroupMessage]] = { - case PostStop ⇒ + case PostStop => context.log.info("DeviceGroup {} stopped", groupId) this } diff --git a/akka-docs/src/test/scala/typed/tutorial_4/DeviceManager.scala b/akka-docs/src/test/scala/typed/tutorial_4/DeviceManager.scala index 2edd9e6648..69e195abe3 100644 --- a/akka-docs/src/test/scala/typed/tutorial_4/DeviceManager.scala +++ b/akka-docs/src/test/scala/typed/tutorial_4/DeviceManager.scala @@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors //#device-manager-full object DeviceManager { def apply(): Behavior[DeviceManagerMessage] = - Behaviors.setup(context ⇒ new DeviceManager(context)) + Behaviors.setup(context => new DeviceManager(context)) //#device-manager-msgs import DeviceGroup.DeviceGroupMessage @@ -51,11 +51,11 @@ class DeviceManager(context: ActorContext[DeviceManager.DeviceManagerMessage]) override def onMessage(msg: DeviceManagerMessage): Behavior[DeviceManagerMessage] = msg match { - case trackMsg @ RequestTrackDevice(groupId, _, replyTo) ⇒ + case trackMsg @ RequestTrackDevice(groupId, _, replyTo) => groupIdToActor.get(groupId) match { - case Some(ref) ⇒ + case Some(ref) => ref ! trackMsg - case None ⇒ + case None => context.log.info("Creating device group actor for {}", groupId) val groupActor = context.spawn(DeviceGroup(groupId), "group-" + groupId) context.watchWith(groupActor, DeviceGroupTerminated(groupId)) @@ -64,23 +64,23 @@ class DeviceManager(context: ActorContext[DeviceManager.DeviceManagerMessage]) } this - case req @ RequestDeviceList(requestId, groupId, replyTo) ⇒ + case req @ RequestDeviceList(requestId, groupId, replyTo) => groupIdToActor.get(groupId) match { - case Some(ref) ⇒ + case Some(ref) => ref ! req - case None ⇒ + case None => replyTo ! ReplyDeviceList(requestId, Set.empty) } this - case DeviceGroupTerminated(groupId) ⇒ + case DeviceGroupTerminated(groupId) => context.log.info("Device group actor for {} has been terminated", groupId) groupIdToActor -= groupId this } override def onSignal: PartialFunction[Signal, Behavior[DeviceManagerMessage]] = { - case PostStop ⇒ + case PostStop => context.log.info("DeviceManager stopped") this } diff --git a/akka-docs/src/test/scala/typed/tutorial_5/Device.scala b/akka-docs/src/test/scala/typed/tutorial_5/Device.scala index 541f28204c..043f6e1010 100644 --- a/akka-docs/src/test/scala/typed/tutorial_5/Device.scala +++ b/akka-docs/src/test/scala/typed/tutorial_5/Device.scala @@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors object Device { def apply(groupId: String, deviceId: String): Behavior[DeviceMessage] = - Behaviors.setup(context ⇒ new Device(context, groupId, deviceId)) + Behaviors.setup(context => new Device(context, groupId, deviceId)) sealed trait DeviceMessage @@ -40,23 +40,23 @@ class Device(context: ActorContext[Device.DeviceMessage], groupId: String, devic override def onMessage(msg: DeviceMessage): Behavior[DeviceMessage] = { msg match { - case RecordTemperature(id, value, replyTo) ⇒ + case RecordTemperature(id, value, replyTo) => context.log.info("Recorded temperature reading {} with {}", value, id) lastTemperatureReading = Some(value) replyTo ! TemperatureRecorded(id) this - case ReadTemperature(id, replyTo) ⇒ + case ReadTemperature(id, replyTo) => replyTo ! RespondTemperature(id, deviceId, lastTemperatureReading) this - case Passivate ⇒ + case Passivate => Behaviors.stopped } } override def onSignal: PartialFunction[Signal, Behavior[DeviceMessage]] = { - case PostStop ⇒ + case PostStop => context.log.info("Device actor {}-{} stopped", groupId, deviceId) this } diff --git a/akka-docs/src/test/scala/typed/tutorial_5/DeviceGroup.scala b/akka-docs/src/test/scala/typed/tutorial_5/DeviceGroup.scala index 7941631d42..0a2ba9fd6a 100644 --- a/akka-docs/src/test/scala/typed/tutorial_5/DeviceGroup.scala +++ b/akka-docs/src/test/scala/typed/tutorial_5/DeviceGroup.scala @@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors object DeviceGroup { def apply(groupId: String): Behavior[DeviceGroupMessage] = - Behaviors.setup(context ⇒ new DeviceGroup(context, groupId)) + Behaviors.setup(context => new DeviceGroup(context, groupId)) trait DeviceGroupMessage @@ -39,11 +39,11 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId override def onMessage(msg: DeviceGroupMessage): Behavior[DeviceGroupMessage] = msg match { //#query-added - case trackMsg @ RequestTrackDevice(`groupId`, deviceId, replyTo) ⇒ + case trackMsg @ RequestTrackDevice(`groupId`, deviceId, replyTo) => deviceIdToActor.get(deviceId) match { - case Some(deviceActor) ⇒ + case Some(deviceActor) => replyTo ! DeviceRegistered(deviceActor) - case None ⇒ + case None => context.log.info("Creating device actor for {}", trackMsg.deviceId) val deviceActor = context.spawn(Device(groupId, deviceId), s"device-$deviceId") //#device-group-register @@ -54,14 +54,14 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId } this - case RequestTrackDevice(gId, _, _) ⇒ + case RequestTrackDevice(gId, _, _) => context.log.warning( "Ignoring TrackDevice request for {}. This actor is responsible for {}.", gId, groupId ) this - case RequestDeviceList(requestId, gId, replyTo) ⇒ + case RequestDeviceList(requestId, gId, replyTo) => if (gId == groupId) { replyTo ! ReplyDeviceList(requestId, deviceIdToActor.keySet) this @@ -69,7 +69,7 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId Behaviors.unhandled //#device-group-remove - case DeviceTerminated(_, _, deviceId) ⇒ + case DeviceTerminated(_, _, deviceId) => context.log.info("Device actor for {} has been terminated", deviceId) deviceIdToActor -= deviceId this @@ -77,7 +77,7 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId //#query-added // ... other cases omitted - case RequestAllTemperatures(requestId, gId, replyTo) ⇒ + case RequestAllTemperatures(requestId, gId, replyTo) => if (gId == groupId) { context.spawnAnonymous(DeviceGroupQuery( deviceIdToActor, @@ -91,7 +91,7 @@ class DeviceGroup(context: ActorContext[DeviceGroup.DeviceGroupMessage], groupId } override def onSignal: PartialFunction[Signal, Behavior[DeviceGroupMessage]] = { - case PostStop ⇒ + case PostStop => context.log.info("DeviceGroup {} stopped", groupId) this } diff --git a/akka-docs/src/test/scala/typed/tutorial_5/DeviceGroupQuery.scala b/akka-docs/src/test/scala/typed/tutorial_5/DeviceGroupQuery.scala index fb8252160d..192df2ed42 100644 --- a/akka-docs/src/test/scala/typed/tutorial_5/DeviceGroupQuery.scala +++ b/akka-docs/src/test/scala/typed/tutorial_5/DeviceGroupQuery.scala @@ -32,8 +32,8 @@ object DeviceGroupQuery { requester: ActorRef[RespondAllTemperatures], timeout: FiniteDuration ): Behavior[DeviceGroupQueryMessage] = { - Behaviors.setup { context ⇒ - Behaviors.withTimers { timers ⇒ + Behaviors.setup { context => + Behaviors.withTimers { timers => new DeviceGroupQuery(deviceIdToActor, requestId, requester, timeout, context, timers) } } @@ -71,7 +71,7 @@ class DeviceGroupQuery( //#query-outline deviceIdToActor.foreach { - case (deviceId, device) ⇒ + case (deviceId, device) => context.watchWith(device, DeviceTerminated(deviceId)) device ! ReadTemperature(0, respondTemperatureAdapter) } @@ -80,15 +80,15 @@ class DeviceGroupQuery( //#query-state override def onMessage(msg: DeviceGroupQueryMessage): Behavior[DeviceGroupQueryMessage] = msg match { - case WrappedRespondTemperature(response) ⇒ onRespondTemperature(response) - case DeviceTerminated(deviceId) ⇒ onDeviceTerminated(deviceId) - case CollectionTimeout ⇒ onCollectionTimout() + case WrappedRespondTemperature(response) => onRespondTemperature(response) + case DeviceTerminated(deviceId) => onDeviceTerminated(deviceId) + case CollectionTimeout => onCollectionTimout() } private def onRespondTemperature(response: RespondTemperature): Behavior[DeviceGroupQueryMessage] = { val reading = response.value match { - case Some(value) ⇒ Temperature(value) - case None ⇒ TemperatureNotAvailable + case Some(value) => Temperature(value) + case None => TemperatureNotAvailable } val deviceId = response.deviceId @@ -107,7 +107,7 @@ class DeviceGroupQuery( } private def onCollectionTimout(): Behavior[DeviceGroupQueryMessage] = { - repliesSoFar ++= stillWaiting.map(deviceId ⇒ deviceId -> DeviceTimedOut) + repliesSoFar ++= stillWaiting.map(deviceId => deviceId -> DeviceTimedOut) stillWaiting = Set.empty respondWhenAllCollected() } diff --git a/akka-docs/src/test/scala/typed/tutorial_5/DeviceManager.scala b/akka-docs/src/test/scala/typed/tutorial_5/DeviceManager.scala index 4f09f5dbe7..781fdff45c 100644 --- a/akka-docs/src/test/scala/typed/tutorial_5/DeviceManager.scala +++ b/akka-docs/src/test/scala/typed/tutorial_5/DeviceManager.scala @@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors //#device-manager-full object DeviceManager { def apply(): Behavior[DeviceManagerMessage] = - Behaviors.setup(context ⇒ new DeviceManager(context)) + Behaviors.setup(context => new DeviceManager(context)) //#device-manager-msgs import DeviceGroup.DeviceGroupMessage @@ -62,11 +62,11 @@ class DeviceManager(context: ActorContext[DeviceManager.DeviceManagerMessage]) override def onMessage(msg: DeviceManagerMessage): Behavior[DeviceManagerMessage] = msg match { - case trackMsg @ RequestTrackDevice(groupId, _, replyTo) ⇒ + case trackMsg @ RequestTrackDevice(groupId, _, replyTo) => groupIdToActor.get(groupId) match { - case Some(ref) ⇒ + case Some(ref) => ref ! trackMsg - case None ⇒ + case None => context.log.info("Creating device group actor for {}", groupId) val groupActor = context.spawn(DeviceGroup(groupId), "group-" + groupId) context.watchWith(groupActor, DeviceGroupTerminated(groupId)) @@ -75,32 +75,32 @@ class DeviceManager(context: ActorContext[DeviceManager.DeviceManagerMessage]) } this - case req @ RequestDeviceList(requestId, groupId, replyTo) ⇒ + case req @ RequestDeviceList(requestId, groupId, replyTo) => groupIdToActor.get(groupId) match { - case Some(ref) ⇒ + case Some(ref) => ref ! req - case None ⇒ + case None => replyTo ! ReplyDeviceList(requestId, Set.empty) } this - case req @ RequestAllTemperatures(requestId, groupId, replyTo) ⇒ + case req @ RequestAllTemperatures(requestId, groupId, replyTo) => groupIdToActor.get(groupId) match { - case Some(ref) ⇒ + case Some(ref) => ref ! req - case None ⇒ + case None => replyTo ! RespondAllTemperatures(requestId, Map.empty) } this - case DeviceGroupTerminated(groupId) ⇒ + case DeviceGroupTerminated(groupId) => context.log.info("Device group actor for {} has been terminated", groupId) groupIdToActor -= groupId this } override def onSignal: PartialFunction[Signal, Behavior[DeviceManagerMessage]] = { - case PostStop ⇒ + case PostStop => context.log.info("DeviceManager stopped") this } diff --git a/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/Conductor.scala b/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/Conductor.scala index 7cde3d1b5b..b220b7b917 100644 --- a/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/Conductor.scala +++ b/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/Conductor.scala @@ -33,14 +33,14 @@ import scala.util.control.NoStackTrace * All of this is bundled inside the [[akka.remote.testconductor.TestConductorExt]] * extension. */ -trait Conductor { this: TestConductorExt ⇒ +trait Conductor { this: TestConductorExt => import Controller._ private var _controller: ActorRef = _ private def controller: ActorRef = _controller match { - case null ⇒ throw new IllegalStateException("TestConductorServer was not started") - case x ⇒ x + case null => throw new IllegalStateException("TestConductorServer was not started") + case x => x } /** @@ -65,7 +65,7 @@ trait Conductor { this: TestConductorExt ⇒ _controller = system.actorOf(Props(classOf[Controller], participants, controllerPort), "controller") import Settings.BarrierTimeout import system.dispatcher - controller ? GetSockAddr flatMap { case sockAddr: InetSocketAddress ⇒ startClient(name, sockAddr) map (_ ⇒ sockAddr) } + controller ? GetSockAddr flatMap { case sockAddr: InetSocketAddress => startClient(name, sockAddr) map (_ => sockAddr) } } /** @@ -189,7 +189,7 @@ trait Conductor { this: TestConductorExt ⇒ import system.dispatcher // the recover is needed to handle ClientDisconnectedException exception, // which is normal during shutdown - controller ? Terminate(node, Right(exitValue)) mapTo classTag[Done] recover { case _: ClientDisconnectedException ⇒ Done } + controller ? Terminate(node, Right(exitValue)) mapTo classTag[Done] recover { case _: ClientDisconnectedException => Done } } /** @@ -212,7 +212,7 @@ trait Conductor { this: TestConductorExt ⇒ import system.dispatcher // the recover is needed to handle ClientDisconnectedException exception, // which is normal during shutdown - controller ? Terminate(node, Left(abort)) mapTo classTag[Done] recover { case _: ClientDisconnectedException ⇒ Done } + controller ? Terminate(node, Left(abort)) mapTo classTag[Done] recover { case _: ClientDisconnectedException => Done } } /** @@ -269,9 +269,9 @@ private[akka] class ConductorHandler(_createTimeout: Timeout, controller: ActorR val channel = event.getChannel log.debug("message from {}: {}", getAddrString(channel), event.getMessage) event.getMessage match { - case msg: NetworkOp ⇒ + case msg: NetworkOp => clients.get(channel) ! msg - case msg ⇒ + case msg => log.info("client {} sent garbage '{}', disconnecting", getAddrString(channel), msg) channel.close() } @@ -312,53 +312,53 @@ private[akka] class ServerFSM(val controller: ActorRef, val channel: Channel) ex startWith(Initial, None) whenUnhandled { - case Event(ClientDisconnected, Some(s)) ⇒ + case Event(ClientDisconnected, Some(s)) => s ! Status.Failure(new ClientDisconnectedException("client disconnected in state " + stateName + ": " + channel)) stop() - case Event(ClientDisconnected, None) ⇒ stop() + case Event(ClientDisconnected, None) => stop() } onTermination { - case _ ⇒ + case _ => controller ! ClientDisconnected(roleName) channel.close() } when(Initial, stateTimeout = 10 seconds) { - case Event(Hello(name, address), _) ⇒ + case Event(Hello(name, address), _) => roleName = RoleName(name) controller ! NodeInfo(roleName, address, self) goto(Ready) - case Event(x: NetworkOp, _) ⇒ + case Event(x: NetworkOp, _) => log.warning("client {} sent no Hello in first message (instead {}), disconnecting", getAddrString(channel), x) channel.close() stop() - case Event(ToClient(msg), _) ⇒ + case Event(ToClient(msg), _) => log.warning("cannot send {} in state Initial", msg) stay - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => log.info("closing channel to {} because of Hello timeout", getAddrString(channel)) channel.close() stop() } when(Ready) { - case Event(d: Done, Some(s)) ⇒ + case Event(d: Done, Some(s)) => s ! d stay using None - case Event(op: ServerOp, _) ⇒ + case Event(op: ServerOp, _) => controller ! op stay - case Event(msg: NetworkOp, _) ⇒ + case Event(msg: NetworkOp, _) => log.warning("client {} sent unsupported message {}", getAddrString(channel), msg) stop() - case Event(ToClient(msg: UnconfirmedClientOp), _) ⇒ + case Event(ToClient(msg: UnconfirmedClientOp), _) => channel.write(msg) stay - case Event(ToClient(msg), None) ⇒ + case Event(ToClient(msg), None) => channel.write(msg) stay using Some(sender()) - case Event(ToClient(msg), _) ⇒ + case Event(ToClient(msg), _) => log.warning("cannot send {} while waiting for previous ACK", msg) stay } @@ -402,16 +402,16 @@ private[akka] class Controller(private var initialParticipants: Int, controllerP * BarrierTimeouts in the players). */ override def supervisorStrategy = OneForOneStrategy() { - case BarrierTimeout(data) ⇒ failBarrier(data) - case FailedBarrier(data) ⇒ failBarrier(data) - case BarrierEmpty(data, msg) ⇒ SupervisorStrategy.Resume - case WrongBarrier(name, client, data) ⇒ { client ! ToClient(BarrierResult(name, false)); failBarrier(data) } - case ClientLost(data, node) ⇒ failBarrier(data) - case DuplicateNode(data, node) ⇒ failBarrier(data) + case BarrierTimeout(data) => failBarrier(data) + case FailedBarrier(data) => failBarrier(data) + case BarrierEmpty(data, msg) => SupervisorStrategy.Resume + case WrongBarrier(name, client, data) => { client ! ToClient(BarrierResult(name, false)); failBarrier(data) } + case ClientLost(data, node) => failBarrier(data) + case DuplicateNode(data, node) => failBarrier(data) } def failBarrier(data: Data): SupervisorStrategy.Directive = { - for (c ← data.arrived) c ! ToClient(BarrierResult(data.barrier, false)) + for (c <- data.arrived) c ! ToClient(BarrierResult(data.barrier, false)) SupervisorStrategy.Restart } @@ -423,23 +423,23 @@ private[akka] class Controller(private var initialParticipants: Int, controllerP val generation = Iterator from 1 override def receive = LoggingReceive { - case CreateServerFSM(channel) ⇒ - val (ip, port) = channel.getRemoteAddress match { case s: InetSocketAddress ⇒ (s.getAddress.getHostAddress, s.getPort) } + case CreateServerFSM(channel) => + val (ip, port) = channel.getRemoteAddress match { case s: InetSocketAddress => (s.getAddress.getHostAddress, s.getPort) } val name = ip + ":" + port + "-server" + generation.next sender() ! context.actorOf(Props(classOf[ServerFSM], self, channel).withDeploy(Deploy.local), name) - case c @ NodeInfo(name, address, fsm) ⇒ + case c @ NodeInfo(name, address, fsm) => barrier forward c if (nodes contains name) { if (initialParticipants > 0) { - for (NodeInfo(_, _, client) ← nodes.values) client ! ToClient(BarrierResult("initial startup", false)) + for (NodeInfo(_, _, client) <- nodes.values) client ! ToClient(BarrierResult("initial startup", false)) initialParticipants = 0 } fsm ! ToClient(BarrierResult("initial startup", false)) } else { - nodes += name → c + nodes += name -> c if (initialParticipants <= 0) fsm ! ToClient(Done) else if (nodes.size == initialParticipants) { - for (NodeInfo(_, _, client) ← nodes.values) client ! ToClient(Done) + for (NodeInfo(_, _, client) <- nodes.values) client ! ToClient(Done) initialParticipants = 0 } if (addrInterest contains name) { @@ -447,35 +447,35 @@ private[akka] class Controller(private var initialParticipants: Int, controllerP addrInterest -= name } } - case c @ ClientDisconnected(name) ⇒ + case c @ ClientDisconnected(name) => nodes -= name barrier forward c - case op: ServerOp ⇒ + case op: ServerOp => op match { - case _: EnterBarrier ⇒ barrier forward op - case _: FailBarrier ⇒ barrier forward op - case GetAddress(node) ⇒ + case _: EnterBarrier => barrier forward op + case _: FailBarrier => barrier forward op + case GetAddress(node) => if (nodes contains node) sender() ! ToClient(AddressReply(node, nodes(node).addr)) - else addrInterest += node → ((addrInterest get node getOrElse Set()) + sender()) - case _: Done ⇒ //FIXME what should happen? + else addrInterest += node -> ((addrInterest get node getOrElse Set()) + sender()) + case _: Done => //FIXME what should happen? } - case op: CommandOp ⇒ + case op: CommandOp => op match { - case Throttle(node, target, direction, rateMBit) ⇒ + case Throttle(node, target, direction, rateMBit) => val t = nodes(target) nodes(node).fsm forward ToClient(ThrottleMsg(t.addr, direction, rateMBit)) - case Disconnect(node, target, abort) ⇒ + case Disconnect(node, target, abort) => val t = nodes(target) nodes(node).fsm forward ToClient(DisconnectMsg(t.addr, abort)) - case Terminate(node, shutdownOrExit) ⇒ + case Terminate(node, shutdownOrExit) => barrier ! BarrierCoordinator.RemoveClient(node) nodes(node).fsm forward ToClient(TerminateMsg(shutdownOrExit)) nodes -= node - case Remove(node) ⇒ + case Remove(node) => barrier ! BarrierCoordinator.RemoveClient(node) } - case GetNodes ⇒ sender() ! nodes.keys - case GetSockAddr ⇒ sender() ! connection.getLocalAddress + case GetNodes => sender() ! nodes.keys + case GetSockAddr => sender() ! connection.getLocalAddress } override def postStop(): Unit = { @@ -495,7 +495,7 @@ private[akka] object BarrierCoordinator { final case class Data(clients: Set[Controller.NodeInfo], barrier: String, arrived: List[ActorRef], deadline: Deadline) - trait Printer { this: Product with Throwable with NoStackTrace ⇒ + trait Printer { this: Product with Throwable with NoStackTrace => override def toString = productPrefix + productIterator.mkString("(", ", ", ")") } @@ -528,7 +528,7 @@ private[akka] object BarrierCoordinator { private[akka] class BarrierCoordinator extends Actor with LoggingFSM[BarrierCoordinator.State, BarrierCoordinator.Data] { import BarrierCoordinator._ import Controller._ - import FSM.`→` + import FSM.`->` // this shall be set to true if all subsequent barriers shall fail var failed = false @@ -541,22 +541,22 @@ private[akka] class BarrierCoordinator extends Actor with LoggingFSM[BarrierCoor startWith(Idle, Data(Set(), "", Nil, null)) whenUnhandled { - case Event(n: NodeInfo, d @ Data(clients, _, _, _)) ⇒ + case Event(n: NodeInfo, d @ Data(clients, _, _, _)) => if (clients.find(_.name == n.name).isDefined) throw new DuplicateNode(d, n) stay using d.copy(clients = clients + n) - case Event(ClientDisconnected(name), d @ Data(clients, _, arrived, _)) ⇒ + case Event(ClientDisconnected(name), d @ Data(clients, _, arrived, _)) => if (arrived.isEmpty) stay using d.copy(clients = clients.filterNot(_.name == name)) else { (clients find (_.name == name)) match { - case None ⇒ stay - case Some(c) ⇒ throw ClientLost(d.copy(clients = clients - c, arrived = arrived filterNot (_ == c.fsm)), name) + case None => stay + case Some(c) => throw ClientLost(d.copy(clients = clients - c, arrived = arrived filterNot (_ == c.fsm)), name) } } } when(Idle) { - case Event(EnterBarrier(name, timeout), d @ Data(clients, _, _, _)) ⇒ + case Event(EnterBarrier(name, timeout), d @ Data(clients, _, _, _)) => if (failed) stay replying ToClient(BarrierResult(name, false)) else if (clients.map(_.fsm) == Set(sender())) @@ -567,18 +567,18 @@ private[akka] class BarrierCoordinator extends Actor with LoggingFSM[BarrierCoor goto(Waiting) using d.copy(barrier = name, arrived = sender() :: Nil, deadline = getDeadline(timeout)) } - case Event(RemoveClient(name), d @ Data(clients, _, _, _)) ⇒ + case Event(RemoveClient(name), d @ Data(clients, _, _, _)) => if (clients.isEmpty) throw BarrierEmpty(d, "cannot remove " + name + ": no client to remove") stay using d.copy(clients = clients filterNot (_.name == name)) } onTransition { - case Idle → Waiting ⇒ setTimer("Timeout", StateTimeout, nextStateData.deadline.timeLeft, false) - case Waiting → Idle ⇒ cancelTimer("Timeout") + case Idle -> Waiting => setTimer("Timeout", StateTimeout, nextStateData.deadline.timeLeft, false) + case Waiting -> Idle => cancelTimer("Timeout") } when(Waiting) { - case Event(EnterBarrier(name, timeout), d @ Data(clients, barrier, arrived, deadline)) ⇒ + case Event(EnterBarrier(name, timeout), d @ Data(clients, barrier, arrived, deadline)) => if (name != barrier) throw WrongBarrier(name, sender(), d) val together = if (clients.exists(_.fsm == sender())) sender() :: arrived else arrived val enterDeadline = getDeadline(timeout) @@ -588,16 +588,16 @@ private[akka] class BarrierCoordinator extends Actor with LoggingFSM[BarrierCoor handleBarrier(d.copy(arrived = together, deadline = enterDeadline)) } else handleBarrier(d.copy(arrived = together)) - case Event(RemoveClient(name), d @ Data(clients, barrier, arrived, _)) ⇒ + case Event(RemoveClient(name), d @ Data(clients, barrier, arrived, _)) => clients find (_.name == name) match { - case None ⇒ stay - case Some(client) ⇒ + case None => stay + case Some(client) => handleBarrier(d.copy(clients = clients - client, arrived = arrived filterNot (_ == client.fsm))) } - case Event(FailBarrier(name), d @ Data(_, barrier, _, _)) ⇒ + case Event(FailBarrier(name), d @ Data(_, barrier, _, _)) => if (name != barrier) throw WrongBarrier(name, sender(), d) throw FailedBarrier(d) - case Event(StateTimeout, d) ⇒ + case Event(StateTimeout, d) => throw BarrierTimeout(d) } diff --git a/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/DataTypes.scala b/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/DataTypes.scala index e1bfa1ccd1..30149826d4 100644 --- a/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/DataTypes.scala +++ b/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/DataTypes.scala @@ -9,7 +9,7 @@ import language.implicitConversions import org.jboss.netty.handler.codec.oneone.OneToOneEncoder import org.jboss.netty.channel.ChannelHandlerContext import org.jboss.netty.channel.Channel -import akka.remote.testconductor.{ TestConductorProtocol ⇒ TCP } +import akka.remote.testconductor.{ TestConductorProtocol => TCP } import akka.actor.Address import org.jboss.netty.handler.codec.oneone.OneToOneDecoder import scala.concurrent.duration._ @@ -67,48 +67,48 @@ private[akka] class MsgEncoder extends OneToOneEncoder { .build implicit def direction2proto(dir: Direction): TCP.Direction = dir match { - case Direction.Send ⇒ TCP.Direction.Send - case Direction.Receive ⇒ TCP.Direction.Receive - case Direction.Both ⇒ TCP.Direction.Both + case Direction.Send => TCP.Direction.Send + case Direction.Receive => TCP.Direction.Receive + case Direction.Both => TCP.Direction.Both } def encode(ctx: ChannelHandlerContext, ch: Channel, msg: AnyRef): AnyRef = msg match { - case x: NetworkOp ⇒ + case x: NetworkOp => val w = TCP.Wrapper.newBuilder x match { - case Hello(name, address) ⇒ + case Hello(name, address) => w.setHello(TCP.Hello.newBuilder.setName(name).setAddress(address)) - case EnterBarrier(name, timeout) ⇒ + case EnterBarrier(name, timeout) => val barrier = TCP.EnterBarrier.newBuilder.setName(name) - timeout foreach (t ⇒ barrier.setTimeout(t.toNanos)) + timeout foreach (t => barrier.setTimeout(t.toNanos)) barrier.setOp(BarrierOp.Enter) w.setBarrier(barrier) - case BarrierResult(name, success) ⇒ + case BarrierResult(name, success) => val res = if (success) BarrierOp.Succeeded else BarrierOp.Failed w.setBarrier(TCP.EnterBarrier.newBuilder.setName(name).setOp(res)) - case FailBarrier(name) ⇒ + case FailBarrier(name) => w.setBarrier(TCP.EnterBarrier.newBuilder.setName(name).setOp(BarrierOp.Fail)) - case ThrottleMsg(target, dir, rate) ⇒ + case ThrottleMsg(target, dir, rate) => w.setFailure(TCP.InjectFailure.newBuilder.setAddress(target) .setFailure(TCP.FailType.Throttle).setDirection(dir).setRateMBit(rate)) - case DisconnectMsg(target, abort) ⇒ + case DisconnectMsg(target, abort) => w.setFailure(TCP.InjectFailure.newBuilder.setAddress(target) .setFailure(if (abort) TCP.FailType.Abort else TCP.FailType.Disconnect)) - case TerminateMsg(Right(exitValue)) ⇒ + case TerminateMsg(Right(exitValue)) => w.setFailure(TCP.InjectFailure.newBuilder.setFailure(TCP.FailType.Exit).setExitValue(exitValue)) - case TerminateMsg(Left(false)) ⇒ + case TerminateMsg(Left(false)) => w.setFailure(TCP.InjectFailure.newBuilder.setFailure(TCP.FailType.Shutdown)) - case TerminateMsg(Left(true)) ⇒ + case TerminateMsg(Left(true)) => w.setFailure(TCP.InjectFailure.newBuilder.setFailure(TCP.FailType.ShutdownAbrupt)) - case GetAddress(node) ⇒ + case GetAddress(node) => w.setAddr(TCP.AddressRequest.newBuilder.setNode(node.name)) - case AddressReply(node, address) ⇒ + case AddressReply(node, address) => w.setAddr(TCP.AddressRequest.newBuilder.setNode(node.name).setAddr(address)) - case _: Done ⇒ + case _: Done => w.setDone("") } w.build - case _ ⇒ throw new IllegalArgumentException("wrong message " + msg) + case _ => throw new IllegalArgumentException("wrong message " + msg) } } @@ -118,36 +118,36 @@ private[akka] class MsgDecoder extends OneToOneDecoder { Address(addr.getProtocol, addr.getSystem, addr.getHost, addr.getPort) implicit def direction2scala(dir: TCP.Direction): Direction = dir match { - case TCP.Direction.Send ⇒ Direction.Send - case TCP.Direction.Receive ⇒ Direction.Receive - case TCP.Direction.Both ⇒ Direction.Both + case TCP.Direction.Send => Direction.Send + case TCP.Direction.Receive => Direction.Receive + case TCP.Direction.Both => Direction.Both } def decode(ctx: ChannelHandlerContext, ch: Channel, msg: AnyRef): AnyRef = msg match { - case w: TCP.Wrapper if w.getAllFields.size == 1 ⇒ + case w: TCP.Wrapper if w.getAllFields.size == 1 => if (w.hasHello) { val h = w.getHello Hello(h.getName, h.getAddress) } else if (w.hasBarrier) { val barrier = w.getBarrier barrier.getOp match { - case BarrierOp.Succeeded ⇒ BarrierResult(barrier.getName, true) - case BarrierOp.Failed ⇒ BarrierResult(barrier.getName, false) - case BarrierOp.Fail ⇒ FailBarrier(barrier.getName) - case BarrierOp.Enter ⇒ EnterBarrier( + case BarrierOp.Succeeded => BarrierResult(barrier.getName, true) + case BarrierOp.Failed => BarrierResult(barrier.getName, false) + case BarrierOp.Fail => FailBarrier(barrier.getName) + case BarrierOp.Enter => EnterBarrier( barrier.getName, if (barrier.hasTimeout) Option(Duration.fromNanos(barrier.getTimeout)) else None) } } else if (w.hasFailure) { val f = w.getFailure - import TCP.{ FailType ⇒ FT } + import TCP.{ FailType => FT } f.getFailure match { - case FT.Throttle ⇒ ThrottleMsg(f.getAddress, f.getDirection, f.getRateMBit) - case FT.Abort ⇒ DisconnectMsg(f.getAddress, true) - case FT.Disconnect ⇒ DisconnectMsg(f.getAddress, false) - case FT.Exit ⇒ TerminateMsg(Right(f.getExitValue)) - case FT.Shutdown ⇒ TerminateMsg(Left(false)) - case FT.ShutdownAbrupt ⇒ TerminateMsg(Left(true)) + case FT.Throttle => ThrottleMsg(f.getAddress, f.getDirection, f.getRateMBit) + case FT.Abort => DisconnectMsg(f.getAddress, true) + case FT.Disconnect => DisconnectMsg(f.getAddress, false) + case FT.Exit => TerminateMsg(Right(f.getExitValue)) + case FT.Shutdown => TerminateMsg(Left(false)) + case FT.ShutdownAbrupt => TerminateMsg(Left(true)) } } else if (w.hasAddr) { val a = w.getAddr @@ -158,6 +158,6 @@ private[akka] class MsgDecoder extends OneToOneDecoder { } else { throw new IllegalArgumentException("unknown message " + msg) } - case _ ⇒ throw new IllegalArgumentException("wrong message " + msg) + case _ => throw new IllegalArgumentException("wrong message " + msg) } } diff --git a/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/Player.scala b/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/Player.scala index 425225e302..2d5eb2ddc7 100644 --- a/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/Player.scala +++ b/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/Player.scala @@ -31,16 +31,16 @@ object Player { var waiting: ActorRef = _ def receive = { - case fsm: ActorRef ⇒ + case fsm: ActorRef => waiting = sender(); fsm ! SubscribeTransitionCallBack(self) - case Transition(_, f: ClientFSM.State, t: ClientFSM.State) if f == Connecting && t == AwaitDone ⇒ // step 1, not there yet // // SI-5900 workaround - case Transition(_, f: ClientFSM.State, t: ClientFSM.State) if f == AwaitDone && t == Connected ⇒ // SI-5900 workaround + case Transition(_, f: ClientFSM.State, t: ClientFSM.State) if f == Connecting && t == AwaitDone => // step 1, not there yet // // SI-5900 workaround + case Transition(_, f: ClientFSM.State, t: ClientFSM.State) if f == AwaitDone && t == Connected => // SI-5900 workaround waiting ! Done; context stop self - case t: Transition[_] ⇒ + case t: Transition[_] => waiting ! Status.Failure(new RuntimeException("unexpected transition: " + t)); context stop self - case CurrentState(_, s: ClientFSM.State) if s == Connected ⇒ // SI-5900 workaround + case CurrentState(_, s: ClientFSM.State) if s == Connected => // SI-5900 workaround waiting ! Done; context stop self - case _: CurrentState[_] ⇒ + case _: CurrentState[_] => } } @@ -54,15 +54,15 @@ object Player { * the [[akka.remote.testconductor.Conductor]]’s [[akka.remote.testconductor.Controller]] * in order to participate in barriers and enable network failure injection. */ -trait Player { this: TestConductorExt ⇒ +trait Player { this: TestConductorExt => private var _client: ActorRef = _ private def client = _client match { - case null ⇒ + case null => throw new IllegalStateException("TestConductor client not yet started") - case _ if system.whenTerminated.isCompleted ⇒ + case _ if system.whenTerminated.isCompleted => throw new IllegalStateException("TestConductor unavailable because system is terminated; you need to startNewSystem() before this point") - case x ⇒ x + case x => x } /** @@ -95,7 +95,7 @@ trait Player { this: TestConductorExt ⇒ def enter(timeout: Timeout, name: immutable.Seq[String]): Unit = { system.log.debug("entering barriers " + name.mkString("(", ", ", ")")) val stop = Deadline.now + timeout.duration - name foreach { b ⇒ + name foreach { b => val barrierTimeout = stop.timeLeft if (barrierTimeout < Duration.Zero) { client ! ToServer(FailBarrier(b)) @@ -105,7 +105,7 @@ trait Player { this: TestConductorExt ⇒ implicit val timeout = Timeout(barrierTimeout + Settings.QueryTimeout.duration) Await.result(client ? ToServer(EnterBarrier(b, Option(barrierTimeout))), Duration.Inf) } catch { - case e: AskTimeoutException ⇒ + case e: AskTimeoutException => client ! ToServer(FailBarrier(b)) // Why don't TimeoutException have a constructor that takes a cause? throw new TimeoutException("Client timed out while waiting for barrier " + b); @@ -167,72 +167,72 @@ private[akka] class ClientFSM(name: RoleName, controllerAddr: InetSocketAddress) startWith(Connecting, Data(None, None)) when(Connecting, stateTimeout = settings.ConnectTimeout) { - case Event(msg: ClientOp, _) ⇒ + case Event(msg: ClientOp, _) => stay replying Status.Failure(new IllegalStateException("not connected yet")) - case Event(Connected(channel), _) ⇒ + case Event(Connected(channel), _) => channel.write(Hello(name.name, TestConductor().address)) goto(AwaitDone) using Data(Some(channel), None) - case Event(e: ConnectionFailure, _) ⇒ + case Event(e: ConnectionFailure, _) => log.error(e, "ConnectionFailure") goto(Failed) - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => log.error("Failed to connect to test conductor within {} ms.", settings.ConnectTimeout.toMillis) goto(Failed) } when(AwaitDone, stateTimeout = settings.BarrierTimeout.duration) { - case Event(Done, _) ⇒ + case Event(Done, _) => log.debug("received Done: starting test") goto(Connected) - case Event(msg: NetworkOp, _) ⇒ + case Event(msg: NetworkOp, _) => log.error("received {} instead of Done", msg) goto(Failed) - case Event(msg: ServerOp, _) ⇒ + case Event(msg: ServerOp, _) => stay replying Status.Failure(new IllegalStateException("not connected yet")) - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => log.error("connect timeout to TestConductor") goto(Failed) } when(Connected) { - case Event(Disconnected, _) ⇒ + case Event(Disconnected, _) => log.info("disconnected from TestConductor") throw new ConnectionFailure("disconnect") - case Event(ToServer(_: Done), Data(Some(channel), _)) ⇒ + case Event(ToServer(_: Done), Data(Some(channel), _)) => channel.write(Done) stay - case Event(ToServer(msg), d @ Data(Some(channel), None)) ⇒ + case Event(ToServer(msg), d @ Data(Some(channel), None)) => channel.write(msg) val token = msg match { - case EnterBarrier(barrier, timeout) ⇒ Some(barrier → sender()) - case GetAddress(node) ⇒ Some(node.name → sender()) - case _ ⇒ None + case EnterBarrier(barrier, timeout) => Some(barrier -> sender()) + case GetAddress(node) => Some(node.name -> sender()) + case _ => None } stay using d.copy(runningOp = token) - case Event(ToServer(op), Data(channel, Some((token, _)))) ⇒ + case Event(ToServer(op), Data(channel, Some((token, _)))) => log.error("cannot write {} while waiting for {}", op, token) stay - case Event(op: ClientOp, d @ Data(Some(channel), runningOp)) ⇒ + case Event(op: ClientOp, d @ Data(Some(channel), runningOp)) => op match { - case BarrierResult(b, success) ⇒ + case BarrierResult(b, success) => runningOp match { - case Some((barrier, requester)) ⇒ + case Some((barrier, requester)) => val response = if (b != barrier) Status.Failure(new RuntimeException("wrong barrier " + b + " received while waiting for " + barrier)) else if (!success) Status.Failure(new RuntimeException("barrier failed: " + b)) else b requester ! response - case None ⇒ + case None => log.warning("did not expect {}", op) } stay using d.copy(runningOp = None) - case AddressReply(node, address) ⇒ + case AddressReply(node, address) => runningOp match { - case Some((_, requester)) ⇒ requester ! address - case None ⇒ log.warning("did not expect {}", op) + case Some((_, requester)) => requester ! address + case None => log.warning("did not expect {}", op) } stay using d.copy(runningOp = None) - case t: ThrottleMsg ⇒ + case t: ThrottleMsg => import context.dispatcher // FIXME is this the right EC for the future below? val mode = if (t.rateMBit < 0.0f) Unthrottled else if (t.rateMBit == 0.0f) Blackhole @@ -243,37 +243,37 @@ private[akka] class ClientFSM(name: RoleName, controllerAddr: InetSocketAddress) val cmdFuture = TestConductor().transport.managementCommand(SetThrottle(t.target, t.direction, mode)) cmdFuture foreach { - case true ⇒ self ! ToServer(Done) - case _ ⇒ throw new RuntimeException("Throttle was requested from the TestConductor, but no transport " + + case true => self ! ToServer(Done) + case _ => throw new RuntimeException("Throttle was requested from the TestConductor, but no transport " + "adapters available that support throttling. Specify `testTransport(on = true)` in your MultiNodeConfig") } stay - case d: DisconnectMsg ⇒ + case d: DisconnectMsg => // FIXME: Currently ignoring, needs support from Remoting stay - case TerminateMsg(Left(false)) ⇒ + case TerminateMsg(Left(false)) => context.system.terminate() stay - case TerminateMsg(Left(true)) ⇒ + case TerminateMsg(Left(true)) => context.system.asInstanceOf[ActorSystemImpl].abort() stay - case TerminateMsg(Right(exitValue)) ⇒ + case TerminateMsg(Right(exitValue)) => System.exit(exitValue) stay // needed because Java doesn’t have Nothing - case _: Done ⇒ stay //FIXME what should happen? + case _: Done => stay //FIXME what should happen? } } when(Failed) { - case Event(msg: ClientOp, _) ⇒ + case Event(msg: ClientOp, _) => stay replying Status.Failure(new RuntimeException("cannot do " + msg + " while Failed")) - case Event(msg: NetworkOp, _) ⇒ + case Event(msg: NetworkOp, _) => log.warning("ignoring network message {} while Failed", msg) stay } onTermination { - case StopEvent(_, _, Data(Some(channel), _)) ⇒ + case StopEvent(_, _, Data(Some(channel), _)) => channel.close() } @@ -310,10 +310,10 @@ private[akka] class PlayerHandler( override def exceptionCaught(ctx: ChannelHandlerContext, event: ExceptionEvent) = { log.debug("channel {} exception {}", event.getChannel, event.getCause) event.getCause match { - case c: ConnectException if reconnects > 0 ⇒ + case c: ConnectException if reconnects > 0 => reconnects -= 1 scheduler.scheduleOnce(nextAttempt.timeLeft)(reconnect()) - case e ⇒ fsm ! ConnectionFailure(e.getMessage) + case e => fsm ! ConnectionFailure(e.getMessage) } } @@ -339,9 +339,9 @@ private[akka] class PlayerHandler( val channel = event.getChannel log.debug("message from {}: {}", getAddrString(channel), event.getMessage) event.getMessage match { - case msg: NetworkOp ⇒ + case msg: NetworkOp => fsm ! msg - case msg ⇒ + case msg => log.info("server {} sent garbage '{}', disconnecting", getAddrString(channel), msg) channel.close() } diff --git a/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/RemoteConnection.scala b/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/RemoteConnection.scala index 9d00eb73b8..4ef7001fac 100644 --- a/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/RemoteConnection.scala +++ b/akka-multi-node-testkit/src/main/scala/akka/remote/testconductor/RemoteConnection.scala @@ -23,10 +23,10 @@ import org.jboss.netty.buffer.ChannelBuffer private[akka] class ProtobufEncoder extends OneToOneEncoder { override def encode(ctx: ChannelHandlerContext, ch: Channel, msg: AnyRef): AnyRef = msg match { - case m: Message ⇒ + case m: Message => val bytes = m.toByteArray() ctx.getChannel.getConfig.getBufferFactory.getBuffer(bytes, 0, bytes.length) - case other ⇒ other + case other => other } } @@ -36,12 +36,12 @@ private[akka] class ProtobufEncoder extends OneToOneEncoder { private[akka] class ProtobufDecoder(prototype: Message) extends OneToOneDecoder { override def decode(ctx: ChannelHandlerContext, ch: Channel, obj: AnyRef): AnyRef = obj match { - case buf: ChannelBuffer ⇒ + case buf: ChannelBuffer => val len = buf.readableBytes() val bytes = new Array[Byte](len) buf.getBytes(buf.readerIndex, bytes, 0, len) prototype.getParserForType.parseFrom(bytes) - case other ⇒ other + case other => other } } @@ -54,7 +54,7 @@ private[akka] class TestConductorPipelineFactory(handler: ChannelUpstreamHandler val proto = List(new ProtobufEncoder, new ProtobufDecoder(TestConductorProtocol.Wrapper.getDefaultInstance)) val msg = List(new MsgEncoder, new MsgDecoder) (encap ::: proto ::: msg ::: handler :: Nil).foldLeft(new DefaultChannelPipeline) { - (pipe, handler) ⇒ pipe.addLast(Logging.simpleName(handler.getClass), handler); pipe + (pipe, handler) => pipe.addLast(Logging.simpleName(handler.getClass), handler); pipe } } } @@ -78,14 +78,14 @@ private[akka] case object Server extends Role private[akka] object RemoteConnection { def apply(role: Role, sockaddr: InetSocketAddress, poolSize: Int, handler: ChannelUpstreamHandler): Channel = { role match { - case Client ⇒ + case Client => val socketfactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool, Executors.newCachedThreadPool, poolSize) val bootstrap = new ClientBootstrap(socketfactory) bootstrap.setPipelineFactory(new TestConductorPipelineFactory(handler)) bootstrap.setOption("tcpNoDelay", true) bootstrap.connect(sockaddr).getChannel - case Server ⇒ + case Server => val socketfactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool, Executors.newCachedThreadPool, poolSize) val bootstrap = new ServerBootstrap(socketfactory) @@ -97,8 +97,8 @@ private[akka] object RemoteConnection { } def getAddrString(channel: Channel) = channel.getRemoteAddress match { - case i: InetSocketAddress ⇒ i.toString - case _ ⇒ "[unknown]" + case i: InetSocketAddress => i.toString + case _ => "[unknown]" } def shutdown(channel: Channel) = diff --git a/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/FlightRecordingSupport.scala b/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/FlightRecordingSupport.scala index 2c3f87fca9..3486a9455b 100644 --- a/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/FlightRecordingSupport.scala +++ b/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/FlightRecordingSupport.scala @@ -26,7 +26,7 @@ import akka.remote.artery.FlightRecorderReader * You need to hook in dump and deletion of files where it makes sense in your tests. (For example, dump after all tests has * run and there was a failure and then delete) */ -trait FlightRecordingSupport { self: MultiNodeSpec ⇒ +trait FlightRecordingSupport { self: MultiNodeSpec => private lazy val arteryEnabled = RARP(system).provider.remoteSettings.Artery.Enabled private lazy val flightRecorderFile: Path = diff --git a/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/MultiNodeSpec.scala b/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/MultiNodeSpec.scala index c4c83a4b44..9aa1128321 100644 --- a/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/MultiNodeSpec.scala +++ b/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/MultiNodeSpec.scala @@ -49,7 +49,7 @@ abstract class MultiNodeConfig { */ def nodeConfig(roles: RoleName*)(configs: Config*): Unit = { val c = configs.reduceLeft(_ withFallback _) - _nodeConf ++= roles map { _ → c } + _nodeConf ++= roles map { _ -> c } } /** @@ -90,7 +90,7 @@ abstract class MultiNodeConfig { } def deployOn(role: RoleName, deployment: String): Unit = - _deployments += role → ((_deployments get role getOrElse Vector()) :+ deployment) + _deployments += role -> ((_deployments get role getOrElse Vector()) :+ deployment) def deployOnAll(deployment: String): Unit = _allDeploy :+= deployment @@ -151,9 +151,9 @@ object MultiNodeSpec { * is defined as system property "multinode.host". */ val selfName: String = Option(System.getProperty("multinode.host")) match { - case None ⇒ throw new IllegalStateException("need system property multinode.host to be set") - case Some("") ⇒ InetAddress.getLocalHost.getHostAddress - case Some(host) ⇒ host + case None => throw new IllegalStateException("need system property multinode.host to be set") + case Some("") => InetAddress.getLocalHost.getHostAddress + case Some(host) => host } require(selfName != "", "multinode.host must not be empty") @@ -208,11 +208,11 @@ object MultiNodeSpec { require(selfIndex >= 0 && selfIndex < maxNodes, "multinode.index is out of bounds: " + selfIndex) private[testkit] val nodeConfig = mapToConfig(Map( - "akka.actor.provider" → "remote", - "akka.remote.artery.canonical.hostname" → selfName, - "akka.remote.netty.tcp.hostname" → selfName, - "akka.remote.netty.tcp.port" → selfPort, - "akka.remote.artery.canonical.port" → selfPort)) + "akka.actor.provider" -> "remote", + "akka.remote.artery.canonical.hostname" -> selfName, + "akka.remote.netty.tcp.hostname" -> selfName, + "akka.remote.netty.tcp.port" -> selfPort, + "akka.remote.artery.canonical.port" -> selfPort)) private[testkit] val baseConfig: Config = ConfigFactory.parseString(""" akka { @@ -243,8 +243,8 @@ object MultiNodeSpec { val pattern = s"(akka\\.remote\\.testkit\\.MultiNodeSpec.*|akka\\.remote\\.RemotingMultiNodeSpec)" val s = Thread.currentThread.getStackTrace.map(_.getClassName).drop(1).dropWhile(_.matches(pattern)) val reduced = s.lastIndexWhere(_ == clazz.getName) match { - case -1 ⇒ s - case z ⇒ s drop (z + 1) + case -1 => s + case z => s drop (z + 1) } reduced.head.replaceFirst(""".*\.""", "").replaceAll("[^a-zA-Z_0-9]", "_") } @@ -258,7 +258,7 @@ object MultiNodeSpec { * `AskTimeoutException: sending to terminated ref breaks promises`. Using lazy * val is fine. */ -abstract class MultiNodeSpec(val myself: RoleName, _system: ActorSystem, _roles: immutable.Seq[RoleName], deployments: RoleName ⇒ Seq[String]) +abstract class MultiNodeSpec(val myself: RoleName, _system: ActorSystem, _roles: immutable.Seq[RoleName], deployments: RoleName => Seq[String]) extends TestKit(_system) with MultiNodeSpecCallbacks { import MultiNodeSpec._ @@ -268,20 +268,20 @@ abstract class MultiNodeSpec(val myself: RoleName, _system: ActorSystem, _roles: * the multi node spec (the `Config` passed to the creator must be used in * the created actor system for the multi node tests to work) */ - def this(config: MultiNodeConfig, actorSystemCreator: Config ⇒ ActorSystem) = + def this(config: MultiNodeConfig, actorSystemCreator: Config => ActorSystem) = this(config.myself, actorSystemCreator(ConfigFactory.load(config.config)), config.roles, config.deployments) def this(config: MultiNodeConfig) = this(config, { val name = MultiNodeSpec.getCallerName(classOf[MultiNodeSpec]) - config ⇒ + config => try { ActorSystem(name, config) } catch { // Retry creating the system once as when using port = 0 two systems may try and use the same one. // RTE is for aeron, CE for netty - case _: RemoteTransportException ⇒ ActorSystem(name, config) - case _: ChannelException ⇒ ActorSystem(name, config) + case _: RemoteTransportException => ActorSystem(name, config) + case _: ChannelException => ActorSystem(name, config) } }) @@ -366,7 +366,7 @@ abstract class MultiNodeSpec(val myself: RoleName, _system: ActorSystem, _roles: * Execute the given block of code only on the given nodes (names according * to the `roleMap`). */ - def runOn(nodes: RoleName*)(thunk: ⇒ Unit): Unit = { + def runOn(nodes: RoleName*)(thunk: => Unit): Unit = { if (isNode(nodes: _*)) { thunk } @@ -417,7 +417,7 @@ abstract class MultiNodeSpec(val myself: RoleName, _system: ActorSystem, _roles: else tc.startClient(myself, controllerAddr) try Await.result(startFuture, timeout) catch { - case NonFatal(x) ⇒ throw new RuntimeException("failure while attaching new conductor", x) + case NonFatal(x) => throw new RuntimeException("failure while attaching new conductor", x) } testConductor = tc } @@ -430,20 +430,20 @@ abstract class MultiNodeSpec(val myself: RoleName, _system: ActorSystem, _roles: lazy val addr = node(role).address.toString } - private val replacements = roles map (r ⇒ Replacement("@" + r.name + "@", r)) + private val replacements = roles map (r => Replacement("@" + r.name + "@", r)) protected def injectDeployments(sys: ActorSystem, role: RoleName): Unit = { val deployer = sys.asInstanceOf[ExtendedActorSystem].provider.deployer - deployments(role) foreach { str ⇒ + deployments(role) foreach { str => val deployString = replacements.foldLeft(str) { - case (base, r @ Replacement(tag, _)) ⇒ + case (base, r @ Replacement(tag, _)) => base.indexOf(tag) match { - case -1 ⇒ base - case start ⇒ + case -1 => base + case start => val replaceWith = try r.addr catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // might happen if all test cases are ignored (excluded) and // controller node is finished/exited before r.addr is run // on the other nodes @@ -456,8 +456,8 @@ abstract class MultiNodeSpec(val myself: RoleName, _system: ActorSystem, _roles: } import scala.collection.JavaConverters._ ConfigFactory.parseString(deployString).root.asScala foreach { - case (key, value: ConfigObject) ⇒ deployer.parseConfig(key, value.toConfig) foreach deployer.deploy - case (key, x) ⇒ throw new IllegalArgumentException(s"key $key must map to deployment section, not simple value $x") + case (key, value: ConfigObject) => deployer.parseConfig(key, value.toConfig) foreach deployer.deploy + case (key, x) => throw new IllegalArgumentException(s"key $key must map to deployment section, not simple value $x") } } } diff --git a/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/PerfFlamesSupport.scala b/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/PerfFlamesSupport.scala index a209cf6948..a768be4705 100644 --- a/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/PerfFlamesSupport.scala +++ b/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/PerfFlamesSupport.scala @@ -14,7 +14,7 @@ import scala.concurrent.duration._ /** * INTERNAL API: Support trait allowing trivially recording perf metrics from [[MultiNodeSpec]]s */ -private[akka] trait PerfFlamesSupport { _: MultiNodeSpec ⇒ +private[akka] trait PerfFlamesSupport { _: MultiNodeSpec => /** * Runs `perf-java-flames` script on given node (JVM process). @@ -27,7 +27,7 @@ private[akka] trait PerfFlamesSupport { _: MultiNodeSpec ⇒ import scala.concurrent.ExecutionContext.Implicits.global val afterDelay = akka.pattern.after(delay, system.scheduler)(Future.successful("GO!")) - afterDelay onComplete { it ⇒ + afterDelay onComplete { it => import java.lang.management._ val name = ManagementFactory.getRuntimeMXBean.getName val pid = name.substring(0, name.indexOf('@')).toInt @@ -37,9 +37,9 @@ private[akka] trait PerfFlamesSupport { _: MultiNodeSpec ⇒ import scala.sys.process._ perfCommand.run(new ProcessLogger { - override def buffer[T](f: ⇒ T): T = f - override def out(s: ⇒ String): Unit = println(s"[perf @ $myself($pid)][OUT] " + s) - override def err(s: ⇒ String): Unit = println(s"[perf @ $myself($pid)][ERR] " + s) + override def buffer[T](f: => T): T = f + override def out(s: => String): Unit = println(s"[perf @ $myself($pid)][OUT] " + s) + override def err(s: => String): Unit = println(s"[perf @ $myself($pid)][ERR] " + s) }) } } diff --git a/akka-osgi/src/main/scala/akka/osgi/ActorSystemActivator.scala b/akka-osgi/src/main/scala/akka/osgi/ActorSystemActivator.scala index 8cef2bbba0..b04dfaf967 100644 --- a/akka-osgi/src/main/scala/akka/osgi/ActorSystemActivator.scala +++ b/akka-osgi/src/main/scala/akka/osgi/ActorSystemActivator.scala @@ -55,9 +55,9 @@ abstract class ActorSystemActivator extends BundleActivator { val logServiceListner = new ServiceListener { def serviceChanged(event: ServiceEvent): Unit = { event.getType match { - case ServiceEvent.REGISTERED ⇒ + case ServiceEvent.REGISTERED => system.eventStream.publish(serviceForReference[LogService](context, event.getServiceReference)) - case ServiceEvent.UNREGISTERING ⇒ system.eventStream.publish(UnregisteringLogService) + case ServiceEvent.UNREGISTERING => system.eventStream.publish(UnregisteringLogService) } } } @@ -65,7 +65,7 @@ abstract class ActorSystemActivator extends BundleActivator { context.addServiceListener(logServiceListner, filter) //Small trick to create an event if the service is registered before this start listing for - Option(context.getServiceReference(classOf[LogService].getName)).foreach(x ⇒ { + Option(context.getServiceReference(classOf[LogService].getName)).foreach(x => { logServiceListner.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, x)) }) } diff --git a/akka-osgi/src/main/scala/akka/osgi/BundleDelegatingClassLoader.scala b/akka-osgi/src/main/scala/akka/osgi/BundleDelegatingClassLoader.scala index 92d142a4ba..fa89687af6 100644 --- a/akka-osgi/src/main/scala/akka/osgi/BundleDelegatingClassLoader.scala +++ b/akka-osgi/src/main/scala/akka/osgi/BundleDelegatingClassLoader.scala @@ -40,8 +40,8 @@ class BundleDelegatingClassLoader(bundle: Bundle, fallBackClassLoader: ClassLoad @tailrec def find(remaining: List[Bundle]): Class[_] = { if (remaining.isEmpty) throw new ClassNotFoundException(name) else Try { remaining.head.loadClass(name) } match { - case Success(cls) ⇒ cls - case Failure(_) ⇒ find(remaining.tail) + case Success(cls) => cls + case Failure(_) => find(remaining.tail) } } find(bundles) @@ -51,8 +51,8 @@ class BundleDelegatingClassLoader(bundle: Bundle, fallBackClassLoader: ClassLoad @tailrec def find(remaining: List[Bundle]): URL = { if (remaining.isEmpty) getParent.getResource(name) else Option { remaining.head.getResource(name) } match { - case Some(r) ⇒ r - case None ⇒ find(remaining.tail) + case Some(r) => r + case None => find(remaining.tail) } } find(bundles) @@ -60,7 +60,7 @@ class BundleDelegatingClassLoader(bundle: Bundle, fallBackClassLoader: ClassLoad override def findResources(name: String): Enumeration[URL] = { val resources = bundles.flatMap { - bundle ⇒ Option(bundle.getResources(name)).map { _.asScala.toList }.getOrElse(Nil) + bundle => Option(bundle.getResources(name)).map { _.asScala.toList }.getOrElse(Nil) } java.util.Collections.enumeration(resources.asJava) } @@ -81,7 +81,7 @@ class BundleDelegatingClassLoader(bundle: Bundle, fallBackClassLoader: ClassLoad val requiredWires: List[BundleWire] = wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE).asScala.toList requiredWires.flatMap { - wire ⇒ Option(wire.getProviderWiring) map { _.getBundle } + wire => Option(wire.getProviderWiring) map { _.getBundle } }.toSet } process(processed + b, rest ++ (direct diff processed)) diff --git a/akka-osgi/src/main/scala/akka/osgi/DefaultOSGiLogger.scala b/akka-osgi/src/main/scala/akka/osgi/DefaultOSGiLogger.scala index bb37c10821..2777f9a840 100644 --- a/akka-osgi/src/main/scala/akka/osgi/DefaultOSGiLogger.scala +++ b/akka-osgi/src/main/scala/akka/osgi/DefaultOSGiLogger.scala @@ -35,15 +35,15 @@ class DefaultOSGiLogger extends DefaultLogger { * @param logService OSGi LogService that has been registered, */ def setLogService(logService: LogService): Unit = { - messagesToLog.foreach(x ⇒ { + messagesToLog.foreach(x => { logMessage(logService, x) }) context.become(initialisedReceive(logService)) } { - case logService: LogService ⇒ setLogService(logService) - case logEvent: LogEvent ⇒ messagesToLog :+= logEvent + case logService: LogService => setLogService(logService) + case logEvent: LogEvent => messagesToLog :+= logEvent } } @@ -57,8 +57,8 @@ class DefaultOSGiLogger extends DefaultLogger { context.system.eventStream.unsubscribe(self, classOf[LogService]) { - case logEvent: LogEvent ⇒ logMessage(logService, logEvent) - case UnregisteringLogService ⇒ context.become(uninitialisedReceive) + case logEvent: LogEvent => logMessage(logService, logEvent) + case UnregisteringLogService => context.become(uninitialisedReceive) } } @@ -70,9 +70,9 @@ class DefaultOSGiLogger extends DefaultLogger { */ def logMessage(logService: LogService, event: LogEvent): Unit = { event match { - case error: Logging.Error if error.cause != NoCause ⇒ + case error: Logging.Error if error.cause != NoCause => logService.log(event.level.asInt, messageFormat.format(timestamp(event), event.thread.getName, event.logSource, event.message), error.cause) - case _ ⇒ + case _ => logService.log(event.level.asInt, messageFormat.format(timestamp(event), event.thread.getName, event.logSource, event.message)) } } diff --git a/akka-osgi/src/test/scala/akka/osgi/PojoSRTestSupport.scala b/akka-osgi/src/test/scala/akka/osgi/PojoSRTestSupport.scala index 2f1bdf40e0..7ce6c63b43 100644 --- a/akka-osgi/src/test/scala/akka/osgi/PojoSRTestSupport.scala +++ b/akka-osgi/src/test/scala/akka/osgi/PojoSRTestSupport.scala @@ -49,7 +49,7 @@ trait PojoSRTestSupport extends Suite with BeforeAndAfterAll { try { ServiceLoader.load(classOf[PojoServiceRegistryFactory]).iterator.next.newPojoServiceRegistry(config).getBundleContext } catch { - case e: Throwable ⇒ oldErr.write(bufferedLoadingErrors.toByteArray); throw e + case e: Throwable => oldErr.write(bufferedLoadingErrors.toByteArray); throw e } finally { System.setErr(oldErr) } @@ -76,13 +76,13 @@ trait PojoSRTestSupport extends Suite with BeforeAndAfterAll { def awaitReference[T](serviceType: Class[T], wait: FiniteDuration): ServiceReference[T] = { @tailrec def poll(step: Duration, deadline: Deadline): ServiceReference[T] = context.getServiceReference(serviceType.getName) match { - case null ⇒ + case null => if (deadline.isOverdue()) fail("Gave up waiting for service of type %s".format(serviceType)) else { Thread.sleep((step min deadline.timeLeft max Duration.Zero).toMillis) poll(step, deadline) } - case some ⇒ some.asInstanceOf[ServiceReference[T]] + case some => some.asInstanceOf[ServiceReference[T]] } poll(wait, Deadline.now + MaxWaitDuration) @@ -91,8 +91,8 @@ trait PojoSRTestSupport extends Suite with BeforeAndAfterAll { protected def buildTestBundles(builders: immutable.Seq[BundleDescriptorBuilder]): immutable.Seq[BundleDescriptor] = builders map (_.build) - def filterErrors()(block: ⇒ Unit): Unit = - try block catch { case e: Throwable ⇒ System.err.write(bufferedLoadingErrors.toByteArray); throw e } + def filterErrors()(block: => Unit): Unit = + try block catch { case e: Throwable => System.err.write(bufferedLoadingErrors.toByteArray); throw e } } object PojoSRTestSupport { @@ -148,7 +148,7 @@ class BundleDescriptorBuilder(name: String) { val headers = new HashMap[String, String]() val jis = new JarInputStream(new FileInputStream(file)) try { - for (entry ← jis.getManifest.getMainAttributes.entrySet.asScala) + for (entry <- jis.getManifest.getMainAttributes.entrySet.asScala) headers.put(entry.getKey.toString, entry.getValue.toString) } finally jis.close() diff --git a/akka-osgi/src/test/scala/akka/osgi/test/PingPong.scala b/akka-osgi/src/test/scala/akka/osgi/test/PingPong.scala index 3678467d18..2b190ab3bc 100644 --- a/akka-osgi/src/test/scala/akka/osgi/test/PingPong.scala +++ b/akka-osgi/src/test/scala/akka/osgi/test/PingPong.scala @@ -18,7 +18,7 @@ object PingPong { class PongActor extends Actor { def receive = { - case Ping ⇒ + case Ping => sender() ! Pong } } diff --git a/akka-osgi/src/test/scala/docs/osgi/Activator.scala b/akka-osgi/src/test/scala/docs/osgi/Activator.scala index 27e0454387..7d957c5b2f 100644 --- a/akka-osgi/src/test/scala/docs/osgi/Activator.scala +++ b/akka-osgi/src/test/scala/docs/osgi/Activator.scala @@ -7,7 +7,7 @@ package docs.osgi case object SomeMessage class SomeActor extends akka.actor.Actor { - def receive = { case SomeMessage ⇒ } + def receive = { case SomeMessage => } } //#Activator diff --git a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/AllPersistenceIdsPublisher.scala b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/AllPersistenceIdsPublisher.scala index a274739047..162b0d615f 100644 --- a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/AllPersistenceIdsPublisher.scala +++ b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/AllPersistenceIdsPublisher.scala @@ -36,31 +36,31 @@ private[akka] class AllPersistenceIdsPublisher(liveQuery: Boolean, maxBufSize: I def receive = init def init: Receive = { - case _: Request ⇒ + case _: Request => journal ! LeveldbJournal.SubscribeAllPersistenceIds context.become(active) - case Cancel ⇒ context.stop(self) + case Cancel => context.stop(self) } def active: Receive = { - case LeveldbJournal.CurrentPersistenceIds(allPersistenceIds) ⇒ + case LeveldbJournal.CurrentPersistenceIds(allPersistenceIds) => buf ++= allPersistenceIds deliverBuf() if (!liveQuery && buf.isEmpty) onCompleteThenStop() - case LeveldbJournal.PersistenceIdAdded(persistenceId) ⇒ + case LeveldbJournal.PersistenceIdAdded(persistenceId) => if (liveQuery) { buf :+= persistenceId deliverBuf() } - case _: Request ⇒ + case _: Request => deliverBuf() if (!liveQuery && buf.isEmpty) onCompleteThenStop() - case Cancel ⇒ context.stop(self) + case Cancel => context.stop(self) } } diff --git a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/DeliveryBuffer.scala b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/DeliveryBuffer.scala index 897718dfbd..bcf92de37b 100644 --- a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/DeliveryBuffer.scala +++ b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/DeliveryBuffer.scala @@ -9,7 +9,7 @@ import akka.stream.actor.ActorPublisher /** * INTERNAL API */ -private[akka] trait DeliveryBuffer[T] { _: ActorPublisher[T] ⇒ +private[akka] trait DeliveryBuffer[T] { _: ActorPublisher[T] => var buf = Vector.empty[T] diff --git a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/EventsByPersistenceIdPublisher.scala b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/EventsByPersistenceIdPublisher.scala index 9e76fc0639..1981be3fd0 100644 --- a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/EventsByPersistenceIdPublisher.scala +++ b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/EventsByPersistenceIdPublisher.scala @@ -21,10 +21,10 @@ private[akka] object EventsByPersistenceIdPublisher { def props(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, refreshInterval: Option[FiniteDuration], maxBufSize: Int, writeJournalPluginId: String): Props = { refreshInterval match { - case Some(interval) ⇒ + case Some(interval) => Props(new LiveEventsByPersistenceIdPublisher(persistenceId, fromSequenceNr, toSequenceNr, interval, maxBufSize, writeJournalPluginId)) - case None ⇒ + case None => Props(new CurrentEventsByPersistenceIdPublisher(persistenceId, fromSequenceNr, toSequenceNr, maxBufSize, writeJournalPluginId)) } @@ -55,22 +55,22 @@ private[akka] abstract class AbstractEventsByPersistenceIdPublisher( def receive = init def init: Receive = { - case _: Request ⇒ receiveInitialRequest() - case Continue ⇒ // skip, wait for first Request - case Cancel ⇒ context.stop(self) + case _: Request => receiveInitialRequest() + case Continue => // skip, wait for first Request + case Cancel => context.stop(self) } def receiveInitialRequest(): Unit def idle: Receive = { - case Continue | _: LeveldbJournal.EventAppended ⇒ + case Continue | _: LeveldbJournal.EventAppended => if (timeForReplay) replay() - case _: Request ⇒ + case _: Request => receiveIdleRequest() - case Cancel ⇒ + case Cancel => context.stop(self) } @@ -87,7 +87,7 @@ private[akka] abstract class AbstractEventsByPersistenceIdPublisher( } def replaying(limit: Int): Receive = { - case ReplayedMessage(p) ⇒ + case ReplayedMessage(p) => buf :+= EventEnvelope( offset = Sequence(p.sequenceNr), persistenceId = persistenceId, @@ -96,21 +96,21 @@ private[akka] abstract class AbstractEventsByPersistenceIdPublisher( currSeqNo = p.sequenceNr + 1 deliverBuf() - case RecoverySuccess(highestSeqNr) ⇒ + case RecoverySuccess(highestSeqNr) => log.debug("replay completed for persistenceId [{}], currSeqNo [{}]", persistenceId, currSeqNo) receiveRecoverySuccess(highestSeqNr) - case ReplayMessagesFailure(cause) ⇒ + case ReplayMessagesFailure(cause) => log.debug("replay failed for persistenceId [{}], due to [{}]", persistenceId, cause.getMessage) deliverBuf() onErrorThenStop(cause) - case _: Request ⇒ + case _: Request => deliverBuf() - case Continue | _: LeveldbJournal.EventAppended ⇒ // skip during replay + case Continue | _: LeveldbJournal.EventAppended => // skip during replay - case Cancel ⇒ + case Cancel => context.stop(self) } diff --git a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/EventsByTagPublisher.scala b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/EventsByTagPublisher.scala index 7c6c8e04ab..ba8e5f0193 100644 --- a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/EventsByTagPublisher.scala +++ b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/EventsByTagPublisher.scala @@ -23,10 +23,10 @@ private[akka] object EventsByTagPublisher { def props(tag: String, fromOffset: Long, toOffset: Long, refreshInterval: Option[FiniteDuration], maxBufSize: Int, writeJournalPluginId: String): Props = { refreshInterval match { - case Some(interval) ⇒ + case Some(interval) => Props(new LiveEventsByTagPublisher(tag, fromOffset, toOffset, interval, maxBufSize, writeJournalPluginId)) - case None ⇒ + case None => Props(new CurrentEventsByTagPublisher(tag, fromOffset, toOffset, maxBufSize, writeJournalPluginId)) } @@ -57,22 +57,22 @@ private[akka] abstract class AbstractEventsByTagPublisher( def receive = init def init: Receive = { - case _: Request ⇒ receiveInitialRequest() - case Continue ⇒ // skip, wait for first Request - case Cancel ⇒ context.stop(self) + case _: Request => receiveInitialRequest() + case Continue => // skip, wait for first Request + case Cancel => context.stop(self) } def receiveInitialRequest(): Unit def idle: Receive = { - case Continue | _: LeveldbJournal.TaggedEventAppended ⇒ + case Continue | _: LeveldbJournal.TaggedEventAppended => if (timeForReplay) replay() - case _: Request ⇒ + case _: Request => receiveIdleRequest() - case Cancel ⇒ + case Cancel => context.stop(self) } @@ -89,7 +89,7 @@ private[akka] abstract class AbstractEventsByTagPublisher( } def replaying(limit: Int): Receive = { - case ReplayedTaggedMessage(p, _, offset) ⇒ + case ReplayedTaggedMessage(p, _, offset) => buf :+= EventEnvelope( offset = Sequence(offset), persistenceId = p.persistenceId, @@ -98,21 +98,21 @@ private[akka] abstract class AbstractEventsByTagPublisher( currOffset = offset deliverBuf() - case RecoverySuccess(highestSeqNr) ⇒ + case RecoverySuccess(highestSeqNr) => log.debug("replay completed for tag [{}], currOffset [{}]", tag, currOffset) receiveRecoverySuccess(highestSeqNr) - case ReplayMessagesFailure(cause) ⇒ + case ReplayMessagesFailure(cause) => log.debug("replay failed for tag [{}], due to [{}]", tag, cause.getMessage) deliverBuf() onErrorThenStop(cause) - case _: Request ⇒ + case _: Request => deliverBuf() - case Continue | _: LeveldbJournal.TaggedEventAppended ⇒ // skip during replay + case Continue | _: LeveldbJournal.TaggedEventAppended => // skip during replay - case Cancel ⇒ + case Cancel => context.stop(self) } diff --git a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/scaladsl/LeveldbReadJournal.scala b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/scaladsl/LeveldbReadJournal.scala index 7c500e6f43..8756ac7e2b 100644 --- a/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/scaladsl/LeveldbReadJournal.scala +++ b/akka-persistence-query/src/main/scala/akka/persistence/query/journal/leveldb/scaladsl/LeveldbReadJournal.scala @@ -62,7 +62,7 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) extends Re override def persistenceIds(): Source[String, NotUsed] = { // no polling for this query, the write journal will push all changes, i.e. no refreshInterval Source.actorPublisher[String](AllPersistenceIdsPublisher.props(liveQuery = true, maxBufSize, writeJournalPluginId)) - .mapMaterializedValue(_ ⇒ NotUsed) + .mapMaterializedValue(_ => NotUsed) .named("allPersistenceIds") } @@ -73,7 +73,7 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) extends Re */ override def currentPersistenceIds(): Source[String, NotUsed] = { Source.actorPublisher[String](AllPersistenceIdsPublisher.props(liveQuery = false, maxBufSize, writeJournalPluginId)) - .mapMaterializedValue(_ ⇒ NotUsed) + .mapMaterializedValue(_ => NotUsed) .named("currentPersistenceIds") } @@ -106,7 +106,7 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) extends Re override def eventsByPersistenceId(persistenceId: String, fromSequenceNr: Long = 0L, toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = { Source.actorPublisher[EventEnvelope](EventsByPersistenceIdPublisher.props(persistenceId, fromSequenceNr, toSequenceNr, - refreshInterval, maxBufSize, writeJournalPluginId)).mapMaterializedValue(_ ⇒ NotUsed) + refreshInterval, maxBufSize, writeJournalPluginId)).mapMaterializedValue(_ => NotUsed) .named("eventsByPersistenceId-" + persistenceId) } @@ -118,7 +118,7 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) extends Re override def currentEventsByPersistenceId(persistenceId: String, fromSequenceNr: Long = 0L, toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = { Source.actorPublisher[EventEnvelope](EventsByPersistenceIdPublisher.props(persistenceId, fromSequenceNr, toSequenceNr, - None, maxBufSize, writeJournalPluginId)).mapMaterializedValue(_ ⇒ NotUsed) + None, maxBufSize, writeJournalPluginId)).mapMaterializedValue(_ => NotUsed) .named("currentEventsByPersistenceId-" + persistenceId) } @@ -163,13 +163,13 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) extends Re */ override def eventsByTag(tag: String, offset: Offset = Sequence(0L)): Source[EventEnvelope, NotUsed] = offset match { - case seq: Sequence ⇒ + case seq: Sequence => Source.actorPublisher[EventEnvelope](EventsByTagPublisher.props(tag, seq.value, Long.MaxValue, refreshInterval, maxBufSize, writeJournalPluginId)) - .mapMaterializedValue(_ ⇒ NotUsed) + .mapMaterializedValue(_ => NotUsed) .named("eventsByTag-" + URLEncoder.encode(tag, ByteString.UTF_8)) - case NoOffset ⇒ eventsByTag(tag, Sequence(0L)) //recursive - case _ ⇒ + case NoOffset => eventsByTag(tag, Sequence(0L)) //recursive + case _ => throw new IllegalArgumentException("LevelDB does not support " + Logging.simpleName(offset.getClass) + " offsets") } @@ -180,12 +180,12 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) extends Re */ override def currentEventsByTag(tag: String, offset: Offset = Sequence(0L)): Source[EventEnvelope, NotUsed] = offset match { - case seq: Sequence ⇒ + case seq: Sequence => Source.actorPublisher[EventEnvelope](EventsByTagPublisher.props(tag, seq.value, Long.MaxValue, - None, maxBufSize, writeJournalPluginId)).mapMaterializedValue(_ ⇒ NotUsed) + None, maxBufSize, writeJournalPluginId)).mapMaterializedValue(_ => NotUsed) .named("currentEventsByTag-" + URLEncoder.encode(tag, ByteString.UTF_8)) - case NoOffset ⇒ currentEventsByTag(tag, Sequence(0L)) //recursive - case _ ⇒ + case NoOffset => currentEventsByTag(tag, Sequence(0L)) //recursive + case _ => throw new IllegalArgumentException("LevelDB does not support " + Logging.simpleName(offset.getClass) + " offsets") } diff --git a/akka-persistence-query/src/test/scala/akka/persistence/query/DummyReadJournal.scala b/akka-persistence-query/src/test/scala/akka/persistence/query/DummyReadJournal.scala index dfbf12862b..08ac28c865 100644 --- a/akka-persistence-query/src/test/scala/akka/persistence/query/DummyReadJournal.scala +++ b/akka-persistence-query/src/test/scala/akka/persistence/query/DummyReadJournal.scala @@ -15,7 +15,7 @@ import akka.actor.ExtendedActorSystem */ class DummyReadJournal(val dummyValue: String) extends scaladsl.ReadJournal with scaladsl.PersistenceIdsQuery { override def persistenceIds(): Source[String, NotUsed] = - Source.fromIterator(() ⇒ Iterator.from(0)).map(_.toString) + Source.fromIterator(() => Iterator.from(0)).map(_.toString) } object DummyReadJournal { diff --git a/akka-persistence-query/src/test/scala/akka/persistence/query/PersistenceQuerySpec.scala b/akka-persistence-query/src/test/scala/akka/persistence/query/PersistenceQuerySpec.scala index 66acb5cbcf..feaf1b2991 100644 --- a/akka-persistence-query/src/test/scala/akka/persistence/query/PersistenceQuerySpec.scala +++ b/akka-persistence-query/src/test/scala/akka/persistence/query/PersistenceQuerySpec.scala @@ -37,7 +37,7 @@ class PersistenceQuerySpec extends WordSpecLike with Matchers with BeforeAndAfte "ReadJournal" must { "be found by full config key" in { - withActorSystem() { system ⇒ + withActorSystem() { system => val readJournalPluginConfig: Config = ConfigFactory.parseString(customReadJournalPluginConfig) PersistenceQuery.get(system).readJournalFor[DummyReadJournal]( DummyReadJournal.Identifier, readJournalPluginConfig) @@ -61,7 +61,7 @@ class PersistenceQuerySpec extends WordSpecLike with Matchers with BeforeAndAfte } "throw if unable to find query journal by config key" in { - withActorSystem() { system ⇒ + withActorSystem() { system => intercept[IllegalArgumentException] { PersistenceQuery.get(system).readJournalFor[DummyReadJournal](DummyReadJournal.Identifier + "-unknown") }.getMessage should include("missing persistence plugin") @@ -72,7 +72,7 @@ class PersistenceQuerySpec extends WordSpecLike with Matchers with BeforeAndAfte private val systemCounter = new AtomicInteger() - private def withActorSystem(conf: String = "")(block: ActorSystem ⇒ Unit): Unit = { + private def withActorSystem(conf: String = "")(block: ActorSystem => Unit): Unit = { val config = DummyReadJournalProvider.config .withFallback(DummyJavaReadJournalProvider.config) diff --git a/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/AllPersistenceIdsSpec.scala b/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/AllPersistenceIdsSpec.scala index 92bc908e98..da399105bd 100644 --- a/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/AllPersistenceIdsSpec.scala +++ b/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/AllPersistenceIdsSpec.scala @@ -68,7 +68,7 @@ class AllPersistenceIdsSpec extends AkkaSpec(AllPersistenceIdsSpec.config) probe.expectNext("e") val more = (1 to 100).map("f" + _) - more.foreach { p ⇒ + more.foreach { p => system.actorOf(TestActor.props(p)) ! p } diff --git a/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/Cleanup.scala b/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/Cleanup.scala index ecdf24f0d8..e61d5bbb8f 100644 --- a/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/Cleanup.scala +++ b/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/Cleanup.scala @@ -8,11 +8,11 @@ import akka.testkit.AkkaSpec import java.io.File import org.apache.commons.io.FileUtils -trait Cleanup { this: AkkaSpec ⇒ +trait Cleanup { this: AkkaSpec => val storageLocations = List( "akka.persistence.journal.leveldb.dir", "akka.persistence.journal.leveldb-shared.store.dir", - "akka.persistence.snapshot-store.local.dir").map(s ⇒ new File(system.settings.config.getString(s))) + "akka.persistence.snapshot-store.local.dir").map(s => new File(system.settings.config.getString(s))) override protected def atStartup(): Unit = { storageLocations.foreach(FileUtils.deleteDirectory) diff --git a/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/EventsByTagSpec.scala b/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/EventsByTagSpec.scala index c5da829bb9..e8b4555c42 100644 --- a/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/EventsByTagSpec.scala +++ b/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/EventsByTagSpec.scala @@ -38,11 +38,11 @@ object EventsByTagSpec { class ColorTagger extends WriteEventAdapter { val colors = Set("green", "black", "blue") override def toJournal(event: Any): Any = event match { - case s: String ⇒ - var tags = colors.foldLeft(Set.empty[String])((acc, c) ⇒ if (s.contains(c)) acc + c else acc) + case s: String => + var tags = colors.foldLeft(Set.empty[String])((acc, c) => if (s.contains(c)) acc + c else acc) if (tags.isEmpty) event else Tagged(event, tags) - case _ ⇒ event + case _ => event } override def manifest(event: Any): String = "" diff --git a/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/TestActor.scala b/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/TestActor.scala index 030c4efa25..161bf49c86 100644 --- a/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/TestActor.scala +++ b/akka-persistence-query/src/test/scala/akka/persistence/query/journal/leveldb/TestActor.scala @@ -19,16 +19,16 @@ class TestActor(override val persistenceId: String) extends PersistentActor { import TestActor.DeleteCmd val receiveRecover: Receive = { - case evt: String ⇒ + case evt: String => } val receiveCommand: Receive = { - case DeleteCmd(toSeqNr) ⇒ + case DeleteCmd(toSeqNr) => deleteMessages(toSeqNr) sender() ! s"$toSeqNr-deleted" - case cmd: String ⇒ - persist(cmd) { evt ⇒ + case cmd: String => + persist(cmd) { evt => sender() ! evt + "-done" } } diff --git a/akka-persistence-shared/src/test/scala/akka/persistence/journal/leveldb/PersistencePluginProxySpec.scala b/akka-persistence-shared/src/test/scala/akka/persistence/journal/leveldb/PersistencePluginProxySpec.scala index 3e4f5f9227..c005351347 100644 --- a/akka-persistence-shared/src/test/scala/akka/persistence/journal/leveldb/PersistencePluginProxySpec.scala +++ b/akka-persistence-shared/src/test/scala/akka/persistence/journal/leveldb/PersistencePluginProxySpec.scala @@ -61,13 +61,13 @@ object PersistencePluginProxySpec { class ExamplePersistentActor(probe: ActorRef, name: String) extends NamedPersistentActor(name) { override def receiveRecover = { - case RecoveryCompleted ⇒ // ignore - case payload ⇒ + case RecoveryCompleted => // ignore + case payload => probe ! payload } override def receiveCommand = { - case payload ⇒ - persist(payload) { _ ⇒ + case payload => + persist(payload) { _ => probe ! payload } } @@ -77,7 +77,7 @@ object PersistencePluginProxySpec { val p = context.actorOf(Props(classOf[ExamplePersistentActor], probe, context.system.name)) def receive = { - case m ⇒ p forward m + case m => p forward m } } diff --git a/akka-persistence-shared/src/test/scala/akka/persistence/journal/leveldb/SharedLeveldbJournalSpec.scala b/akka-persistence-shared/src/test/scala/akka/persistence/journal/leveldb/SharedLeveldbJournalSpec.scala index 8f839d2671..8c1de5986d 100644 --- a/akka-persistence-shared/src/test/scala/akka/persistence/journal/leveldb/SharedLeveldbJournalSpec.scala +++ b/akka-persistence-shared/src/test/scala/akka/persistence/journal/leveldb/SharedLeveldbJournalSpec.scala @@ -41,11 +41,11 @@ object SharedLeveldbJournalSpec { class ExamplePersistentActor(probe: ActorRef, name: String) extends NamedPersistentActor(name) { override def receiveRecover = { - case RecoveryCompleted ⇒ // ignore - case payload ⇒ probe ! payload + case RecoveryCompleted => // ignore + case payload => probe ! payload } override def receiveCommand = { - case payload ⇒ persist(payload) { _ ⇒ + case payload => persist(payload) { _ => probe ! payload } } @@ -55,8 +55,8 @@ object SharedLeveldbJournalSpec { val p = context.actorOf(Props(classOf[ExamplePersistentActor], probe, context.system.name)) def receive = { - case ActorIdentity(1, Some(store)) ⇒ SharedLeveldbJournal.setStore(store, context.system) - case m ⇒ p forward m + case ActorIdentity(1, Some(store)) => SharedLeveldbJournal.setStore(store, context.system) + case m => p forward m } override def preStart(): Unit = diff --git a/akka-persistence-shared/src/test/scala/akka/persistence/serialization/SerializerSpec.scala b/akka-persistence-shared/src/test/scala/akka/persistence/serialization/SerializerSpec.scala index 6a6e92abd1..421b57717a 100644 --- a/akka-persistence-shared/src/test/scala/akka/persistence/serialization/SerializerSpec.scala +++ b/akka-persistence-shared/src/test/scala/akka/persistence/serialization/SerializerSpec.scala @@ -60,7 +60,7 @@ object SerializerSpecConfigs { """) def config(configs: String*): Config = - configs.foldLeft(ConfigFactory.empty)((r, c) ⇒ r.withFallback(ConfigFactory.parseString(c))) + configs.foldLeft(ConfigFactory.empty)((r, c) => r.withFallback(ConfigFactory.parseString(c))) } @@ -297,16 +297,16 @@ class MessageSerializerPersistenceSpec extends AkkaSpec(customSerializers) { object MessageSerializerRemotingSpec { class LocalActor(port: Int) extends Actor { def receive = { - case m ⇒ context.actorSelection(s"akka.tcp://remote@127.0.0.1:${port}/user/remote").tell(m, Actor.noSender) + case m => context.actorSelection(s"akka.tcp://remote@127.0.0.1:${port}/user/remote").tell(m, Actor.noSender) } } class RemoteActor extends Actor { def receive = { - case p @ PersistentRepr(MyPayload(data), _) ⇒ p.sender ! s"p${data}" - case a: AtomicWrite ⇒ + case p @ PersistentRepr(MyPayload(data), _) => p.sender ! s"p${data}" + case a: AtomicWrite => a.payload.foreach { - case p @ PersistentRepr(MyPayload(data), _) ⇒ p.sender ! s"p${data}" + case p @ PersistentRepr(MyPayload(data), _) => p.sender ! s"p${data}" } } } @@ -376,13 +376,13 @@ class MyPayloadSerializer extends Serializer { def includeManifest: Boolean = true def toBinary(o: AnyRef): Array[Byte] = o match { - case MyPayload(data) ⇒ s".${data}".getBytes(UTF_8) + case MyPayload(data) => s".${data}".getBytes(UTF_8) } def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = manifest match { - case Some(MyPayloadClass) ⇒ MyPayload(s"${new String(bytes, UTF_8)}.") - case Some(c) ⇒ throw new Exception(s"unexpected manifest ${c}") - case None ⇒ throw new Exception("no manifest") + case Some(MyPayloadClass) => MyPayload(s"${new String(bytes, UTF_8)}.") + case Some(c) => throw new Exception(s"unexpected manifest ${c}") + case None => throw new Exception("no manifest") } } @@ -397,16 +397,16 @@ class MyPayload2Serializer extends SerializerWithStringManifest { def manifest(o: AnyRef): String = ManifestV2 def toBinary(o: AnyRef): Array[Byte] = o match { - case MyPayload2(data, n) ⇒ s".$data:$n".getBytes(UTF_8) + case MyPayload2(data, n) => s".$data:$n".getBytes(UTF_8) } def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case ManifestV2 ⇒ + case ManifestV2 => val parts = new String(bytes, UTF_8).split(":") MyPayload2(data = parts(0) + ".", n = parts(1).toInt) - case ManifestV1 ⇒ + case ManifestV1 => MyPayload2(data = s"${new String(bytes, UTF_8)}.", n = 0) - case other ⇒ + case other => throw new Exception(s"unexpected manifest [$other]") } } @@ -418,13 +418,13 @@ class MySnapshotSerializer extends Serializer { def includeManifest: Boolean = true def toBinary(o: AnyRef): Array[Byte] = o match { - case MySnapshot(data) ⇒ s".${data}".getBytes(UTF_8) + case MySnapshot(data) => s".${data}".getBytes(UTF_8) } def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = manifest match { - case Some(MySnapshotClass) ⇒ MySnapshot(s"${new String(bytes, UTF_8)}.") - case Some(c) ⇒ throw new Exception(s"unexpected manifest ${c}") - case None ⇒ throw new Exception("no manifest") + case Some(MySnapshotClass) => MySnapshot(s"${new String(bytes, UTF_8)}.") + case Some(c) => throw new Exception(s"unexpected manifest ${c}") + case None => throw new Exception("no manifest") } } @@ -437,13 +437,13 @@ class MySnapshotSerializer2 extends SerializerWithStringManifest { def manifest(o: AnyRef): String = CurrentManifest def toBinary(o: AnyRef): Array[Byte] = o match { - case MySnapshot2(data) ⇒ s".${data}".getBytes(UTF_8) + case MySnapshot2(data) => s".${data}".getBytes(UTF_8) } def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case CurrentManifest | OldManifest ⇒ + case CurrentManifest | OldManifest => MySnapshot2(s"${new String(bytes, UTF_8)}.") - case other ⇒ + case other => throw new Exception(s"unexpected manifest [$other]") } } @@ -457,16 +457,16 @@ class OldPayloadSerializer extends SerializerWithStringManifest { def manifest(o: AnyRef): String = o.getClass.getName def toBinary(o: AnyRef): Array[Byte] = o match { - case MyPayload(data) ⇒ s".${data}".getBytes(UTF_8) - case old if old.getClass.getName == OldPayloadClassName ⇒ + case MyPayload(data) => s".${data}".getBytes(UTF_8) + case old if old.getClass.getName == OldPayloadClassName => o.toString.getBytes(UTF_8) } def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { - case OldPayloadClassName ⇒ + case OldPayloadClassName => MyPayload(new String(bytes, UTF_8)) - case MyPayloadClassName ⇒ MyPayload(s"${new String(bytes, UTF_8)}.") - case other ⇒ + case MyPayloadClassName => MyPayload(s"${new String(bytes, UTF_8)}.") + case other => throw new Exception(s"unexpected manifest [$other]") } } diff --git a/akka-persistence-tck/src/main/scala/akka/persistence/CapabilityFlags.scala b/akka-persistence-tck/src/main/scala/akka/persistence/CapabilityFlags.scala index 003170d36c..de7964631a 100644 --- a/akka-persistence-tck/src/main/scala/akka/persistence/CapabilityFlags.scala +++ b/akka-persistence-tck/src/main/scala/akka/persistence/CapabilityFlags.scala @@ -9,7 +9,7 @@ import scala.language.implicitConversions sealed abstract class CapabilityFlag { private val capturedStack = (new Throwable().getStackTrace) .filter(_.getMethodName.startsWith("supports")) - .find { el ⇒ + .find { el => val clazz = Class.forName(el.getClassName) clazz.getDeclaredMethod(el.getMethodName).getReturnType == classOf[CapabilityFlag] } map { _.getMethodName } getOrElse "[unknown]" diff --git a/akka-persistence-tck/src/main/scala/akka/persistence/TestSerializer.scala b/akka-persistence-tck/src/main/scala/akka/persistence/TestSerializer.scala index 06e3c47d52..1bb2ff2868 100644 --- a/akka-persistence-tck/src/main/scala/akka/persistence/TestSerializer.scala +++ b/akka-persistence-tck/src/main/scala/akka/persistence/TestSerializer.scala @@ -16,10 +16,10 @@ final case class TestPayload(ref: ActorRef) class TestSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest { def identifier: Int = 666 def manifest(o: AnyRef): String = o match { - case _: TestPayload ⇒ "A" + case _: TestPayload => "A" } def toBinary(o: AnyRef): Array[Byte] = o match { - case TestPayload(ref) ⇒ + case TestPayload(ref) => verifyTransportInfo() val refStr = Serialization.serializedActorPath(ref) refStr.getBytes(StandardCharsets.UTF_8) @@ -27,7 +27,7 @@ class TestSerializer(system: ExtendedActorSystem) extends SerializerWithStringMa def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { verifyTransportInfo() manifest match { - case "A" ⇒ + case "A" => val refStr = new String(bytes, StandardCharsets.UTF_8) val ref = system.provider.resolveActorRef(refStr) TestPayload(ref) @@ -36,9 +36,9 @@ class TestSerializer(system: ExtendedActorSystem) extends SerializerWithStringMa private def verifyTransportInfo(): Unit = { Serialization.currentTransportInformation.value match { - case null ⇒ + case null => throw new IllegalStateException("currentTransportInformation was not set") - case t ⇒ + case t => if (t.system ne system) throw new IllegalStateException( s"wrong system in currentTransportInformation, ${t.system} != $system") diff --git a/akka-persistence-tck/src/main/scala/akka/persistence/journal/JournalPerfSpec.scala b/akka-persistence-tck/src/main/scala/akka/persistence/journal/JournalPerfSpec.scala index 16aa83e683..f58834ad31 100644 --- a/akka-persistence-tck/src/main/scala/akka/persistence/journal/JournalPerfSpec.scala +++ b/akka-persistence-tck/src/main/scala/akka/persistence/journal/JournalPerfSpec.scala @@ -19,38 +19,38 @@ object JournalPerfSpec { var counter = 0 override def receiveCommand: Receive = { - case c @ Cmd("p", payload) ⇒ - persist(c) { d ⇒ + case c @ Cmd("p", payload) => + persist(c) { d => counter += 1 require(d.payload == counter, s"Expected to receive [$counter] yet got: [${d.payload}]") if (counter == replyAfter) replyTo ! d.payload } - case c @ Cmd("pa", payload) ⇒ - persistAsync(c) { d ⇒ + case c @ Cmd("pa", payload) => + persistAsync(c) { d => counter += 1 require(d.payload == counter, s"Expected to receive [$counter] yet got: [${d.payload}]") if (counter == replyAfter) replyTo ! d.payload } - case c @ Cmd("par", payload) ⇒ + case c @ Cmd("par", payload) => counter += 1 - persistAsync(c) { d ⇒ + persistAsync(c) { d => require(d.payload == counter, s"Expected to receive [$counter] yet got: [${d.payload}]") } if (counter == replyAfter) replyTo ! payload - case c @ Cmd("n", payload) ⇒ + case c @ Cmd("n", payload) => counter += 1 require(payload == counter, s"Expected to receive [$counter] yet got: [${payload}]") if (counter == replyAfter) replyTo ! payload - case ResetCounter ⇒ + case ResetCounter => counter = 0 } override def receiveRecover: Receive = { - case Cmd(_, payload) ⇒ + case Cmd(_, payload) => counter += 1 require(payload == counter, s"Expected to receive [$counter] yet got: [${payload}]") if (counter == replyAfter) replyTo ! payload @@ -84,12 +84,12 @@ abstract class JournalPerfSpec(config: Config) extends JournalSpec(config) { system.actorOf(Props(classOf[BenchActor], pid, testProbe.ref, replyAfter)) def feedAndExpectLast(actor: ActorRef, mode: String, cmnds: immutable.Seq[Int]): Unit = { - cmnds foreach { c ⇒ actor ! Cmd(mode, c) } + cmnds foreach { c => actor ! Cmd(mode, c) } testProbe.expectMsg(awaitDuration, cmnds.last) } /** Executes a block of code multiple times (no warm-up) */ - def measure(msg: Duration ⇒ String)(block: ⇒ Unit): Unit = { + def measure(msg: Duration => String)(block: => Unit): Unit = { val measurements = new Array[Duration](measurementIterations) var i = 0 while (i < measurementIterations) { @@ -125,7 +125,7 @@ abstract class JournalPerfSpec(config: Config) extends JournalSpec(config) { s"measure: persistAsync()-ing $eventsCount events" in { val p1 = benchActor(eventsCount) - measure(d ⇒ s"PersistAsync()-ing $eventsCount took ${d.toMillis} ms") { + measure(d => s"PersistAsync()-ing $eventsCount took ${d.toMillis} ms") { feedAndExpectLast(p1, "pa", commands) p1 ! ResetCounter } @@ -133,7 +133,7 @@ abstract class JournalPerfSpec(config: Config) extends JournalSpec(config) { s"measure: persist()-ing $eventsCount events" in { val p1 = benchActor(eventsCount) - measure(d ⇒ s"Persist()-ing $eventsCount took ${d.toMillis} ms") { + measure(d => s"Persist()-ing $eventsCount took ${d.toMillis} ms") { feedAndExpectLast(p1, "p", commands) p1 ! ResetCounter } @@ -142,7 +142,7 @@ abstract class JournalPerfSpec(config: Config) extends JournalSpec(config) { val p1 = benchActor(eventsCount) feedAndExpectLast(p1, "p", commands) - measure(d ⇒ s"Recovering $eventsCount took ${d.toMillis} ms") { + measure(d => s"Recovering $eventsCount took ${d.toMillis} ms") { benchActor(eventsCount) testProbe.expectMsg(max = awaitDuration, commands.last) } diff --git a/akka-persistence-tck/src/main/scala/akka/persistence/journal/JournalSpec.scala b/akka-persistence-tck/src/main/scala/akka/persistence/journal/JournalSpec.scala index ee66dca4dd..d6449c68dd 100644 --- a/akka-persistence-tck/src/main/scala/akka/persistence/journal/JournalSpec.scala +++ b/akka-persistence-tck/src/main/scala/akka/persistence/journal/JournalSpec.scala @@ -88,14 +88,14 @@ abstract class JournalSpec(config: Config) extends PluginSpec(config) with MayVe val msgs = if (supportsAtomicPersistAllOfSeveralEvents) { - (fromSnr to toSnr - 1).map { i ⇒ + (fromSnr to toSnr - 1).map { i => if (i == toSnr - 1) AtomicWrite(List(persistentRepr(i), persistentRepr(i + 1))) else AtomicWrite(persistentRepr(i)) } } else { - (fromSnr to toSnr).map { i ⇒ + (fromSnr to toSnr).map { i => AtomicWrite(persistentRepr(i)) } } @@ -105,9 +105,9 @@ abstract class JournalSpec(config: Config) extends PluginSpec(config) with MayVe journal ! WriteMessages(msgs, probe.ref, actorInstanceId) probe.expectMsg(WriteMessagesSuccessful) - fromSnr to toSnr foreach { i ⇒ + fromSnr to toSnr foreach { i => probe.expectMsgPF() { - case WriteMessageSuccess(PersistentImpl(payload, `i`, `pid`, _, _, `sender`, `writerUuid`), _) ⇒ + case WriteMessageSuccess(PersistentImpl(payload, `i`, `pid`, _, _, `sender`, `writerUuid`), _) => payload should be(s"a-${i}") } } @@ -116,42 +116,42 @@ abstract class JournalSpec(config: Config) extends PluginSpec(config) with MayVe "A journal" must { "replay all messages" in { journal ! ReplayMessages(1, Long.MaxValue, Long.MaxValue, pid, receiverProbe.ref) - 1 to 5 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 1 to 5 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "replay messages using a lower sequence number bound" in { journal ! ReplayMessages(3, Long.MaxValue, Long.MaxValue, pid, receiverProbe.ref) - 3 to 5 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 3 to 5 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "replay messages using an upper sequence number bound" in { journal ! ReplayMessages(1, 3, Long.MaxValue, pid, receiverProbe.ref) - 1 to 3 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 1 to 3 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "replay messages using a count limit" in { journal ! ReplayMessages(1, Long.MaxValue, 3, pid, receiverProbe.ref) - 1 to 3 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 1 to 3 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "replay messages using a lower and upper sequence number bound" in { journal ! ReplayMessages(2, 3, Long.MaxValue, pid, receiverProbe.ref) - 2 to 3 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 2 to 3 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "replay messages using a lower and upper sequence number bound and a count limit" in { journal ! ReplayMessages(2, 5, 2, pid, receiverProbe.ref) - 2 to 3 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 2 to 3 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "replay a single if lower sequence number bound equals upper sequence number bound" in { journal ! ReplayMessages(2, 2, Long.MaxValue, pid, receiverProbe.ref) - 2 to 2 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 2 to 2 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "replay a single message if count limit equals 1" in { journal ! ReplayMessages(2, 4, 1, pid, receiverProbe.ref) - 2 to 2 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 2 to 2 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "not replay messages if count limit equals 0" in { @@ -177,27 +177,27 @@ abstract class JournalSpec(config: Config) extends PluginSpec(config) with MayVe receiverProbe2.expectMsg(DeleteMessagesSuccess(cmd.toSequenceNr)) journal ! ReplayMessages(1, Long.MaxValue, Long.MaxValue, pid, receiverProbe.ref) - List(4, 5) foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + List(4, 5) foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe2.expectNoMsg(200.millis) } "not reset highestSequenceNr after message deletion" in { journal ! ReplayMessages(0, Long.MaxValue, Long.MaxValue, pid, receiverProbe.ref) - 1 to 5 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 1 to 5 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) journal ! DeleteMessagesTo(pid, 3L, receiverProbe.ref) receiverProbe.expectMsg(DeleteMessagesSuccess(3L)) journal ! ReplayMessages(0, Long.MaxValue, Long.MaxValue, pid, receiverProbe.ref) - 4 to 5 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 4 to 5 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) } "not reset highestSequenceNr after journal cleanup" in { journal ! ReplayMessages(0, Long.MaxValue, Long.MaxValue, pid, receiverProbe.ref) - 1 to 5 foreach { i ⇒ receiverProbe.expectMsg(replayedMessage(i)) } + 1 to 5 foreach { i => receiverProbe.expectMsg(replayedMessage(i)) } receiverProbe.expectMsg(RecoverySuccess(highestSequenceNr = 5L)) journal ! DeleteMessagesTo(pid, Long.MaxValue, receiverProbe.ref) @@ -216,7 +216,7 @@ abstract class JournalSpec(config: Config) extends PluginSpec(config) with MayVe val notSerializableEvent = new Object { override def toString = "not serializable" } - val msgs = (6 to 8).map { i ⇒ + val msgs = (6 to 8).map { i => val event = if (i == 7) notSerializableEvent else s"b-$i" AtomicWrite(PersistentRepr(payload = event, sequenceNr = i, persistenceId = pid, sender = Actor.noSender, writerUuid = writerUuid)) @@ -229,14 +229,14 @@ abstract class JournalSpec(config: Config) extends PluginSpec(config) with MayVe val Pid = pid val WriterUuid = writerUuid probe.expectMsgPF() { - case WriteMessageSuccess(PersistentImpl(payload, 6L, Pid, _, _, Actor.noSender, WriterUuid), _) ⇒ payload should be(s"b-6") + case WriteMessageSuccess(PersistentImpl(payload, 6L, Pid, _, _, Actor.noSender, WriterUuid), _) => payload should be(s"b-6") } probe.expectMsgPF() { - case WriteMessageRejected(PersistentImpl(payload, 7L, Pid, _, _, Actor.noSender, WriterUuid), _, _) ⇒ + case WriteMessageRejected(PersistentImpl(payload, 7L, Pid, _, _, Actor.noSender, WriterUuid), _, _) => payload should be(notSerializableEvent) } probe.expectMsgPF() { - case WriteMessageSuccess(PersistentImpl(payload, 8L, Pid, _, _, Actor.noSender, WriterUuid), _) ⇒ payload should be(s"b-8") + case WriteMessageSuccess(PersistentImpl(payload, 8L, Pid, _, _, Actor.noSender, WriterUuid), _) => payload should be(s"b-8") } } } @@ -255,15 +255,15 @@ abstract class JournalSpec(config: Config) extends PluginSpec(config) with MayVe val Pid = pid val WriterUuid = writerUuid probe.expectMsgPF() { - case WriteMessageSuccess(PersistentImpl(payload, 6L, Pid, _, _, Actor.noSender, WriterUuid), _) ⇒ payload should be(event) + case WriteMessageSuccess(PersistentImpl(payload, 6L, Pid, _, _, Actor.noSender, WriterUuid), _) => payload should be(event) } journal ! ReplayMessages(6, Long.MaxValue, Long.MaxValue, pid, receiverProbe.ref) receiverProbe.expectMsgPF() { - case ReplayedMessage(PersistentImpl(payload, 6L, Pid, _, _, Actor.noSender, WriterUuid)) ⇒ payload should be(event) + case ReplayedMessage(PersistentImpl(payload, 6L, Pid, _, _, Actor.noSender, WriterUuid)) => payload should be(event) } receiverProbe.expectMsgPF() { - case RecoverySuccess(highestSequenceNr) ⇒ highestSequenceNr should be >= 6L + case RecoverySuccess(highestSequenceNr) => highestSequenceNr should be >= 6L } } } diff --git a/akka-persistence-tck/src/main/scala/akka/persistence/scalatest/MayVerb.scala b/akka-persistence-tck/src/main/scala/akka/persistence/scalatest/MayVerb.scala index 7bd49eb3b2..b47b903e8a 100644 --- a/akka-persistence-tck/src/main/scala/akka/persistence/scalatest/MayVerb.scala +++ b/akka-persistence-tck/src/main/scala/akka/persistence/scalatest/MayVerb.scala @@ -19,9 +19,9 @@ trait MayVerb { */ def mayVerbStacktraceContextFrames = 3 - def optional(whenSkippedMessage: String)(body: ⇒ Unit): Unit = + def optional(whenSkippedMessage: String)(body: => Unit): Unit = try body catch { - case cause: Throwable ⇒ + case cause: Throwable => val shortTrace = cause.getStackTrace.take(mayVerbStacktraceContextFrames) throw new TestCanceledByFailure(whenSkippedMessage, shortTrace) } @@ -39,7 +39,7 @@ trait MayVerb { * * @see RFC 2119 */ - def may(right: ⇒ Unit)(implicit fun: StringVerbBlockRegistration, pos: Position): Unit = { + def may(right: => Unit)(implicit fun: StringVerbBlockRegistration, pos: Position): Unit = { fun(leftSideString, "may", pos, right _) } } diff --git a/akka-persistence-tck/src/main/scala/akka/persistence/scalatest/OptionalTests.scala b/akka-persistence-tck/src/main/scala/akka/persistence/scalatest/OptionalTests.scala index eab0a25204..102de862e3 100644 --- a/akka-persistence-tck/src/main/scala/akka/persistence/scalatest/OptionalTests.scala +++ b/akka-persistence-tck/src/main/scala/akka/persistence/scalatest/OptionalTests.scala @@ -8,16 +8,16 @@ import akka.persistence.CapabilityFlag import org.scalatest.Informing trait OptionalTests { - this: Informing ⇒ + this: Informing => - def optional(flag: CapabilityFlag)(test: ⇒ Unit) = { + def optional(flag: CapabilityFlag)(test: => Unit) = { val msg = s"CapabilityFlag `${flag.name}` was turned `" + (if (flag.value) "on" else "off") + "`. " + (if (!flag.value) "To enable the related tests override it with `CapabilityFlag.on` (or `true` in Scala)." else "") info(msg) if (flag.value) try test catch { - case ex: Exception ⇒ + case ex: Exception => throw new AssertionError("Implementation did not pass this spec. " + "If your journal will be (by definition) unable to abide the here tested rule, you can disable this test," + s"by overriding [${flag.name}] with CapabilityFlag.off in your test class.") diff --git a/akka-persistence-tck/src/main/scala/akka/persistence/snapshot/SnapshotStoreSpec.scala b/akka-persistence-tck/src/main/scala/akka/persistence/snapshot/SnapshotStoreSpec.scala index 1355721b38..be45072ce4 100644 --- a/akka-persistence-tck/src/main/scala/akka/persistence/snapshot/SnapshotStoreSpec.scala +++ b/akka-persistence-tck/src/main/scala/akka/persistence/snapshot/SnapshotStoreSpec.scala @@ -59,10 +59,10 @@ abstract class SnapshotStoreSpec(config: Config) extends PluginSpec(config) extension.snapshotStoreFor(null) def writeSnapshots(): Seq[SnapshotMetadata] = { - 1 to 5 map { i ⇒ + 1 to 5 map { i => val metadata = SnapshotMetadata(pid, i + 10) snapshotStore.tell(SaveSnapshot(metadata, s"s-${i}"), senderProbe.ref) - senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md) ⇒ md } + senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md) => md } } } @@ -150,7 +150,7 @@ abstract class SnapshotStoreSpec(config: Config) extends PluginSpec(config) "save and overwrite snapshot with same sequence number" in { val md = metadata(4) snapshotStore.tell(SaveSnapshot(md, s"s-5-modified"), senderProbe.ref) - val md2 = senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md2) ⇒ md2 } + val md2 = senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md2) => md2 } md2.sequenceNr should be(md.sequenceNr) snapshotStore.tell(LoadSnapshot(pid, SnapshotSelectionCriteria(md.sequenceNr), Long.MaxValue), senderProbe.ref) val result = senderProbe.expectMsgType[LoadSnapshotResult] @@ -162,7 +162,7 @@ abstract class SnapshotStoreSpec(config: Config) extends PluginSpec(config) val metadata = SnapshotMetadata(pid, 100) val bigSnapshot = "0" * snapshotByteSizeLimit snapshotStore.tell(SaveSnapshot(metadata, bigSnapshot), senderProbe.ref) - senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md) ⇒ md } + senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md) => md } } } @@ -173,12 +173,12 @@ abstract class SnapshotStoreSpec(config: Config) extends PluginSpec(config) val metadata = SnapshotMetadata(pid, 100) val snap = TestPayload(probe.ref) snapshotStore.tell(SaveSnapshot(metadata, snap), senderProbe.ref) - senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md) ⇒ md } + senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md) => md } val Pid = pid snapshotStore.tell(LoadSnapshot(pid, SnapshotSelectionCriteria.Latest, Long.MaxValue), senderProbe.ref) senderProbe.expectMsgPF() { - case LoadSnapshotResult(Some(SelectedSnapshot(SnapshotMetadata(Pid, 100, _), payload)), Long.MaxValue) ⇒ + case LoadSnapshotResult(Some(SelectedSnapshot(SnapshotMetadata(Pid, 100, _), payload)), Long.MaxValue) => payload should be(snap) } } diff --git a/akka-persistence-tck/src/test/scala/akka/persistence/PluginCleanup.scala b/akka-persistence-tck/src/test/scala/akka/persistence/PluginCleanup.scala index c9361a2b93..1b1ff30cd5 100644 --- a/akka-persistence-tck/src/test/scala/akka/persistence/PluginCleanup.scala +++ b/akka-persistence-tck/src/test/scala/akka/persistence/PluginCleanup.scala @@ -8,10 +8,10 @@ import java.io.File import org.apache.commons.io.FileUtils import org.scalatest.BeforeAndAfterAll -trait PluginCleanup extends BeforeAndAfterAll { _: PluginSpec ⇒ +trait PluginCleanup extends BeforeAndAfterAll { _: PluginSpec => val storageLocations = List( "akka.persistence.journal.leveldb.dir", - "akka.persistence.snapshot-store.local.dir").map(s ⇒ new File(system.settings.config.getString(s))) + "akka.persistence.snapshot-store.local.dir").map(s => new File(system.settings.config.getString(s))) override def beforeAll(): Unit = { storageLocations.foreach(FileUtils.deleteDirectory) diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/SideEffect.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/SideEffect.scala index 49ce7167da..ba7db97755 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/SideEffect.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/SideEffect.scala @@ -20,21 +20,21 @@ sealed abstract class SideEffect[State] /** INTERNAL API */ @InternalApi -private[akka] class Callback[State](val sideEffect: State ⇒ Unit) extends SideEffect[State] { +private[akka] class Callback[State](val sideEffect: State => Unit) extends SideEffect[State] { override def toString: String = "Callback" } /** INTERNAL API */ @InternalApi -final private[akka] class ReplyEffectImpl[ReplyMessage, State](replyTo: ActorRef[ReplyMessage], replyWithMessage: State ⇒ ReplyMessage) - extends Callback[State](state ⇒ replyTo ! replyWithMessage(state)) { +final private[akka] class ReplyEffectImpl[ReplyMessage, State](replyTo: ActorRef[ReplyMessage], replyWithMessage: State => ReplyMessage) + extends Callback[State](state => replyTo ! replyWithMessage(state)) { override def toString: String = "Reply" } /** INTERNAL API */ @InternalApi final private[akka] class NoReplyEffectImpl[State] - extends Callback[State](_ ⇒ ()) { + extends Callback[State](_ => ()) { override def toString: String = "NoReply" } @@ -50,7 +50,7 @@ object SideEffect { /** * Create a ChainedEffect that can be run after Effects */ - def apply[State](callback: State ⇒ Unit): SideEffect[State] = + def apply[State](callback: State => Unit): SideEffect[State] = new Callback(callback) /** @@ -59,7 +59,7 @@ object SideEffect { * Create a ChainedEffect that can be run after Effects */ def create[State](callback: function.Procedure[State]): SideEffect[State] = - new Callback(s ⇒ callback.apply(s)) + new Callback(s => callback.apply(s)) def stop[State](): SideEffect[State] = Stop.asInstanceOf[SideEffect[State]] diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/BehaviorSetup.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/BehaviorSetup.scala index c5e84535b4..6e28dea12c 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/BehaviorSetup.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/BehaviorSetup.scala @@ -30,12 +30,12 @@ private[akka] final class BehaviorSetup[C, E, S]( val commandHandler: EventSourcedBehavior.CommandHandler[C, E, S], val eventHandler: EventSourcedBehavior.EventHandler[S, E], val writerIdentity: EventSourcedBehaviorImpl.WriterIdentity, - val recoveryCompleted: S ⇒ Unit, - val onRecoveryFailure: Throwable ⇒ Unit, - val onSnapshot: (SnapshotMetadata, Try[Done]) ⇒ Unit, - val tagger: E ⇒ Set[String], + val recoveryCompleted: S => Unit, + val onRecoveryFailure: Throwable => Unit, + val onSnapshot: (SnapshotMetadata, Try[Done]) => Unit, + val tagger: E => Set[String], val eventAdapter: EventAdapter[E, _], - val snapshotWhen: (S, E, Long) ⇒ Boolean, + val snapshotWhen: (S, E, Long) => Boolean, val recovery: Recovery, var holdingRecoveryPermit: Boolean, val settings: EventSourcedSettings, @@ -55,8 +55,8 @@ private[akka] final class BehaviorSetup[C, E, S]( private var _log: OptionVal[Logger] = OptionVal.Some(context.log) // changed when mdc is changed def log: Logger = { _log match { - case OptionVal.Some(l) ⇒ l - case OptionVal.None ⇒ + case OptionVal.Some(l) => l + case OptionVal.None => // lazy init if mdc changed val l = context.log.withMdc(mdc) _log = OptionVal.Some(l) @@ -93,8 +93,8 @@ private[akka] final class BehaviorSetup[C, E, S]( def cancelRecoveryTimer(): Unit = { recoveryTimer match { - case OptionVal.Some(t) ⇒ t.cancel() - case OptionVal.None ⇒ + case OptionVal.Some(t) => t.cancel() + case OptionVal.None => } recoveryTimer = OptionVal.None } @@ -117,8 +117,8 @@ private[akka] object MDC { def create(persistenceId: PersistenceId, phaseName: String): Map[String, Any] = { Map( - "persistenceId" → persistenceId.id, - "phase" → phaseName + "persistenceId" -> persistenceId.id, + "phase" -> phaseName ) } } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/EventSourcedBehaviorImpl.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/EventSourcedBehaviorImpl.scala index e959a661e1..4925491aeb 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/EventSourcedBehaviorImpl.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/EventSourcedBehaviorImpl.scala @@ -37,9 +37,9 @@ private[akka] object EventSourcedBehaviorImpl { def defaultOnSnapshot[A](ctx: ActorContext[A], meta: SnapshotMetadata, result: Try[Done]): Unit = { result match { - case Success(_) ⇒ + case Success(_) => ctx.log.debug("Save snapshot successful, snapshot metadata: [{}]", meta) - case Failure(t) ⇒ + case Failure(t) => ctx.log.error(t, "Save snapshot failed, snapshot metadata: [{}]", meta) } } @@ -68,16 +68,16 @@ private[akka] final case class EventSourcedBehaviorImpl[Command, Event, State]( loggerClass: Class[_], journalPluginId: Option[String] = None, snapshotPluginId: Option[String] = None, - recoveryCompleted: State ⇒ Unit = ConstantFun.scalaAnyToUnit, - postStop: () ⇒ Unit = ConstantFun.unitToUnit, - preRestart: () ⇒ Unit = ConstantFun.unitToUnit, - tagger: Event ⇒ Set[String] = (_: Event) ⇒ Set.empty[String], + recoveryCompleted: State => Unit = ConstantFun.scalaAnyToUnit, + postStop: () => Unit = ConstantFun.unitToUnit, + preRestart: () => Unit = ConstantFun.unitToUnit, + tagger: Event => Set[String] = (_: Event) => Set.empty[String], eventAdapter: EventAdapter[Event, Any] = NoOpEventAdapter.instance[Event], - snapshotWhen: (State, Event, Long) ⇒ Boolean = ConstantFun.scalaAnyThreeToFalse, + snapshotWhen: (State, Event, Long) => Boolean = ConstantFun.scalaAnyThreeToFalse, recovery: Recovery = Recovery(), supervisionStrategy: SupervisorStrategy = SupervisorStrategy.stop, - onSnapshot: (SnapshotMetadata, Try[Done]) ⇒ Unit = ConstantFun.scalaAnyTwoToUnit, - onRecoveryFailure: Throwable ⇒ Unit = ConstantFun.scalaAnyToUnit + onSnapshot: (SnapshotMetadata, Try[Done]) => Unit = ConstantFun.scalaAnyTwoToUnit, + onRecoveryFailure: Throwable => Unit = ConstantFun.scalaAnyToUnit ) extends EventSourcedBehavior[Command, Event, State] { import EventSourcedBehaviorImpl.WriterIdentity @@ -91,11 +91,11 @@ private[akka] final case class EventSourcedBehaviorImpl[Command, Event, State]( val stashState = new StashState(settings) Behaviors.supervise { - Behaviors.setup[Command] { _ ⇒ + Behaviors.setup[Command] { _ => // the default impl needs context which isn't available until here, so we // use the anyTwoToUnit as a marker to use the default - val actualOnSnapshot: (SnapshotMetadata, Try[Done]) ⇒ Unit = + val actualOnSnapshot: (SnapshotMetadata, Try[Done]) => Unit = if (onSnapshot == ConstantFun.scalaAnyTwoToUnit) EventSourcedBehaviorImpl.defaultOnSnapshot[Command](ctx, _, _) else onSnapshot @@ -140,11 +140,11 @@ private[akka] final case class EventSourcedBehaviorImpl[Command, Event, State]( } } val widened = RequestingRecoveryPermit(eventsourcedSetup).widen[Any] { - case res: JournalProtocol.Response ⇒ InternalProtocol.JournalResponse(res) - case res: SnapshotProtocol.Response ⇒ InternalProtocol.SnapshotterResponse(res) - case RecoveryPermitter.RecoveryPermitGranted ⇒ InternalProtocol.RecoveryPermitGranted - case internal: InternalProtocol ⇒ internal // such as RecoveryTickEvent - case cmd: Command @unchecked ⇒ InternalProtocol.IncomingCommand(cmd) + case res: JournalProtocol.Response => InternalProtocol.JournalResponse(res) + case res: SnapshotProtocol.Response => InternalProtocol.SnapshotterResponse(res) + case RecoveryPermitter.RecoveryPermitGranted => InternalProtocol.RecoveryPermitGranted + case internal: InternalProtocol => internal // such as RecoveryTickEvent + case cmd: Command @unchecked => InternalProtocol.IncomingCommand(cmd) } Behaviors.intercept(onStopInterceptor)(widened).narrow[Command] } @@ -154,33 +154,33 @@ private[akka] final case class EventSourcedBehaviorImpl[Command, Event, State]( def signalPostStop(log: Logger): Unit = { try postStop() catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning("Exception in postStop: {}", e) } } def signalPreRestart(log: Logger): Unit = { try preRestart() catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning("Exception in preRestart: {}", e) } } - override def onRecoveryCompleted(callback: State ⇒ Unit): EventSourcedBehavior[Command, Event, State] = + override def onRecoveryCompleted(callback: State => Unit): EventSourcedBehavior[Command, Event, State] = copy(recoveryCompleted = callback) - override def onPostStop(callback: () ⇒ Unit): EventSourcedBehavior[Command, Event, State] = + override def onPostStop(callback: () => Unit): EventSourcedBehavior[Command, Event, State] = copy(postStop = callback) - override def onPreRestart(callback: () ⇒ Unit): EventSourcedBehavior[Command, Event, State] = + override def onPreRestart(callback: () => Unit): EventSourcedBehavior[Command, Event, State] = copy(preRestart = callback) - override def snapshotWhen(predicate: (State, Event, Long) ⇒ Boolean): EventSourcedBehavior[Command, Event, State] = + override def snapshotWhen(predicate: (State, Event, Long) => Boolean): EventSourcedBehavior[Command, Event, State] = copy(snapshotWhen = predicate) override def snapshotEvery(numberOfEvents: Long): EventSourcedBehavior[Command, Event, State] = { require(numberOfEvents > 0, s"numberOfEvents should be positive: Was $numberOfEvents") - copy(snapshotWhen = (_, _, seqNr) ⇒ seqNr % numberOfEvents == 0) + copy(snapshotWhen = (_, _, seqNr) => seqNr % numberOfEvents == 0) } override def withJournalPluginId(id: String): EventSourcedBehavior[Command, Event, State] = { @@ -197,19 +197,19 @@ private[akka] final case class EventSourcedBehaviorImpl[Command, Event, State]( copy(recovery = Recovery(selection)) } - override def withTagger(tagger: Event ⇒ Set[String]): EventSourcedBehavior[Command, Event, State] = + override def withTagger(tagger: Event => Set[String]): EventSourcedBehavior[Command, Event, State] = copy(tagger = tagger) override def eventAdapter(adapter: EventAdapter[Event, _]): EventSourcedBehavior[Command, Event, State] = copy(eventAdapter = adapter.asInstanceOf[EventAdapter[Event, Any]]) - override def onSnapshot(callback: (SnapshotMetadata, Try[Done]) ⇒ Unit): EventSourcedBehavior[Command, Event, State] = + override def onSnapshot(callback: (SnapshotMetadata, Try[Done]) => Unit): EventSourcedBehavior[Command, Event, State] = copy(onSnapshot = callback) override def onPersistFailure(backoffStrategy: BackoffSupervisorStrategy): EventSourcedBehavior[Command, Event, State] = copy(supervisionStrategy = backoffStrategy) - override def onRecoveryFailure(callback: Throwable ⇒ Unit): EventSourcedBehavior[Command, Event, State] = + override def onRecoveryFailure(callback: Throwable => Unit): EventSourcedBehavior[Command, Event, State] = copy(onRecoveryFailure = callback) } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/EventSourcedSettings.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/EventSourcedSettings.scala index fdd31311dc..f32a646574 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/EventSourcedSettings.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/EventSourcedSettings.scala @@ -25,9 +25,9 @@ import com.typesafe.config.Config val typedConfig = config.getConfig("akka.persistence.typed") val stashOverflowStrategy = typedConfig.getString("stash-overflow-strategy").toLowerCase match { - case "drop" ⇒ StashOverflowStrategy.Drop - case "fail" ⇒ StashOverflowStrategy.Fail - case unknown ⇒ + case "drop" => StashOverflowStrategy.Drop + case "fail" => StashOverflowStrategy.Fail + case unknown => throw new IllegalArgumentException(s"Unknown value for stash-overflow-strategy: [$unknown]") } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/JournalInteractions.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/JournalInteractions.scala index 093d858db7..7abc767f4c 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/JournalInteractions.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/JournalInteractions.scala @@ -55,7 +55,7 @@ private[akka] trait JournalInteractions[C, E, S] { if (events.nonEmpty) { var newState = state - val writes = events.map { event ⇒ + val writes = events.map { event => newState = newState.nextSequenceNr() PersistentRepr( event, @@ -83,10 +83,10 @@ private[akka] trait JournalInteractions[C, E, S] { /** Intended to be used in .onSignal(returnPermitOnStop) by behaviors */ protected def returnPermitOnStop: PartialFunction[(ActorContext[InternalProtocol], Signal), Behavior[InternalProtocol]] = { - case (_, PostStop) ⇒ + case (_, PostStop) => tryReturnRecoveryPermit("PostStop") Behaviors.stopped - case (_, PreRestart) ⇒ + case (_, PreRestart) => tryReturnRecoveryPermit("PreRestart") Behaviors.stopped } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/ReplayingEvents.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/ReplayingEvents.scala index 76b3969fdb..9924627e6e 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/ReplayingEvents.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/ReplayingEvents.scala @@ -49,7 +49,7 @@ private[akka] object ReplayingEvents { setup: BehaviorSetup[C, E, S], state: ReplayingState[S] ): Behavior[InternalProtocol] = - Behaviors.setup { ctx ⇒ + Behaviors.setup { ctx => // protect against event recovery stalling forever because of journal overloaded and such setup.startRecoveryTimer(snapshot = false) new ReplayingEvents[C, E, S](setup.setMdc(MDC.ReplayingEvents), state) @@ -70,16 +70,16 @@ private[akka] final class ReplayingEvents[C, E, S]( override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = { msg match { - case JournalResponse(r) ⇒ onJournalResponse(r) - case SnapshotterResponse(r) ⇒ onSnapshotterResponse(r) - case RecoveryTickEvent(snap) ⇒ onRecoveryTick(snap) - case cmd: IncomingCommand[C] ⇒ onCommand(cmd) - case RecoveryPermitGranted ⇒ Behaviors.unhandled // should not happen, we already have the permit + case JournalResponse(r) => onJournalResponse(r) + case SnapshotterResponse(r) => onSnapshotterResponse(r) + case RecoveryTickEvent(snap) => onRecoveryTick(snap) + case cmd: IncomingCommand[C] => onCommand(cmd) + case RecoveryPermitGranted => Behaviors.unhandled // should not happen, we already have the permit } } override def onSignal: PartialFunction[Signal, Behavior[InternalProtocol]] = { - case PoisonPill ⇒ + case PoisonPill => state = state.copy(receivedPoisonPill = true) this } @@ -88,7 +88,7 @@ private[akka] final class ReplayingEvents[C, E, S]( response: JournalProtocol.Response): Behavior[InternalProtocol] = { try { response match { - case ReplayedMessage(repr) ⇒ + case ReplayedMessage(repr) => val event = setup.eventAdapter.fromJournal(repr.payload.asInstanceOf[setup.eventAdapter.Per]) try { @@ -98,23 +98,23 @@ private[akka] final class ReplayingEvents[C, E, S]( eventSeenInInterval = true) this } catch { - case NonFatal(ex) ⇒ onRecoveryFailure(ex, repr.sequenceNr, Some(event)) + case NonFatal(ex) => onRecoveryFailure(ex, repr.sequenceNr, Some(event)) } - case RecoverySuccess(highestSeqNr) ⇒ + case RecoverySuccess(highestSeqNr) => setup.log.debug("Recovery successful, recovered until sequenceNr: [{}]", highestSeqNr) onRecoveryCompleted(state) - case ReplayMessagesFailure(cause) ⇒ + case ReplayMessagesFailure(cause) => onRecoveryFailure(cause, state.seqNr, Some(response)) - case _ ⇒ + case _ => Behaviors.unhandled } } catch { - case ex: UnstashException[_] ⇒ + case ex: UnstashException[_] => // let supervisor handle it, don't treat it as recovery failure throw ex - case NonFatal(cause) ⇒ + case NonFatal(cause) => onRecoveryFailure(cause, state.seqNr, None) } } @@ -162,16 +162,16 @@ private[akka] final class ReplayingEvents[C, E, S]( try { setup.onRecoveryFailure(cause) } catch { - case NonFatal(t) ⇒ setup.log.error(t, "onRecoveryFailure threw exception") + case NonFatal(t) => setup.log.error(t, "onRecoveryFailure threw exception") } setup.cancelRecoveryTimer() tryReturnRecoveryPermit("on replay failure: " + cause.getMessage) val msg = message match { - case Some(evt) ⇒ + case Some(evt) => s"Exception during recovery while handling [${evt.getClass.getName}] with sequence number [$sequenceNr]. " + s"PersistenceId [${setup.persistenceId.id}]" - case None ⇒ + case None => s"Exception during recovery. Last known sequence number [$sequenceNr]. PersistenceId [${setup.persistenceId.id}]" } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/ReplayingSnapshot.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/ReplayingSnapshot.scala index 1f9e07f204..d28157e76c 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/ReplayingSnapshot.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/ReplayingSnapshot.scala @@ -49,15 +49,15 @@ private[akka] class ReplayingSnapshot[C, E, S](override val setup: BehaviorSetup def stay(receivedPoisonPill: Boolean): Behavior[InternalProtocol] = { Behaviors.receiveMessage[InternalProtocol] { - case SnapshotterResponse(r) ⇒ onSnapshotterResponse(r, receivedPoisonPill) - case JournalResponse(r) ⇒ onJournalResponse(r) - case RecoveryTickEvent(snapshot) ⇒ onRecoveryTick(snapshot) - case cmd: IncomingCommand[C] ⇒ + case SnapshotterResponse(r) => onSnapshotterResponse(r, receivedPoisonPill) + case JournalResponse(r) => onJournalResponse(r) + case RecoveryTickEvent(snapshot) => onRecoveryTick(snapshot) + case cmd: IncomingCommand[C] => if (receivedPoisonPill) Behaviors.unhandled else onCommand(cmd) - case RecoveryPermitGranted ⇒ Behaviors.unhandled // should not happen, we already have the permit + case RecoveryPermitGranted => Behaviors.unhandled // should not happen, we already have the permit }.receiveSignal(returnPermitOnStop.orElse { - case (_, PoisonPill) ⇒ stay(receivedPoisonPill = true) + case (_, PoisonPill) => stay(receivedPoisonPill = true) }) } stay(receivedPoisonPillInPreviousPhase) @@ -75,9 +75,9 @@ private[akka] class ReplayingSnapshot[C, E, S](override val setup: BehaviorSetup setup.cancelRecoveryTimer() event match { - case Some(evt) ⇒ + case Some(evt) => setup.log.error(cause, "Exception in receiveRecover when replaying snapshot [{}]", evt.getClass.getName) - case _ ⇒ + case _ => setup.log.error(cause, "Persistence failure when replaying snapshot") } @@ -104,22 +104,22 @@ private[akka] class ReplayingSnapshot[C, E, S](override val setup: BehaviorSetup def onSnapshotterResponse(response: SnapshotProtocol.Response, receivedPoisonPill: Boolean): Behavior[InternalProtocol] = { response match { - case LoadSnapshotResult(sso, toSnr) ⇒ + case LoadSnapshotResult(sso, toSnr) => var state: S = setup.emptyState val seqNr: Long = sso match { - case Some(SelectedSnapshot(metadata, snapshot)) ⇒ + case Some(SelectedSnapshot(metadata, snapshot)) => state = snapshot.asInstanceOf[S] metadata.sequenceNr - case None ⇒ 0 // from the beginning please + case None => 0 // from the beginning please } becomeReplayingEvents(state, seqNr, toSnr, receivedPoisonPill) - case LoadSnapshotFailed(cause) ⇒ + case LoadSnapshotFailed(cause) => onRecoveryFailure(cause, event = None) - case _ ⇒ + case _ => Behaviors.unhandled } } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/RequestingRecoveryPermit.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/RequestingRecoveryPermit.scala index 4a281ff5fc..9b5eb25302 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/RequestingRecoveryPermit.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/RequestingRecoveryPermit.scala @@ -37,13 +37,13 @@ private[akka] class RequestingRecoveryPermit[C, E, S](override val setup: Behavi def stay(receivedPoisonPill: Boolean): Behavior[InternalProtocol] = { Behaviors.receiveMessage[InternalProtocol] { - case InternalProtocol.RecoveryPermitGranted ⇒ + case InternalProtocol.RecoveryPermitGranted => becomeReplaying(receivedPoisonPill) - case _ if receivedPoisonPill ⇒ + case _ if receivedPoisonPill => Behaviors.unhandled - case other ⇒ + case other => if (receivedPoisonPill) { if (setup.settings.logOnStashing) setup.log.debug( "Discarding message [{}], because actor is to be stopped", other) @@ -54,7 +54,7 @@ private[akka] class RequestingRecoveryPermit[C, E, S](override val setup: Behavi } }.receiveSignal { - case (_, PoisonPill) ⇒ stay(receivedPoisonPill = true) + case (_, PoisonPill) => stay(receivedPoisonPill = true) } } stay(receivedPoisonPill = false) diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/Running.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/Running.scala index e53d5863e1..b931f3be57 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/Running.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/Running.scala @@ -94,15 +94,15 @@ private[akka] object Running { final class HandlingCommands(state: RunningState[S]) extends AbstractBehavior[InternalProtocol] with WithSeqNrAccessible { def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = msg match { - case IncomingCommand(c: C @unchecked) ⇒ onCommand(state, c) - case SnapshotterResponse(r) ⇒ + case IncomingCommand(c: C @unchecked) => onCommand(state, c) + case SnapshotterResponse(r) => setup.log.warning("Unexpected SnapshotterResponse {}", r) Behaviors.unhandled - case _ ⇒ Behaviors.unhandled + case _ => Behaviors.unhandled } override def onSignal: PartialFunction[Signal, Behavior[InternalProtocol]] = { - case PoisonPill ⇒ + case PoisonPill => if (isInternalStashEmpty && !isUnstashAllInProgress) Behaviors.stopped else new HandlingCommands(state.copy(receivedPoisonPill = true)) } @@ -124,11 +124,11 @@ private[akka] object Running { msg.getClass.getName, effect, sideEffects.size) effect match { - case CompositeEffect(eff, currentSideEffects) ⇒ + case CompositeEffect(eff, currentSideEffects) => // unwrap and accumulate effects applyEffects(msg, state, eff, currentSideEffects ++ sideEffects) - case Persist(event) ⇒ + case Persist(event) => // apply the event before persist so that validation exception is handled before persisting // the invalid event, in case such validation is implemented in the event handler. // also, ensure that there is an event handler for each single event @@ -142,14 +142,14 @@ private[akka] object Running { persistingEvents(newState2, numberOfEvents = 1, shouldSnapshotAfterPersist, sideEffects) - case PersistAll(events) ⇒ + case PersistAll(events) => if (events.nonEmpty) { // apply the event before persist so that validation exception is handled before persisting // the invalid event, in case such validation is implemented in the event handler. // also, ensure that there is an event handler for each single event var seqNr = state.seqNr val (newState, shouldSnapshotAfterPersist) = events.foldLeft((state, false)) { - case ((currentState, snapshot), event) ⇒ + case ((currentState, snapshot), event) => seqNr += 1 val shouldSnapshot = snapshot || setup.snapshotWhen(currentState.state, event, seqNr) (currentState.applyEvent(setup, event), shouldSnapshot) @@ -166,16 +166,16 @@ private[akka] object Running { tryUnstashOne(applySideEffects(sideEffects, state)) } - case _: PersistNothing.type ⇒ + case _: PersistNothing.type => tryUnstashOne(applySideEffects(sideEffects, state)) - case _: Unhandled.type ⇒ + case _: Unhandled.type => import akka.actor.typed.scaladsl.adapter._ setup.context.system.toUntyped.eventStream.publish( UnhandledMessage(msg, setup.context.system.toUntyped.deadLetters, setup.context.self.toUntyped)) tryUnstashOne(applySideEffects(sideEffects, state)) - case _: Stash.type ⇒ + case _: Stash.type => stashUser(IncomingCommand(msg)) tryUnstashOne(applySideEffects(sideEffects, state)) } @@ -219,13 +219,13 @@ private[akka] object Running { override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = { msg match { - case JournalResponse(r) ⇒ onJournalResponse(r) - case in: IncomingCommand[C @unchecked] ⇒ onCommand(in) - case SnapshotterResponse(r) ⇒ + case JournalResponse(r) => onJournalResponse(r) + case in: IncomingCommand[C @unchecked] => onCommand(in) + case SnapshotterResponse(r) => setup.log.warning("Unexpected SnapshotterResponse {}", r) Behaviors.unhandled - case RecoveryTickEvent(_) ⇒ Behaviors.unhandled - case RecoveryPermitGranted ⇒ Behaviors.unhandled + case RecoveryTickEvent(_) => Behaviors.unhandled + case RecoveryPermitGranted => Behaviors.unhandled } } @@ -260,37 +260,37 @@ private[akka] object Running { } response match { - case WriteMessageSuccess(p, id) ⇒ + case WriteMessageSuccess(p, id) => if (id == setup.writerIdentity.instanceId) onWriteResponse(p) else this - case WriteMessageRejected(p, cause, id) ⇒ + case WriteMessageRejected(p, cause, id) => if (id == setup.writerIdentity.instanceId) { throw new EventRejectedException(setup.persistenceId, p.sequenceNr, cause) } else this - case WriteMessageFailure(p, cause, id) ⇒ + case WriteMessageFailure(p, cause, id) => if (id == setup.writerIdentity.instanceId) throw new JournalFailureException(setup.persistenceId, p.sequenceNr, p.payload.getClass.getName, cause) else this - case WriteMessagesSuccessful ⇒ + case WriteMessagesSuccessful => // ignore this - case WriteMessagesFailed(_) ⇒ + case WriteMessagesFailed(_) => // ignore this // it will be stopped by the first WriteMessageFailure message; not applying side effects - case _ ⇒ + case _ => // ignore all other messages, since they relate to recovery handling which we're not dealing with in Running phase Behaviors.unhandled } } override def onSignal: PartialFunction[Signal, Behavior[InternalProtocol]] = { - case PoisonPill ⇒ + case PoisonPill => // wait for journal responses before stopping state = state.copy(receivedPoisonPill = true) this @@ -320,32 +320,32 @@ private[akka] object Running { def onSnapshotterResponse(response: SnapshotProtocol.Response): Unit = { response match { - case SaveSnapshotSuccess(meta) ⇒ + case SaveSnapshotSuccess(meta) => setup.onSnapshot(meta, Success(Done)) - case SaveSnapshotFailure(meta, ex) ⇒ + case SaveSnapshotFailure(meta, ex) => setup.onSnapshot(meta, Failure(ex)) // FIXME #24698 not implemented yet - case DeleteSnapshotFailure(_, _) ⇒ ??? - case DeleteSnapshotSuccess(_) ⇒ ??? - case DeleteSnapshotsFailure(_, _) ⇒ ??? - case DeleteSnapshotsSuccess(_) ⇒ ??? + case DeleteSnapshotFailure(_, _) => ??? + case DeleteSnapshotSuccess(_) => ??? + case DeleteSnapshotsFailure(_, _) => ??? + case DeleteSnapshotsSuccess(_) => ??? // ignore LoadSnapshot messages - case _ ⇒ + case _ => } } Behaviors.receiveMessage[InternalProtocol] { - case cmd: IncomingCommand[C] @unchecked ⇒ + case cmd: IncomingCommand[C] @unchecked => onCommand(cmd) - case SnapshotterResponse(r) ⇒ + case SnapshotterResponse(r) => onSnapshotterResponse(r) tryUnstashOne(applySideEffects(sideEffects, state)) - case _ ⇒ + case _ => Behaviors.unhandled }.receiveSignal { - case (_, PoisonPill) ⇒ + case (_, PoisonPill) => // wait for snapshot response before stopping storingSnapshot(state.copy(receivedPoisonPill = true), sideEffects) } @@ -376,18 +376,18 @@ private[akka] object Running { state: RunningState[S], behavior: Behavior[InternalProtocol]): Behavior[InternalProtocol] = { effect match { - case _: Stop.type @unchecked ⇒ + case _: Stop.type @unchecked => Behaviors.stopped - case _: UnstashAll.type @unchecked ⇒ + case _: UnstashAll.type @unchecked => unstashAll() behavior - case callback: Callback[_] ⇒ + case callback: Callback[_] => callback.sideEffect(state.state) behavior - case _ ⇒ + case _ => throw new IllegalArgumentException(s"Unsupported side effect detected [${effect.getClass.getName}]") } } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/StashManagement.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/StashManagement.scala index 57c9839118..d0a9f5a096 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/StashManagement.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/internal/StashManagement.scala @@ -41,18 +41,18 @@ private[akka] trait StashManagement[C, E, S] { logStashMessage(msg, buffer) try buffer.stash(msg) catch { - case e: StashOverflowException ⇒ + case e: StashOverflowException => setup.settings.stashOverflowStrategy match { - case StashOverflowStrategy.Drop ⇒ + case StashOverflowStrategy.Drop => if (context.log.isWarningEnabled) { val dropName = msg match { - case InternalProtocol.IncomingCommand(actual) ⇒ actual.getClass.getName - case other ⇒ other.getClass.getName + case InternalProtocol.IncomingCommand(actual) => actual.getClass.getName + case other => other.getClass.getName } context.log.warning("Stash buffer is full, dropping message [{}]", dropName) } context.system.toUntyped.eventStream.publish(Dropped(msg, context.self)) - case StashOverflowStrategy.Fail ⇒ + case StashOverflowStrategy.Fail => throw e } } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/CommandHandler.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/CommandHandler.scala index fe2f5f1aa3..853e7c62c9 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/CommandHandler.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/CommandHandler.scala @@ -5,7 +5,7 @@ package akka.persistence.typed.javadsl import java.util.Objects -import java.util.function.{ BiFunction, Predicate, Supplier, Function ⇒ JFunction } +import java.util.function.{ BiFunction, Predicate, Supplier, Function => JFunction } import akka.annotation.InternalApi import akka.persistence.typed.internal._ @@ -95,7 +95,7 @@ final class CommandHandlerBuilder[Command, Event, State]() { * @return A new, mutable, CommandHandlerBuilderByState */ def forNullState(): CommandHandlerBuilderByState[Command, Event, State, State] = { - val predicate: Predicate[State] = asJavaPredicate(s ⇒ Objects.isNull(s)) + val predicate: Predicate[State] = asJavaPredicate(s => Objects.isNull(s)) val builder = CommandHandlerBuilderByState.builder[Command, Event, State](predicate) builders = builder :: builders builder @@ -111,7 +111,7 @@ final class CommandHandlerBuilder[Command, Event, State]() { * @return A new, mutable, CommandHandlerBuilderByState */ def forNonNullState(): CommandHandlerBuilderByState[Command, Event, State, State] = { - val predicate: Predicate[State] = asJavaPredicate(s ⇒ Objects.nonNull(s)) + val predicate: Predicate[State] = asJavaPredicate(s => Objects.nonNull(s)) val builder = CommandHandlerBuilderByState.builder[Command, Event, State](predicate) builders = builder :: builders builder @@ -129,7 +129,7 @@ final class CommandHandlerBuilder[Command, Event, State]() { * @return A new, mutable, CommandHandlerBuilderByState */ def forAnyState(): CommandHandlerBuilderByState[Command, Event, State, State] = { - val predicate: Predicate[State] = asJavaPredicate(_ ⇒ true) + val predicate: Predicate[State] = asJavaPredicate(_ => true) val builder = CommandHandlerBuilderByState.builder[Command, Event, State](predicate) builders = builder :: builders builder @@ -139,11 +139,11 @@ final class CommandHandlerBuilder[Command, Event, State]() { val combined = builders.reverse match { - case head :: Nil ⇒ head - case head :: tail ⇒ tail.foldLeft(head) { (acc, builder) ⇒ + case head :: Nil => head + case head :: tail => tail.foldLeft(head) { (acc, builder) => acc.orElse(builder) } - case Nil ⇒ throw new IllegalStateException("No matchers defined") + case Nil => throw new IllegalStateException("No matchers defined") } combined.build() @@ -178,8 +178,8 @@ object CommandHandlerBuilderByState { * INTERNAL API */ @InternalApi private final case class CommandHandlerCase[Command, Event, State]( - commandPredicate: Command ⇒ Boolean, - statePredicate: State ⇒ Boolean, + commandPredicate: Command => Boolean, + statePredicate: State => Boolean, handler: BiFunction[State, Command, Effect[Event, State]]) } @@ -190,10 +190,10 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int private var cases: List[CommandHandlerCase[Command, Event, State]] = Nil - private def addCase(predicate: Command ⇒ Boolean, handler: BiFunction[S, Command, Effect[Event, State]]): Unit = { + private def addCase(predicate: Command => Boolean, handler: BiFunction[S, Command, Effect[Event, State]]): Unit = { cases = CommandHandlerCase[Command, Event, State]( commandPredicate = predicate, - statePredicate = state ⇒ + statePredicate = state => if (state == null) statePredicate.test(state.asInstanceOf[S]) else statePredicate.test(state.asInstanceOf[S]) && stateClass.isAssignableFrom(state.getClass), handler.asInstanceOf[BiFunction[State, Command, Effect[Event, State]]]) :: cases @@ -207,7 +207,7 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int * otherwise you risk to 'shadow' part of your command handlers. */ def onCommand(predicate: Predicate[Command], handler: BiFunction[S, Command, Effect[Event, State]]): CommandHandlerBuilderByState[Command, Event, S, State] = { - addCase(cmd ⇒ predicate.test(cmd), handler) + addCase(cmd => predicate.test(cmd), handler) this } @@ -222,7 +222,7 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int * otherwise you risk to 'shadow' part of your command handlers. */ def onCommand(predicate: Predicate[Command], handler: JFunction[Command, Effect[Event, State]]): CommandHandlerBuilderByState[Command, Event, S, State] = { - addCase(cmd ⇒ predicate.test(cmd), new BiFunction[S, Command, Effect[Event, State]] { + addCase(cmd => predicate.test(cmd), new BiFunction[S, Command, Effect[Event, State]] { override def apply(state: S, cmd: Command): Effect[Event, State] = handler(cmd) }) this @@ -236,7 +236,7 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int * otherwise you risk to 'shadow' part of your command handlers. */ def onCommand[C <: Command](commandClass: Class[C], handler: BiFunction[S, C, Effect[Event, State]]): CommandHandlerBuilderByState[Command, Event, S, State] = { - addCase(cmd ⇒ commandClass.isAssignableFrom(cmd.getClass), handler.asInstanceOf[BiFunction[S, Command, Effect[Event, State]]]) + addCase(cmd => commandClass.isAssignableFrom(cmd.getClass), handler.asInstanceOf[BiFunction[S, Command, Effect[Event, State]]]) this } @@ -287,7 +287,7 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int * @return A CommandHandler from the appended states. */ def onAnyCommand(handler: BiFunction[S, Command, Effect[Event, State]]): CommandHandler[Command, Event, State] = { - addCase(_ ⇒ true, handler) + addCase(_ => true, handler) build() } @@ -309,7 +309,7 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int * @return A CommandHandler from the appended states. */ def onAnyCommand(handler: JFunction[Command, Effect[Event, State]]): CommandHandler[Command, Event, State] = { - addCase(_ ⇒ true, new BiFunction[S, Command, Effect[Event, State]] { + addCase(_ => true, new BiFunction[S, Command, Effect[Event, State]] { override def apply(state: S, cmd: Command): Effect[Event, State] = handler(cmd) }) build() @@ -332,7 +332,7 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int * @return A CommandHandler from the appended states. */ def onAnyCommand(handler: Supplier[Effect[Event, State]]): CommandHandler[Command, Event, State] = { - addCase(_ ⇒ true, new BiFunction[S, Command, Effect[Event, State]] { + addCase(_ => true, new BiFunction[S, Command, Effect[Event, State]] { override def apply(state: S, cmd: Command): Effect[Event, State] = handler.get() }) build() @@ -371,8 +371,8 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int } effect match { - case OptionVal.None ⇒ throw new MatchError(s"No match found for command of type [${command.getClass.getName}]") - case OptionVal.Some(e) ⇒ e.asInstanceOf[EffectImpl[Event, State]] + case OptionVal.None => throw new MatchError(s"No match found for command of type [${command.getClass.getName}]") + case OptionVal.Some(e) => e.asInstanceOf[EffectImpl[Event, State]] } } } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/CommandHandlerWithReply.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/CommandHandlerWithReply.scala index 884f1e6fbc..8cb7f44b96 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/CommandHandlerWithReply.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/CommandHandlerWithReply.scala @@ -5,7 +5,7 @@ package akka.persistence.typed.javadsl import java.util.Objects -import java.util.function.{ BiFunction, Predicate, Supplier, Function ⇒ JFunction } +import java.util.function.{ BiFunction, Predicate, Supplier, Function => JFunction } import akka.annotation.InternalApi import akka.persistence.typed.internal._ @@ -103,7 +103,7 @@ final class CommandHandlerWithReplyBuilder[Command, Event, State]() { * @return A new, mutable, CommandHandlerWithReplyBuilderByState */ def forNullState(): CommandHandlerWithReplyBuilderByState[Command, Event, State, State] = { - val predicate: Predicate[State] = asJavaPredicate(s ⇒ Objects.isNull(s)) + val predicate: Predicate[State] = asJavaPredicate(s => Objects.isNull(s)) val builder = CommandHandlerWithReplyBuilderByState.builder[Command, Event, State](predicate) builders = builder :: builders builder @@ -119,7 +119,7 @@ final class CommandHandlerWithReplyBuilder[Command, Event, State]() { * @return A new, mutable, CommandHandlerWithReplyBuilderByState */ def forNonNullState(): CommandHandlerWithReplyBuilderByState[Command, Event, State, State] = { - val predicate: Predicate[State] = asJavaPredicate(s ⇒ Objects.nonNull(s)) + val predicate: Predicate[State] = asJavaPredicate(s => Objects.nonNull(s)) val builder = CommandHandlerWithReplyBuilderByState.builder[Command, Event, State](predicate) builders = builder :: builders builder @@ -137,7 +137,7 @@ final class CommandHandlerWithReplyBuilder[Command, Event, State]() { * @return A new, mutable, CommandHandlerWithReplyBuilderByState */ def forAnyState(): CommandHandlerWithReplyBuilderByState[Command, Event, State, State] = { - val predicate: Predicate[State] = asJavaPredicate(_ ⇒ true) + val predicate: Predicate[State] = asJavaPredicate(_ => true) val builder = CommandHandlerWithReplyBuilderByState.builder[Command, Event, State](predicate) builders = builder :: builders builder @@ -147,11 +147,11 @@ final class CommandHandlerWithReplyBuilder[Command, Event, State]() { val combined = builders.reverse match { - case head :: Nil ⇒ head - case head :: tail ⇒ tail.foldLeft(head) { (acc, builder) ⇒ + case head :: Nil => head + case head :: tail => tail.foldLeft(head) { (acc, builder) => acc.orElse(builder) } - case Nil ⇒ throw new IllegalStateException("No matchers defined") + case Nil => throw new IllegalStateException("No matchers defined") } combined.build() @@ -186,8 +186,8 @@ object CommandHandlerWithReplyBuilderByState { * INTERNAL API */ @InternalApi private final case class CommandHandlerCase[Command, Event, State]( - commandPredicate: Command ⇒ Boolean, - statePredicate: State ⇒ Boolean, + commandPredicate: Command => Boolean, + statePredicate: State => Boolean, handler: BiFunction[State, Command, ReplyEffect[Event, State]]) } @@ -198,10 +198,10 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St private var cases: List[CommandHandlerCase[Command, Event, State]] = Nil - private def addCase(predicate: Command ⇒ Boolean, handler: BiFunction[S, Command, ReplyEffect[Event, State]]): Unit = { + private def addCase(predicate: Command => Boolean, handler: BiFunction[S, Command, ReplyEffect[Event, State]]): Unit = { cases = CommandHandlerCase[Command, Event, State]( commandPredicate = predicate, - statePredicate = state ⇒ + statePredicate = state => if (state == null) statePredicate.test(state.asInstanceOf[S]) else statePredicate.test(state.asInstanceOf[S]) && stateClass.isAssignableFrom(state.getClass), handler.asInstanceOf[BiFunction[State, Command, ReplyEffect[Event, State]]]) :: cases @@ -215,7 +215,7 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St * otherwise you risk to 'shadow' part of your command handlers. */ def onCommand(predicate: Predicate[Command], handler: BiFunction[S, Command, ReplyEffect[Event, State]]): CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = { - addCase(cmd ⇒ predicate.test(cmd), handler) + addCase(cmd => predicate.test(cmd), handler) this } @@ -230,7 +230,7 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St * otherwise you risk to 'shadow' part of your command handlers. */ def onCommand(predicate: Predicate[Command], handler: JFunction[Command, ReplyEffect[Event, State]]): CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = { - addCase(cmd ⇒ predicate.test(cmd), new BiFunction[S, Command, ReplyEffect[Event, State]] { + addCase(cmd => predicate.test(cmd), new BiFunction[S, Command, ReplyEffect[Event, State]] { override def apply(state: S, cmd: Command): ReplyEffect[Event, State] = handler(cmd) }) this @@ -244,7 +244,7 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St * otherwise you risk to 'shadow' part of your command handlers. */ def onCommand[C <: Command](commandClass: Class[C], handler: BiFunction[S, C, ReplyEffect[Event, State]]): CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = { - addCase(cmd ⇒ commandClass.isAssignableFrom(cmd.getClass), handler.asInstanceOf[BiFunction[S, Command, ReplyEffect[Event, State]]]) + addCase(cmd => commandClass.isAssignableFrom(cmd.getClass), handler.asInstanceOf[BiFunction[S, Command, ReplyEffect[Event, State]]]) this } @@ -295,7 +295,7 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St * @return A CommandHandlerWithReply from the appended states. */ def onAnyCommand(handler: BiFunction[S, Command, ReplyEffect[Event, State]]): CommandHandlerWithReply[Command, Event, State] = { - addCase(_ ⇒ true, handler) + addCase(_ => true, handler) build() } @@ -317,7 +317,7 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St * @return A CommandHandlerWithReply from the appended states. */ def onAnyCommand(handler: JFunction[Command, ReplyEffect[Event, State]]): CommandHandlerWithReply[Command, Event, State] = { - addCase(_ ⇒ true, new BiFunction[S, Command, ReplyEffect[Event, State]] { + addCase(_ => true, new BiFunction[S, Command, ReplyEffect[Event, State]] { override def apply(state: S, cmd: Command): ReplyEffect[Event, State] = handler(cmd) }) build() @@ -340,7 +340,7 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St * @return A CommandHandlerWithReply from the appended states. */ def onAnyCommand(handler: Supplier[ReplyEffect[Event, State]]): CommandHandlerWithReply[Command, Event, State] = { - addCase(_ ⇒ true, new BiFunction[S, Command, ReplyEffect[Event, State]] { + addCase(_ => true, new BiFunction[S, Command, ReplyEffect[Event, State]] { override def apply(state: S, cmd: Command): ReplyEffect[Event, State] = handler.get() }) build() @@ -379,8 +379,8 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St } effect match { - case OptionVal.None ⇒ throw new MatchError(s"No match found for command of type [${command.getClass.getName}]") - case OptionVal.Some(e) ⇒ e.asInstanceOf[EffectImpl[Event, State]] + case OptionVal.None => throw new MatchError(s"No match found for command of type [${command.getClass.getName}]") + case OptionVal.Some(e) => e.asInstanceOf[EffectImpl[Event, State]] } } } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/Effect.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/Effect.scala index 905eb9c6ea..4ac1d859f1 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/Effect.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/Effect.scala @@ -117,7 +117,7 @@ import akka.persistence.typed.internal._ * Not intended for user extension. */ @DoNotInherit abstract class Effect[+Event, State] { - self: EffectImpl[Event, State] ⇒ + self: EffectImpl[Event, State] => /** * Run the given callback. Callbacks are run sequentially. * @@ -128,13 +128,13 @@ import akka.persistence.typed.internal._ * */ final def thenRun[NewState <: State](callback: function.Procedure[NewState]): Effect[Event, State] = - CompositeEffect(this, SideEffect[State](s ⇒ callback.apply(s.asInstanceOf[NewState]))) + CompositeEffect(this, SideEffect[State](s => callback.apply(s.asInstanceOf[NewState]))) /** * Run the given callback. Callbacks are run sequentially. */ final def thenRun(callback: function.Effect): Effect[Event, State] = - CompositeEffect(this, SideEffect[State]((_: State) ⇒ callback.apply())) + CompositeEffect(this, SideEffect[State]((_: State) => callback.apply())) /** * Run the given callback after the current Effect @@ -166,7 +166,7 @@ import akka.persistence.typed.internal._ * finding mistakes. */ def thenReply[ReplyMessage](cmd: ExpectingReply[ReplyMessage], replyWithMessage: function.Function[State, ReplyMessage]): ReplyEffect[Event, State] = - CompositeEffect(this, SideEffect[State](newState ⇒ cmd.replyTo ! replyWithMessage(newState))) + CompositeEffect(this, SideEffect[State](newState => cmd.replyTo ! replyWithMessage(newState))) /** * When [[EventSourcedBehaviorWithEnforcedReplies]] is used there will be compilation errors if the returned effect @@ -183,5 +183,5 @@ import akka.persistence.typed.internal._ * created with `Effects().reply`, `Effects().noReply`, [[Effect.thenReply]], or [[Effect.thenNoReply]]. */ @DoNotInherit abstract class ReplyEffect[+Event, State] extends Effect[Event, State] { - self: EffectImpl[Event, State] ⇒ + self: EffectImpl[Event, State] => } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/EventHandler.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/EventHandler.scala index 163ae6bdf0..d36ca52520 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/EventHandler.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/EventHandler.scala @@ -5,7 +5,7 @@ package akka.persistence.typed.javadsl import java.util.Objects -import java.util.function.{ BiFunction, Predicate, Supplier, Function ⇒ JFunction } +import java.util.function.{ BiFunction, Predicate, Supplier, Function => JFunction } import akka.annotation.InternalApi import akka.util.OptionVal @@ -96,7 +96,7 @@ final class EventHandlerBuilder[State >: Null, Event]() { * @return A new, mutable, EventHandlerBuilderByState */ def forNullState(): EventHandlerBuilderByState[State, State, Event] = { - val predicate: Predicate[State] = asJavaPredicate(s ⇒ Objects.isNull(s)) + val predicate: Predicate[State] = asJavaPredicate(s => Objects.isNull(s)) val builder = EventHandlerBuilderByState.builder[State, Event](predicate) builders = builder :: builders builder @@ -112,7 +112,7 @@ final class EventHandlerBuilder[State >: Null, Event]() { * @return A new, mutable, EventHandlerBuilderByState */ def forNonNullState(): EventHandlerBuilderByState[State, State, Event] = { - val predicate: Predicate[State] = asJavaPredicate(s ⇒ Objects.nonNull(s)) + val predicate: Predicate[State] = asJavaPredicate(s => Objects.nonNull(s)) val builder = EventHandlerBuilderByState.builder[State, Event](predicate) builders = builder :: builders builder @@ -130,7 +130,7 @@ final class EventHandlerBuilder[State >: Null, Event]() { * @return A new, mutable, EventHandlerBuilderByState */ def forAnyState(): EventHandlerBuilderByState[State, State, Event] = { - val predicate: Predicate[State] = asJavaPredicate(_ ⇒ true) + val predicate: Predicate[State] = asJavaPredicate(_ => true) val builder = EventHandlerBuilderByState.builder[State, Event](predicate) builders = builder :: builders builder @@ -140,11 +140,11 @@ final class EventHandlerBuilder[State >: Null, Event]() { val combined = builders.reverse match { - case head :: Nil ⇒ head - case head :: tail ⇒ tail.foldLeft(head) { (acc, builder) ⇒ + case head :: Nil => head + case head :: tail => tail.foldLeft(head) { (acc, builder) => acc.orElse(builder) } - case Nil ⇒ throw new IllegalStateException("No matchers defined") + case Nil => throw new IllegalStateException("No matchers defined") } combined.build() @@ -179,8 +179,8 @@ object EventHandlerBuilderByState { * INTERNAL API */ @InternalApi private final case class EventHandlerCase[State, Event]( - statePredicate: State ⇒ Boolean, - eventPredicate: Event ⇒ Boolean, + statePredicate: State => Boolean, + eventPredicate: Event => Boolean, handler: BiFunction[State, Event, State]) } @@ -190,9 +190,9 @@ final class EventHandlerBuilderByState[S <: State, State >: Null, Event](private private var cases: List[EventHandlerCase[State, Event]] = Nil - private def addCase(eventPredicate: Event ⇒ Boolean, handler: BiFunction[State, Event, State]): Unit = { + private def addCase(eventPredicate: Event => Boolean, handler: BiFunction[State, Event, State]): Unit = { cases = EventHandlerCase[State, Event]( - statePredicate = state ⇒ + statePredicate = state => if (state == null) statePredicate.test(state.asInstanceOf[S]) else statePredicate.test(state.asInstanceOf[S]) && stateClass.isAssignableFrom(state.getClass), eventPredicate = eventPredicate, @@ -207,7 +207,7 @@ final class EventHandlerBuilderByState[S <: State, State >: Null, Event](private * otherwise you risk to 'shadow' part of your event handlers. */ def onEvent[E <: Event](eventClass: Class[E], handler: BiFunction[S, E, State]): EventHandlerBuilderByState[S, State, Event] = { - addCase(e ⇒ eventClass.isAssignableFrom(e.getClass), handler.asInstanceOf[BiFunction[State, Event, State]]) + addCase(e => eventClass.isAssignableFrom(e.getClass), handler.asInstanceOf[BiFunction[State, Event, State]]) this } @@ -258,7 +258,7 @@ final class EventHandlerBuilderByState[S <: State, State >: Null, Event](private * @return An EventHandler from the appended states. */ def onAnyEvent(handler: BiFunction[State, Event, State]): EventHandler[State, Event] = { - addCase(_ ⇒ true, handler.asInstanceOf[BiFunction[State, Event, State]]) + addCase(_ => true, handler.asInstanceOf[BiFunction[State, Event, State]]) build() } @@ -315,10 +315,10 @@ final class EventHandlerBuilderByState[S <: State, State >: Null, Event](private } result match { - case OptionVal.None ⇒ + case OptionVal.None => val stateClass = if (state == null) "null" else state.getClass.getName throw new MatchError(s"No match found for event [${event.getClass}] and state [$stateClass]. Has this event been stored using an EventAdapter?") - case OptionVal.Some(s) ⇒ s + case OptionVal.Some(s) => s } } } diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/EventSourcedBehavior.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/EventSourcedBehavior.scala index c5f4f96ef8..c3500d4ec0 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/EventSourcedBehavior.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/javadsl/EventSourcedBehavior.scala @@ -148,7 +148,7 @@ abstract class EventSourcedBehavior[Command, Event, State >: Null] private[akka] * INTERNAL API: DeferredBehavior init */ @InternalApi override def apply(context: typed.TypedActorContext[Command]): Behavior[Command] = { - val snapshotWhen: (State, Event, Long) ⇒ Boolean = { (state, event, seqNr) ⇒ + val snapshotWhen: (State, Event, Long) => Boolean = { (state, event, seqNr) => val n = snapshotEvery() if (n > 0) seqNr % n == 0 @@ -156,7 +156,7 @@ abstract class EventSourcedBehavior[Command, Event, State >: Null] private[akka] shouldSnapshot(state, event, seqNr) } - val tagger: Event ⇒ Set[String] = { event ⇒ + val tagger: Event => Set[String] = { event => import scala.collection.JavaConverters._ val tags = tagsFor(event) if (tags.isEmpty) Set.empty @@ -166,25 +166,25 @@ abstract class EventSourcedBehavior[Command, Event, State >: Null] private[akka] val behavior = new internal.EventSourcedBehaviorImpl[Command, Event, State]( persistenceId, emptyState, - (state, cmd) ⇒ commandHandler()(state, cmd).asInstanceOf[EffectImpl[Event, State]], + (state, cmd) => commandHandler()(state, cmd).asInstanceOf[EffectImpl[Event, State]], eventHandler()(_, _), getClass) .onRecoveryCompleted(onRecoveryCompleted) - .onPostStop(() ⇒ onPostStop()) - .onPreRestart(() ⇒ onPreRestart()) + .onPostStop(() => onPostStop()) + .onPreRestart(() => onPreRestart()) .snapshotWhen(snapshotWhen) .withTagger(tagger) - .onSnapshot((meta, result) ⇒ { + .onSnapshot((meta, result) => { result match { - case Success(_) ⇒ + case Success(_) => context.asScala.log.debug("Save snapshot successful, snapshot metadata: [{}]", meta) - case Failure(e) ⇒ + case Failure(e) => context.asScala.log.error(e, "Save snapshot failed, snapshot metadata: [{}]", meta) } onSnapshot(meta, result match { - case Success(_) ⇒ Optional.empty() - case Failure(t) ⇒ Optional.of(t) + case Success(_) => Optional.empty() + case Failure(t) => Optional.of(t) }) }) .eventAdapter(eventAdapter()) diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/scaladsl/Effect.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/scaladsl/Effect.scala index 7df50d1b0e..1e79cf4cec 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/scaladsl/Effect.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/scaladsl/Effect.scala @@ -4,7 +4,7 @@ package akka.persistence.typed.scaladsl -import scala.collection.{ immutable ⇒ im } +import scala.collection.{ immutable => im } import akka.annotation.DoNotInherit import akka.persistence.typed.ExpectingReply @@ -101,7 +101,7 @@ object Effect { * finding mistakes. */ def reply[ReplyMessage, Event, State](cmd: ExpectingReply[ReplyMessage])(replyWithMessage: ReplyMessage): ReplyEffect[Event, State] = - none[Event, State].thenReply[ReplyMessage](cmd)(_ ⇒ replyWithMessage) + none[Event, State].thenReply[ReplyMessage](cmd)(_ => replyWithMessage) /** * When [[EventSourcedBehavior.withEnforcedReplies]] is used there will be compilation errors if the returned effect @@ -126,7 +126,7 @@ trait Effect[+Event, State] { /** * Run the given callback. Callbacks are run sequentially. */ - final def thenRun(callback: State ⇒ Unit): Effect[Event, State] = + final def thenRun(callback: State => Unit): Effect[Event, State] = CompositeEffect(this, SideEffect(callback)) /** @@ -164,7 +164,7 @@ trait Effect[+Event, State] { * The reply message will be sent also if `withEnforcedReplies` isn't used, but then the compiler will not help * finding mistakes. */ - def thenReply[ReplyMessage](cmd: ExpectingReply[ReplyMessage])(replyWithMessage: State ⇒ ReplyMessage): ReplyEffect[Event, State] = + def thenReply[ReplyMessage](cmd: ExpectingReply[ReplyMessage])(replyWithMessage: State => ReplyMessage): ReplyEffect[Event, State] = CompositeEffect(this, new ReplyEffectImpl[ReplyMessage, State](cmd.replyTo, replyWithMessage)) /** diff --git a/akka-persistence-typed/src/main/scala/akka/persistence/typed/scaladsl/EventSourcedBehavior.scala b/akka-persistence-typed/src/main/scala/akka/persistence/typed/scaladsl/EventSourcedBehavior.scala index 1186e0bfd7..5e4980128f 100644 --- a/akka-persistence-typed/src/main/scala/akka/persistence/typed/scaladsl/EventSourcedBehavior.scala +++ b/akka-persistence-typed/src/main/scala/akka/persistence/typed/scaladsl/EventSourcedBehavior.scala @@ -31,7 +31,7 @@ object EventSourcedBehavior { * when full function type is used. When defining the handler as a separate function value it can * be useful to use the alias for shorter type signature. */ - type CommandHandler[Command, Event, State] = (State, Command) ⇒ Effect[Event, State] + type CommandHandler[Command, Event, State] = (State, Command) => Effect[Event, State] /** * Type alias for the event handler function for updating the state based on events having been persisted. @@ -40,7 +40,7 @@ object EventSourcedBehavior { * when full function type is used. When defining the handler as a separate function value it can * be useful to use the alias for shorter type signature. */ - type EventHandler[State, Event] = (State, Event) ⇒ State + type EventHandler[State, Event] = (State, Event) => State /** * Create a `Behavior` for a persistent actor. @@ -48,8 +48,8 @@ object EventSourcedBehavior { def apply[Command, Event, State]( persistenceId: PersistenceId, emptyState: State, - commandHandler: (State, Command) ⇒ Effect[Event, State], - eventHandler: (State, Event) ⇒ State): EventSourcedBehavior[Command, Event, State] = { + commandHandler: (State, Command) => Effect[Event, State], + eventHandler: (State, Event) => State): EventSourcedBehavior[Command, Event, State] = { val loggerClass = LoggerClass.detectLoggerClassFromStack(classOf[EventSourcedBehavior[_, _, _]]) EventSourcedBehaviorImpl(persistenceId, emptyState, commandHandler, eventHandler, loggerClass) } @@ -62,8 +62,8 @@ object EventSourcedBehavior { def withEnforcedReplies[Command <: ExpectingReply[_], Event, State]( persistenceId: PersistenceId, emptyState: State, - commandHandler: (State, Command) ⇒ ReplyEffect[Event, State], - eventHandler: (State, Event) ⇒ State): EventSourcedBehavior[Command, Event, State] = { + commandHandler: (State, Command) => ReplyEffect[Event, State], + eventHandler: (State, Event) => State): EventSourcedBehavior[Command, Event, State] = { val loggerClass = LoggerClass.detectLoggerClassFromStack(classOf[EventSourcedBehavior[_, _, _]]) EventSourcedBehaviorImpl(persistenceId, emptyState, commandHandler, eventHandler, loggerClass) } @@ -73,7 +73,7 @@ object EventSourcedBehavior { * a function: * * {{{ - * (State, Command) ⇒ Effect[Event, State] + * (State, Command) => Effect[Event, State] * }}} * * The [[CommandHandler#command]] is useful for simple commands that don't need the state @@ -86,8 +86,8 @@ object EventSourcedBehavior { * * @see [[Effect]] for possible effects of a command. */ - def command[Command, Event, State](commandHandler: Command ⇒ Effect[Event, State]): (State, Command) ⇒ Effect[Event, State] = - (_, cmd) ⇒ commandHandler(cmd) + def command[Command, Event, State](commandHandler: Command => Effect[Event, State]): (State, Command) => Effect[Event, State] = + (_, cmd) => commandHandler(cmd) } @@ -98,17 +98,17 @@ object EventSourcedBehavior { @tailrec def extractConcreteBehavior(beh: Behavior[_]): Behavior[_] = beh match { - case interceptor: InterceptorImpl[_, _] ⇒ extractConcreteBehavior(interceptor.nestedBehavior) - case concrete ⇒ concrete + case interceptor: InterceptorImpl[_, _] => extractConcreteBehavior(interceptor.nestedBehavior) + case concrete => concrete } context match { - case impl: ActorContextAdapter[_] ⇒ + case impl: ActorContextAdapter[_] => extractConcreteBehavior(impl.currentBehavior) match { - case w: Running.WithSeqNrAccessible ⇒ w.currentSequenceNumber - case s ⇒ throw new IllegalStateException(s"Cannot extract the lastSequenceNumber in state ${s.getClass.getName}") + case w: Running.WithSeqNrAccessible => w.currentSequenceNumber + case s => throw new IllegalStateException(s"Cannot extract the lastSequenceNumber in state ${s.getClass.getName}") } - case c ⇒ throw new IllegalStateException(s"Cannot extract the lastSequenceNumber from context ${c.getClass.getName}") + case c => throw new IllegalStateException(s"Cannot extract the lastSequenceNumber from context ${c.getClass.getName}") } } @@ -126,27 +126,27 @@ object EventSourcedBehavior { /** * The `callback` function is called to notify that the recovery process has finished. */ - def onRecoveryCompleted(callback: State ⇒ Unit): EventSourcedBehavior[Command, Event, State] + def onRecoveryCompleted(callback: State => Unit): EventSourcedBehavior[Command, Event, State] /** * The `callback` function is called to notify that recovery has failed. For setting a supervision * strategy `onPersistFailure` */ - def onRecoveryFailure(callback: Throwable ⇒ Unit): EventSourcedBehavior[Command, Event, State] + def onRecoveryFailure(callback: Throwable => Unit): EventSourcedBehavior[Command, Event, State] /** * The `callback` function is called to notify that the actor has stopped. */ - def onPostStop(callback: () ⇒ Unit): EventSourcedBehavior[Command, Event, State] + def onPostStop(callback: () => Unit): EventSourcedBehavior[Command, Event, State] /** * The `callback` function is called to notify that the actor is restarted. */ - def onPreRestart(callback: () ⇒ Unit): EventSourcedBehavior[Command, Event, State] + def onPreRestart(callback: () => Unit): EventSourcedBehavior[Command, Event, State] /** * The `callback` function is called to notify when a snapshot is complete. */ - def onSnapshot(callback: (SnapshotMetadata, Try[Done]) ⇒ Unit): EventSourcedBehavior[Command, Event, State] + def onSnapshot(callback: (SnapshotMetadata, Try[Done]) => Unit): EventSourcedBehavior[Command, Event, State] /** * Initiates a snapshot if the given function returns true. @@ -155,7 +155,7 @@ object EventSourcedBehavior { * * `predicate` receives the State, Event and the sequenceNr used for the Event */ - def snapshotWhen(predicate: (State, Event, Long) ⇒ Boolean): EventSourcedBehavior[Command, Event, State] + def snapshotWhen(predicate: (State, Event, Long) => Boolean): EventSourcedBehavior[Command, Event, State] /** * Snapshot every N events * @@ -186,7 +186,7 @@ object EventSourcedBehavior { /** * The `tagger` function should give event tags, which will be used in persistence query */ - def withTagger(tagger: Event ⇒ Set[String]): EventSourcedBehavior[Command, Event, State] + def withTagger(tagger: Event => Set[String]): EventSourcedBehavior[Command, Event, State] /** * Transform the event in another type before giving to the journal. Can be used to wrap events diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/ManyRecoveriesSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/ManyRecoveriesSpec.scala index 5b099cfab0..f9565edc3b 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/ManyRecoveriesSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/ManyRecoveriesSpec.scala @@ -30,21 +30,21 @@ object ManyRecoveriesSpec { persistenceId = PersistenceId(name), emptyState = "", commandHandler = CommandHandler.command { - case Cmd(s) ⇒ Effect.persist(Evt(s)).thenRun(_ ⇒ probe.ref ! s"$name-$s") + case Cmd(s) => Effect.persist(Evt(s)).thenRun(_ => probe.ref ! s"$name-$s") }, eventHandler = { - case (state, _) ⇒ latch.foreach(Await.ready(_, 10.seconds)); state + case (state, _) => latch.foreach(Await.ready(_, 10.seconds)); state } ) def forwardBehavior(sender: TestProbe[String]): Behaviors.Receive[Int] = Behaviors.receiveMessagePartial[Int] { - case value ⇒ + case value => sender.ref ! value.toString Behaviors.same } - def forN(n: Int)(mapper: Int ⇒ String): Set[String] = + def forN(n: Int)(mapper: Int => String): Set[String] = (1 to n).map(mapper).toSet } @@ -66,7 +66,7 @@ class ManyRecoveriesSpec extends ScalaTestWithActorTestKit(s""" "Many persistent actors" must { "be able to recover without overloading" in { val probe = TestProbe[String]() - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => val name = s"a$n" spawn(persistentBehavior(s"a$n", probe, latch = None), name) ! Cmd("A") probe.expectMessage(s"a$n-A") @@ -74,20 +74,20 @@ class ManyRecoveriesSpec extends ScalaTestWithActorTestKit(s""" // this would starve (block) all threads without max-concurrent-recoveries val latch = TestLatch()(system.toUntyped) - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => spawn(persistentBehavior(s"a$n", probe, Some(latch))) ! Cmd("B") } // this should be able to progress even though above is blocking, // 2 remaining non-blocked threads - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => spawn(forwardBehavior(probe)) ! n probe.expectMessage(n.toString) } latch.countDown() - forN(100)(_ ⇒ probe.receiveMessage()) should - be(forN(100)(i ⇒ s"a$i-B")) + forN(100)(_ => probe.receiveMessage()) should + be(forN(100)(i => s"a$i-B")) } } } diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/internal/RecoveryPermitterSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/internal/RecoveryPermitterSpec.scala index ed28a70a8c..d6b1acb8b8 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/internal/RecoveryPermitterSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/internal/RecoveryPermitterSpec.scala @@ -48,18 +48,18 @@ object RecoveryPermitterSpec { persistenceId = PersistenceId(name), emptyState = EmptyState, commandHandler = CommandHandler.command { - case StopActor ⇒ Effect.stop() - case command ⇒ commandProbe.ref ! command; Effect.none + case StopActor => Effect.stop() + case command => commandProbe.ref ! command; Effect.none }, - eventHandler = { (state, event) ⇒ eventProbe.ref ! event; state } - ).onRecoveryCompleted { _ ⇒ + eventHandler = { (state, event) => eventProbe.ref ! event; state } + ).onRecoveryCompleted { _ => eventProbe.ref ! Recovered if (throwOnRecovery) throw new TE } def forwardingBehavior(target: TestProbe[Any]): Behavior[Any] = Behaviors.receive[Any] { - (_, any) ⇒ target.ref ! any; Behaviors.same + (_, any) => target.ref ! any; Behaviors.same } } @@ -187,15 +187,15 @@ class RecoveryPermitterSpec extends ScalaTestWithActorTestKit(s""" val parent = EventFilter.error(occurrences = 1, start = "Exception during recovery.").intercept { spawn( - Behaviors.setup[Command](ctx ⇒ { + Behaviors.setup[Command](ctx => { val persistentActor = ctx.spawnAnonymous(persistentBehavior("p3", p3, p3, throwOnRecovery = true)) Behaviors.receive[Command] { - case (_, StopActor) ⇒ + case (_, StopActor) => stopProbe.ref ! persistentActor ctx.stop(persistentActor) Behavior.same - case (_, message) ⇒ + case (_, message) => persistentActor ! message Behaviors.same } diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/internal/StashStateSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/internal/StashStateSpec.scala index 1942f400ed..4e9bca4eaa 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/internal/StashStateSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/internal/StashStateSpec.scala @@ -38,16 +38,16 @@ class StashStateSpec extends ScalaTestWithActorTestKit with WordSpecLike { def apply(probe: TestProbe[Int]): Behavior[InternalProtocol] = { val settings = dummySettings() - Behaviors.setup[InternalProtocol] { _ ⇒ + Behaviors.setup[InternalProtocol] { _ => val stashState = new StashState(settings) Behaviors.receiveMessagePartial[InternalProtocol] { - case RecoveryPermitGranted ⇒ + case RecoveryPermitGranted => stashState.internalStashBuffer.stash(RecoveryPermitGranted) probe.ref ! stashState.internalStashBuffer.size Behaviors.same[InternalProtocol] - case _: IncomingCommand[_] ⇒ Behaviors.stopped + case _: IncomingCommand[_] => Behaviors.stopped }.receiveSignal { - case (_, _) ⇒ + case (_, _) => stashState.clearStashBuffers() Behaviors.stopped[InternalProtocol] } diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorFailureSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorFailureSpec.scala index 74094a8614..21869b23e5 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorFailureSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorFailureSpec.scala @@ -37,7 +37,7 @@ class ChaosJournal extends InmemJournal { Future.failed(TestException("database says no")) } else if (pid == "reject-first" && reject) { reject = false - Future.successful(messages.map(_ ⇒ Try { + Future.successful(messages.map(_ => Try { throw TestException("I don't like it") })) } else { @@ -77,21 +77,21 @@ class EventSourcedBehaviorFailureSpec extends ScalaTestWithActorTestKit(EventSou def failingPersistentActor(pid: PersistenceId, probe: ActorRef[String]): EventSourcedBehavior[String, String, String] = EventSourcedBehavior[String, String, String]( pid, "", - (_, cmd) ⇒ { + (_, cmd) => { if (cmd == "wrong") throw new TestException("wrong command") probe.tell("persisting") Effect.persist(cmd) }, - (state, event) ⇒ { + (state, event) => { probe.tell(event) state + event } - ).onRecoveryCompleted { _ ⇒ + ).onRecoveryCompleted { _ => probe.tell("starting") } - .onPostStop(() ⇒ probe.tell("stopped")) - .onPreRestart(() ⇒ probe.tell("restarting")) + .onPostStop(() => probe.tell("stopped")) + .onPreRestart(() => probe.tell("restarting")) .onPersistFailure(SupervisorStrategy.restartWithBackoff(1.milli, 5.millis, 0.1) .withLoggingEnabled(enabled = false)) @@ -101,7 +101,7 @@ class EventSourcedBehaviorFailureSpec extends ScalaTestWithActorTestKit(EventSou val probe = TestProbe[String]() val excProbe = TestProbe[Throwable]() spawn(failingPersistentActor(PersistenceId("fail-recovery"), probe.ref) - .onRecoveryFailure(t ⇒ excProbe.ref ! t)) + .onRecoveryFailure(t => excProbe.ref ! t)) excProbe.expectMessageType[TestException].message shouldEqual "Nope" probe.expectMessage("restarting") @@ -110,7 +110,7 @@ class EventSourcedBehaviorFailureSpec extends ScalaTestWithActorTestKit(EventSou "handle exceptions in onRecoveryFailure" in { val probe = TestProbe[String]() val pa = spawn(failingPersistentActor(PersistenceId("fail-recovery-twice"), probe.ref) - .onRecoveryFailure(_ ⇒ throw TestException("recovery call back failure"))) + .onRecoveryFailure(_ => throw TestException("recovery call back failure"))) pa ! "one" probe.expectMessage("starting") probe.expectMessage("persisting") diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorReplySpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorReplySpec.scala index c39d4e1b2f..a8464d6a74 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorReplySpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorReplySpec.scala @@ -42,7 +42,7 @@ object EventSourcedBehaviorReplySpec { final case class State(value: Int, history: Vector[Int]) def counter(persistenceId: PersistenceId): Behavior[Command[_]] = - Behaviors.setup(ctx ⇒ counter(ctx, persistenceId)) + Behaviors.setup(ctx => counter(ctx, persistenceId)) def counter( ctx: ActorContext[Command[_]], @@ -50,26 +50,26 @@ object EventSourcedBehaviorReplySpec { EventSourcedBehavior.withEnforcedReplies[Command[_], Event, State]( persistenceId, emptyState = State(0, Vector.empty), - commandHandler = (state, command) ⇒ command match { + commandHandler = (state, command) => command match { - case cmd: IncrementWithConfirmation ⇒ + case cmd: IncrementWithConfirmation => Effect.persist(Incremented(1)) - .thenReply(cmd)(_ ⇒ Done) + .thenReply(cmd)(_ => Done) - case cmd: IncrementReplyLater ⇒ + case cmd: IncrementReplyLater => Effect.persist(Incremented(1)) - .thenRun((_: State) ⇒ ctx.self ! ReplyNow(cmd.replyTo)) + .thenRun((_: State) => ctx.self ! ReplyNow(cmd.replyTo)) .thenNoReply() - case cmd: ReplyNow ⇒ + case cmd: ReplyNow => Effect.reply(cmd)(Done) - case query: GetValue ⇒ + case query: GetValue => Effect.reply(query)(state) }, - eventHandler = (state, evt) ⇒ evt match { - case Incremented(delta) ⇒ + eventHandler = (state, evt) => evt match { + case Incremented(delta) => State(state.value + delta, state.history :+ state.value) }) } diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorSpec.scala index a39df7f9d3..dffe6459dd 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorSpec.scala @@ -115,10 +115,10 @@ object EventSourcedBehaviorSpec { val secondLogging = "second logging" def counter(persistenceId: PersistenceId)(implicit system: ActorSystem[_]): Behavior[Command] = - Behaviors.setup(ctx ⇒ counter(ctx, persistenceId)) + Behaviors.setup(ctx => counter(ctx, persistenceId)) def counter(persistenceId: PersistenceId, logging: ActorRef[String])(implicit system: ActorSystem[_]): Behavior[Command] = - Behaviors.setup(ctx ⇒ counter(ctx, persistenceId, logging)) + Behaviors.setup(ctx => counter(ctx, persistenceId, logging)) def counter(ctx: ActorContext[Command], persistenceId: PersistenceId)(implicit system: ActorSystem[_]): EventSourcedBehavior[Command, Event, State] = counter(ctx, persistenceId, loggingActor = TestProbe[String].ref, probe = TestProbe[(State, Event)].ref, TestProbe[Try[Done]].ref) @@ -144,102 +144,102 @@ object EventSourcedBehaviorSpec { EventSourcedBehavior[Command, Event, State]( persistenceId, emptyState = State(0, Vector.empty), - commandHandler = (state, cmd) ⇒ cmd match { - case Increment ⇒ + commandHandler = (state, cmd) => cmd match { + case Increment => Effect.persist(Incremented(1)) - case IncrementThenLogThenStop ⇒ + case IncrementThenLogThenStop => Effect.persist(Incremented(1)) - .thenRun { (_: State) ⇒ + .thenRun { (_: State) => loggingActor ! firstLogging } .thenStop - case IncrementTwiceThenLogThenStop ⇒ + case IncrementTwiceThenLogThenStop => Effect.persist(Incremented(1), Incremented(2)) - .thenRun { (_: State) ⇒ + .thenRun { (_: State) => loggingActor ! firstLogging } .thenStop - case IncrementWithPersistAll(n) ⇒ - Effect.persist((0 until n).map(_ ⇒ Incremented(1))) + case IncrementWithPersistAll(n) => + Effect.persist((0 until n).map(_ => Incremented(1))) - case cmd: IncrementWithConfirmation ⇒ + case cmd: IncrementWithConfirmation => Effect.persist(Incremented(1)) - .thenReply(cmd)(_ ⇒ Done) + .thenReply(cmd)(_ => Done) - case GetValue(replyTo) ⇒ + case GetValue(replyTo) => replyTo ! state Effect.none - case IncrementLater ⇒ + case IncrementLater => // purpose is to test signals - val delay = ctx.spawnAnonymous(Behaviors.withTimers[Tick.type] { timers ⇒ + val delay = ctx.spawnAnonymous(Behaviors.withTimers[Tick.type] { timers => timers.startSingleTimer(Tick, Tick, 10.millis) - Behaviors.receive((_, msg) ⇒ msg match { - case Tick ⇒ Behaviors.stopped + Behaviors.receive((_, msg) => msg match { + case Tick => Behaviors.stopped }) }) ctx.watchWith(delay, DelayFinished) Effect.none - case DelayFinished ⇒ + case DelayFinished => Effect.persist(Incremented(10)) - case IncrementAfterReceiveTimeout ⇒ + case IncrementAfterReceiveTimeout => ctx.setReceiveTimeout(10.millis, Timeout) Effect.none - case Timeout ⇒ + case Timeout => ctx.cancelReceiveTimeout() Effect.persist(Incremented(100)) - case IncrementTwiceAndThenLog ⇒ + case IncrementTwiceAndThenLog => Effect .persist(Incremented(1), Incremented(1)) - .thenRun { (_: State) ⇒ + .thenRun { (_: State) => loggingActor ! firstLogging } - .thenRun { _ ⇒ + .thenRun { _ => loggingActor ! secondLogging } - case EmptyEventsListAndThenLog ⇒ + case EmptyEventsListAndThenLog => Effect .persist(List.empty) // send empty list of events - .thenRun { _ ⇒ + .thenRun { _ => loggingActor ! firstLogging } - case DoNothingAndThenLog ⇒ + case DoNothingAndThenLog => Effect .none - .thenRun { _ ⇒ + .thenRun { _ => loggingActor ! firstLogging } - case LogThenStop ⇒ + case LogThenStop => Effect.none[Event, State] - .thenRun { _ ⇒ + .thenRun { _ => loggingActor ! firstLogging } .thenStop - case Fail ⇒ + case Fail => throw new TestException("boom!") - case StopIt ⇒ + case StopIt => Effect.none.thenStop() }, - eventHandler = (state, evt) ⇒ evt match { - case Incremented(delta) ⇒ + eventHandler = (state, evt) => evt match { + case Incremented(delta) => probe ! ((state, evt)) State(state.value + delta, state.history :+ state.value) - }).onRecoveryCompleted(_ ⇒ ()) + }).onRecoveryCompleted(_ => ()) .onSnapshot { - case (_, result) ⇒ + case (_, result) => snapshotProbe ! result } } @@ -416,8 +416,8 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh val pid = nextPid val snapshotProbe = TestProbe[Try[Done]] val alwaysSnapshot: Behavior[Command] = - Behaviors.setup { ctx ⇒ - counterWithSnapshotProbe(ctx, pid, snapshotProbe.ref).snapshotWhen { (_, _, _) ⇒ true } + Behaviors.setup { ctx => + counterWithSnapshotProbe(ctx, pid, snapshotProbe.ref).snapshotWhen { (_, _, _) => true } } val c = spawn(alwaysSnapshot) val watchProbe = watcher(c) @@ -431,7 +431,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh watchProbe.expectMessage("Terminated") val probe = TestProbe[(State, Event)]() - val c2 = spawn(Behaviors.setup[Command](ctx ⇒ counterWithProbe(ctx, pid, probe.ref))) + val c2 = spawn(Behaviors.setup[Command](ctx => counterWithProbe(ctx, pid, probe.ref))) // state should be rebuilt from snapshot, no events replayed // Fails as snapshot is async (i think) probe.expectNoMessage() @@ -443,8 +443,8 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "check all events for snapshot in PersistAll" in { val pid = nextPid val snapshotProbe = TestProbe[Try[Done]] - val snapshotAtTwo = Behaviors.setup[Command](ctx ⇒ - counterWithSnapshotProbe(ctx, pid, snapshotProbe.ref).snapshotWhen { (s, _, _) ⇒ s.value == 2 } + val snapshotAtTwo = Behaviors.setup[Command](ctx => + counterWithSnapshotProbe(ctx, pid, snapshotProbe.ref).snapshotWhen { (s, _, _) => s.value == 2 } ) val c: ActorRef[Command] = spawn(snapshotAtTwo) val watchProbe = watcher(c) @@ -459,7 +459,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh watchProbe.expectMessage("Terminated") val probeC2 = TestProbe[(State, Event)]() - val c2 = spawn(Behaviors.setup[Command](ctx ⇒ counterWithProbe(ctx, pid, probeC2.ref))) + val c2 = spawn(Behaviors.setup[Command](ctx => counterWithProbe(ctx, pid, probeC2.ref))) // middle event triggered all to be snapshot probeC2.expectNoMessage() c2 ! GetValue(replyProbe.ref) @@ -468,7 +468,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "snapshot every N sequence nrs" in { val pid = nextPid - val c = spawn(Behaviors.setup[Command](ctx ⇒ counter(ctx, pid).snapshotEvery(2))) + val c = spawn(Behaviors.setup[Command](ctx => counter(ctx, pid).snapshotEvery(2))) val watchProbe = watcher(c) val replyProbe = TestProbe[State]() @@ -481,7 +481,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh // no snapshot should have happened val probeC2 = TestProbe[(State, Event)]() val snapshotProbe = TestProbe[Try[Done]]() - val c2 = spawn(Behaviors.setup[Command](ctx ⇒ + val c2 = spawn(Behaviors.setup[Command](ctx => counterWithProbe(ctx, pid, probeC2.ref, snapshotProbe.ref) .snapshotEvery(2)) ) @@ -493,7 +493,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh watchProbeC2.expectMessage("Terminated") val probeC3 = TestProbe[(State, Event)]() - val c3 = spawn(Behaviors.setup[Command](ctx ⇒ + val c3 = spawn(Behaviors.setup[Command](ctx => counterWithProbe(ctx, pid, probeC3.ref).snapshotEvery(2)) ) // this time it should have been snapshotted so no events to replay @@ -505,7 +505,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "snapshot every N sequence nrs when persisting multiple events" in { val pid = nextPid val snapshotProbe = TestProbe[Try[Done]]() - val c = spawn(Behaviors.setup[Command](ctx ⇒ + val c = spawn(Behaviors.setup[Command](ctx => counterWithSnapshotProbe(ctx, pid, snapshotProbe.ref).snapshotEvery(2)) ) val watchProbe = watcher(c) @@ -519,7 +519,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh watchProbe.expectMessage("Terminated") val probeC2 = TestProbe[(State, Event)]() - val c2 = spawn(Behaviors.setup[Command](ctx ⇒ + val c2 = spawn(Behaviors.setup[Command](ctx => counterWithProbe(ctx, pid, probeC2.ref).snapshotEvery(2)) ) probeC2.expectNoMessage() @@ -541,8 +541,8 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "tag events" in { val pid = nextPid - val c = spawn(Behaviors.setup[Command](ctx ⇒ - counter(ctx, pid).withTagger(_ ⇒ Set("tag1", "tag2"))) + val c = spawn(Behaviors.setup[Command](ctx => + counter(ctx, pid).withTagger(_ => Set("tag1", "tag2"))) ) val replyProbe = TestProbe[State]() @@ -556,7 +556,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "adapt events" in { val pid = nextPid - val c = spawn(Behaviors.setup[Command] { ctx ⇒ + val c = spawn(Behaviors.setup[Command] { ctx => val persistentBehavior = counter(ctx, pid) //#install-event-adapter @@ -572,7 +572,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh val events = queries.currentEventsByPersistenceId(pid.id).runWith(Sink.seq).futureValue events shouldEqual List(EventEnvelope(Sequence(1), pid.id, 1, Wrapper(Incremented(1)))) - val c2 = spawn(Behaviors.setup[Command](ctx ⇒ + val c2 = spawn(Behaviors.setup[Command](ctx => counter(ctx, pid).eventAdapter(new WrapperEventAdapter[Event]) )) c2 ! GetValue(replyProbe.ref) @@ -582,7 +582,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "adapter multiple events with persist all" in { val pid = nextPid - val c = spawn(Behaviors.setup[Command](ctx ⇒ + val c = spawn(Behaviors.setup[Command](ctx => counter(ctx, pid).eventAdapter(new WrapperEventAdapter[Event])) ) val replyProbe = TestProbe[State]() @@ -597,7 +597,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh EventEnvelope(Sequence(2), pid.id, 2, Wrapper(Incremented(1))) ) - val c2 = spawn(Behaviors.setup[Command](ctx ⇒ + val c2 = spawn(Behaviors.setup[Command](ctx => counter(ctx, pid).eventAdapter(new WrapperEventAdapter[Event]) )) c2 ! GetValue(replyProbe.ref) @@ -606,9 +606,9 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "adapt and tag events" in { val pid = nextPid - val c = spawn(Behaviors.setup[Command](ctx ⇒ + val c = spawn(Behaviors.setup[Command](ctx => counter(ctx, pid) - .withTagger(_ ⇒ Set("tag99")) + .withTagger(_ => Set("tag99")) .eventAdapter(new WrapperEventAdapter[Event])) ) val replyProbe = TestProbe[State]() @@ -620,7 +620,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh val events = queries.currentEventsByPersistenceId(pid.id).runWith(Sink.seq).futureValue events shouldEqual List(EventEnvelope(Sequence(1), pid.id, 1, Wrapper(Incremented(1)))) - val c2 = spawn(Behaviors.setup[Command](ctx ⇒ + val c2 = spawn(Behaviors.setup[Command](ctx => counter(ctx, pid).eventAdapter(new WrapperEventAdapter[Event])) ) c2 ! GetValue(replyProbe.ref) @@ -632,7 +632,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "handle scheduled message arriving before recovery completed " in { val c = spawn(Behaviors.withTimers[Command] { - timers ⇒ + timers => timers.startSingleTimer("tick", Increment, 1.millis) Thread.sleep(30) // now it's probably already in the mailbox, and will be stashed counter(nextPid) @@ -648,7 +648,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "handle scheduled message arriving after recovery completed " in { val c = spawn(Behaviors.withTimers[Command] { - timers ⇒ + timers => // probably arrives after recovery completed timers.startSingleTimer("tick", Increment, 200.millis) counter(nextPid) @@ -664,7 +664,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh "fail after recovery timeout" in { EventFilter.error(start = "Persistence failure when replaying snapshot", occurrences = 1).intercept { - val c = spawn(Behaviors.setup[Command](ctx ⇒ + val c = spawn(Behaviors.setup[Command](ctx => counter(ctx, nextPid) .withSnapshotPluginId("slow-snapshot-store") .withJournalPluginId("short-recovery-timeout")) @@ -682,7 +682,7 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh // put some events in there, so that recovering takes a little time val c = spawn(Behaviors.setup[Command](counter(_, pid))) - (0 to 50).foreach { _ ⇒ + (0 to 50).foreach { _ => c ! IncrementWithConfirmation(probe.ref) probe.expectMessage(Done) } @@ -699,11 +699,11 @@ class EventSourcedBehaviorSpec extends ScalaTestWithActorTestKit(EventSourcedBeh def watcher(toWatch: ActorRef[_]): TestProbe[String] = { val probe = TestProbe[String]() - val w = Behaviors.setup[Any] { (ctx) ⇒ + val w = Behaviors.setup[Any] { (ctx) => ctx.watch(toWatch) - Behaviors.receive[Any] { (_, _) ⇒ Behaviors.same } + Behaviors.receive[Any] { (_, _) => Behaviors.same } .receiveSignal { - case (_, _: Terminated) ⇒ + case (_, _: Terminated) => probe.ref ! "Terminated" Behaviors.stopped } diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorStashSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorStashSpec.scala index 6b5ae435f1..56cbbceb94 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorStashSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedBehaviorStashSpec.scala @@ -70,7 +70,7 @@ object EventSourcedBehaviorStashSpec { def counter(persistenceId: PersistenceId): Behavior[Command[_]] = Behaviors.supervise[Command[_]] { - Behaviors.setup(_ ⇒ eventSourcedCounter(persistenceId)) + Behaviors.setup(_ => eventSourcedCounter(persistenceId)) }.onFailure(SupervisorStrategy.restart.withLoggingEnabled(enabled = false)) def eventSourcedCounter( @@ -78,20 +78,20 @@ object EventSourcedBehaviorStashSpec { EventSourcedBehavior.withEnforcedReplies[Command[_], Event, State]( persistenceId, emptyState = State(0, active = true), - commandHandler = (state, command) ⇒ { + commandHandler = (state, command) => { if (state.active) active(state, command) else inactive(state, command) }, - eventHandler = (state, evt) ⇒ evt match { - case Incremented(delta) ⇒ + eventHandler = (state, evt) => evt match { + case Incremented(delta) => if (!state.active) throw new IllegalStateException State(state.value + delta, active = true) - case ValueUpdated(value) ⇒ + case ValueUpdated(value) => State(value, active = state.active) - case Activated ⇒ + case Activated => if (state.active) throw new IllegalStateException state.copy(active = true) - case Deactivated ⇒ + case Deactivated => if (!state.active) throw new IllegalStateException state.copy(active = false) }) @@ -101,30 +101,30 @@ object EventSourcedBehaviorStashSpec { private def active(state: State, command: Command[_]): ReplyEffect[Event, State] = { command match { - case cmd: Increment ⇒ + case cmd: Increment => Effect.persist(Incremented(1)) - .thenReply(cmd)(_ ⇒ Ack(cmd.id)) - case cmd @ UpdateValue(_, value, _) ⇒ + .thenReply(cmd)(_ => Ack(cmd.id)) + case cmd @ UpdateValue(_, value, _) => Effect.persist(ValueUpdated(value)) - .thenReply(cmd)(_ ⇒ Ack(cmd.id)) - case query: GetValue ⇒ + .thenReply(cmd)(_ => Ack(cmd.id)) + case query: GetValue => Effect.reply(query)(state) - case cmd: Deactivate ⇒ + case cmd: Deactivate => Effect.persist(Deactivated) - .thenReply(cmd)(_ ⇒ Ack(cmd.id)) - case cmd: Activate ⇒ + .thenReply(cmd)(_ => Ack(cmd.id)) + case cmd: Activate => // already active Effect.reply(cmd)(Ack(cmd.id)) - case _: Unhandled ⇒ + case _: Unhandled => Effect.unhandled.thenNoReply() - case Throw(id, t, replyTo) ⇒ + case Throw(id, t, replyTo) => replyTo ! Ack(id) throw t - case cmd: IncrementThenThrow ⇒ + case cmd: IncrementThenThrow => Effect.persist(Incremented(1)) - .thenRun((_: State) ⇒ throw cmd.t) + .thenRun((_: State) => throw cmd.t) .thenNoReply() - case cmd: Slow ⇒ + case cmd: Slow => cmd.latch.await(30, TimeUnit.SECONDS) Effect.reply(cmd)(Ack(cmd.id)) } @@ -132,28 +132,28 @@ object EventSourcedBehaviorStashSpec { private def inactive(state: State, command: Command[_]): ReplyEffect[Event, State] = { command match { - case _: Increment ⇒ + case _: Increment => Effect.stash() - case cmd @ UpdateValue(_, value, _) ⇒ + case cmd @ UpdateValue(_, value, _) => Effect.persist(ValueUpdated(value)) - .thenReply(cmd)(_ ⇒ Ack(cmd.id)) - case query: GetValue ⇒ + .thenReply(cmd)(_ => Ack(cmd.id)) + case query: GetValue => Effect.reply(query)(state) - case cmd: Deactivate ⇒ + case cmd: Deactivate => // already inactive Effect.reply(cmd)(Ack(cmd.id)) - case cmd: Activate ⇒ + case cmd: Activate => Effect.persist(Activated) .thenUnstashAll() - .thenReply(cmd)(_ ⇒ Ack(cmd.id)) - case _: Unhandled ⇒ + .thenReply(cmd)(_ => Ack(cmd.id)) + case _: Unhandled => Effect.unhandled.thenNoReply() - case Throw(id, t, replyTo) ⇒ + case Throw(id, t, replyTo) => replyTo ! Ack(id) throw t - case _: IncrementThenThrow ⇒ + case _: IncrementThenThrow => Effect.stash() - case _: Slow ⇒ + case _: Slow => Effect.stash() } } @@ -270,15 +270,15 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc val stateProbe = TestProbe[State] val notUsedProbe = TestProbe[NotUsed] - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => c ! Increment(s"inc-1-$n", ackProbe.ref) } - (1 to 3).foreach { n ⇒ + (1 to 3).foreach { n => c ! Deactivate(s"deact-2-$n", ackProbe.ref) } - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => if (n % 10 == 0) c ! Unhandled(notUsedProbe.ref) c ! Increment(s"inc-3-$n", ackProbe.ref) @@ -286,33 +286,33 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc c ! GetValue(stateProbe.ref) - (1 to 5).foreach { n ⇒ + (1 to 5).foreach { n => c ! UpdateValue(s"upd-4-$n", n * 1000, ackProbe.ref) } - (1 to 3).foreach { n ⇒ + (1 to 3).foreach { n => c ! Activate(s"act-5-$n", ackProbe.ref) } - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => c ! Increment(s"inc-6-$n", ackProbe.ref) } c ! GetValue(stateProbe.ref) - (6 to 8).foreach { n ⇒ + (6 to 8).foreach { n => c ! UpdateValue(s"upd-7-$n", n * 1000, ackProbe.ref) } - (1 to 3).foreach { n ⇒ + (1 to 3).foreach { n => c ! Deactivate(s"deact-8-$n", ackProbe.ref) } - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => c ! Increment(s"inc-9-$n", ackProbe.ref) } - (1 to 3).foreach { n ⇒ + (1 to 3).foreach { n => c ! Activate(s"act-10-$n", ackProbe.ref) } @@ -323,47 +323,47 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc // verify the order - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => ackProbe.expectMessage(Ack(s"inc-1-$n")) } - (1 to 3).foreach { n ⇒ + (1 to 3).foreach { n => ackProbe.expectMessage(Ack(s"deact-2-$n")) } - (1 to 5).foreach { n ⇒ + (1 to 5).foreach { n => ackProbe.expectMessage(Ack(s"upd-4-$n")) } ackProbe.expectMessage(Ack("act-5-1")) - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => ackProbe.expectMessage(Ack(s"inc-3-$n")) } - (2 to 3).foreach { n ⇒ + (2 to 3).foreach { n => ackProbe.expectMessage(Ack(s"act-5-$n")) } - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => ackProbe.expectMessage(Ack(s"inc-6-$n")) } - (6 to 8).foreach { n ⇒ + (6 to 8).foreach { n => ackProbe.expectMessage(Ack(s"upd-7-$n")) } - (1 to 3).foreach { n ⇒ + (1 to 3).foreach { n => ackProbe.expectMessage(Ack(s"deact-8-$n")) } ackProbe.expectMessage(Ack("act-10-1")) - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => ackProbe.expectMessage(Ack(s"inc-9-$n")) } - (2 to 3).foreach { n ⇒ + (2 to 3).foreach { n => ackProbe.expectMessage(Ack(s"act-10-$n")) } @@ -416,7 +416,7 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc // make first command slow to ensure that all subsequent commands are enqueued first c ! Slow("slow", latch, ackProbe.ref) - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => if (n == 3) c ! IncrementThenThrow(s"inc-$n", new TestException("test"), ackProbe.ref) else @@ -442,11 +442,11 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc val ackProbe = TestProbe[Ack] val stateProbe = TestProbe[State] - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => c ! Increment(s"inc-$n", ackProbe.ref) } - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => if (n != 5) ackProbe.expectMessage(Ack(s"inc-$n")) } @@ -494,39 +494,39 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc val behavior = EventSourcedBehavior[String, String, Boolean]( PersistenceId("stash-is-full-drop"), emptyState = false, - commandHandler = { (state, command) ⇒ + commandHandler = { (state, command) => state match { - case false ⇒ + case false => command match { - case "ping" ⇒ + case "ping" => probe.ref ! "pong" Effect.none - case "start-stashing" ⇒ + case "start-stashing" => Effect.persist("start-stashing") - case msg ⇒ + case msg => probe.ref ! msg Effect.none } - case true ⇒ + case true => command match { - case "unstash" ⇒ + case "unstash" => Effect.persist("unstash") .thenUnstashAll() // FIXME this is run before unstash, so not sequentially as the docs say // https://github.com/akka/akka/issues/26489 - .thenRun(_ ⇒ + .thenRun(_ => probe.ref ! "done-unstashing" ) - case _ ⇒ + case _ => Effect.stash() } } }, { - case (_, "start-stashing") ⇒ true - case (_, "unstash") ⇒ false - case (_, _) ⇒ throw new IllegalArgumentException() + case (_, "start-stashing") => true + case (_, "unstash") => false + case (_, _) => throw new IllegalArgumentException() } ) @@ -540,7 +540,7 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc val limit = system.settings.config.getInt("akka.persistence.typed.stash-capacity") EventFilter.warning(start = "Stash buffer is full, dropping message").intercept { - (0 to limit).foreach { n ⇒ + (0 to limit).foreach { n => c ! s"cmd-$n" // limit triggers overflow } probe.expectMessageType[Dropped] @@ -549,7 +549,7 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc // we can still unstash and continue interacting c ! "unstash" probe.expectMessage("done-unstashing") // before actually unstashing, see above - (0 to (limit - 1)).foreach { n ⇒ + (0 to (limit - 1)).foreach { n => probe.expectMessage(s"cmd-$n") } @@ -569,13 +569,13 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc PersistenceId("stash-is-full-fail"), "", commandHandler = { - case (_, "ping") ⇒ + case (_, "ping") => probe.ref ! "pong" Effect.none - case (_, _) ⇒ + case (_, _) => Effect.stash() }, - (state, _) ⇒ state + (state, _) => state ) val c = failStashTestKit.spawn(behavior) @@ -586,7 +586,7 @@ class EventSourcedBehaviorStashSpec extends ScalaTestWithActorTestKit(EventSourc EventFilter[StashOverflowException](occurrences = 1).intercept { val limit = system.settings.config.getInt("akka.persistence.typed.stash-capacity") - (0 to limit).foreach { n ⇒ + (0 to limit).foreach { n => c ! s"cmd-$n" // limit triggers overflow } probe.expectTerminated(c, 10.seconds) diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedSequenceNumberSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedSequenceNumberSpec.scala index 50fb5afac3..2595a76ae1 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedSequenceNumberSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/EventSourcedSequenceNumberSpec.scala @@ -23,21 +23,21 @@ object EventSourcedSequenceNumberSpec { class EventSourcedSequenceNumberSpec extends ScalaTestWithActorTestKit(EventSourcedSequenceNumberSpec.conf) with WordSpecLike { private def behavior(pid: PersistenceId, probe: ActorRef[String]): Behavior[String] = - Behaviors.setup(ctx ⇒ + Behaviors.setup(ctx => EventSourcedBehavior[String, String, String]( pid, "", - { (_, command) ⇒ + { (_, command) => probe ! (EventSourcedBehavior.lastSequenceNumber(ctx) + " onCommand") - Effect.persist(command).thenRun(_ ⇒ + Effect.persist(command).thenRun(_ => probe ! (EventSourcedBehavior.lastSequenceNumber(ctx) + " thenRun") ) }, - { (state, evt) ⇒ + { (state, evt) => probe ! (EventSourcedBehavior.lastSequenceNumber(ctx) + " eventHandler") state + evt } - ).onRecoveryCompleted(_ ⇒ + ).onRecoveryCompleted(_ => probe ! (EventSourcedBehavior.lastSequenceNumber(ctx) + " onRecoveryComplete") ) ) diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/NullEmptyStateSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/NullEmptyStateSpec.scala index 9da26fffc0..41fec801b5 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/NullEmptyStateSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/NullEmptyStateSpec.scala @@ -28,17 +28,17 @@ class NullEmptyStateSpec extends ScalaTestWithActorTestKit(NullEmptyStateSpec.co EventSourcedBehavior[String, String, String]( persistenceId, emptyState = null, - commandHandler = (_, command) ⇒ { + commandHandler = (_, command) => { if (command == "stop") Effect.stop() else Effect.persist(command) }, - eventHandler = (state, event) ⇒ { + eventHandler = (state, event) => { probe.tell("eventHandler:" + state + ":" + event) if (state == null) event else state + event } - ).onRecoveryCompleted { s ⇒ + ).onRecoveryCompleted { s => probe.tell("onRecoveryCompleted:" + s) } diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/OptionalSnapshotStoreSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/OptionalSnapshotStoreSpec.scala index eea5397edc..886ca5d3f0 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/OptionalSnapshotStoreSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/OptionalSnapshotStoreSpec.scala @@ -31,12 +31,12 @@ object OptionalSnapshotStoreSpec { persistenceId = PersistenceId(name), emptyState = State(), commandHandler = CommandHandler.command { - _ ⇒ Effect.persist(Event()).thenRun(probe.ref ! _) + _ => Effect.persist(Event()).thenRun(probe.ref ! _) }, eventHandler = { - case (_, _) ⇒ State() + case (_, _) => State() } - ).snapshotWhen { case _ ⇒ true } + ).snapshotWhen { case _ => true } def persistentBehaviorWithSnapshotPlugin(probe: TestProbe[State]) = persistentBehavior(probe).withSnapshotPluginId("akka.persistence.snapshot-store.local") diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PerformanceSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PerformanceSpec.scala index 3bfe43fe0d..8691d0020d 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PerformanceSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PerformanceSpec.scala @@ -67,21 +67,21 @@ object PerformanceSpec { def failureWasDefined: Boolean = failAt != -1L } - def behavior(name: String, probe: TestProbe[Reply])(other: (Command, Parameters) ⇒ Effect[String, String]) = { + def behavior(name: String, probe: TestProbe[Reply])(other: (Command, Parameters) => Effect[String, String]) = { Behaviors.supervise({ val parameters = Parameters() EventSourcedBehavior[Command, String, String]( persistenceId = PersistenceId(name), "", commandHandler = CommandHandler.command { - case StopMeasure ⇒ Effect.none.thenRun(_ ⇒ probe.ref ! StopMeasure) - case FailAt(sequence) ⇒ Effect.none.thenRun(_ ⇒ parameters.failAt = sequence) - case command ⇒ other(command, parameters) + case StopMeasure => Effect.none.thenRun(_ => probe.ref ! StopMeasure) + case FailAt(sequence) => Effect.none.thenRun(_ => parameters.failAt = sequence) + case command => other(command, parameters) }, eventHandler = { - case (state, _) ⇒ state + case (state, _) => state } - ).onRecoveryCompleted { _ ⇒ + ).onRecoveryCompleted { _ => if (parameters.every(1000)) print("r") } }).onFailure(SupervisorStrategy.restart) @@ -89,8 +89,8 @@ object PerformanceSpec { def eventSourcedTestPersistenceBehavior(name: String, probe: TestProbe[Reply]) = behavior(name, probe) { - case (CommandWithEvent(evt), parameters) ⇒ - Effect.persist(evt).thenRun(_ ⇒ { + case (CommandWithEvent(evt), parameters) => + Effect.persist(evt).thenRun(_ => { parameters.persistCalls += 1 if (parameters.every(1000)) print(".") if (parameters.shouldFail) { @@ -98,7 +98,7 @@ object PerformanceSpec { throw TestException("boom") } }) - case _ ⇒ Effect.none + case _ => Effect.none } } @@ -124,7 +124,7 @@ class PerformanceSpec extends ScalaTestWithActorTestKit(ConfigFactory.parseStrin val m = new Measure(loadCycles) m.startMeasure() val parameters = Parameters(0, failAt = failAt.getOrElse(-1)) - (1 to loadCycles).foreach { n ⇒ + (1 to loadCycles).foreach { n => parameters.persistCalls += 1 persistentActor ! CommandWithEvent(s"msg$n") // stash is cleared when exception is thrown so have to wait before sending more commands diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PersistentActorCompileOnlyTest.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PersistentActorCompileOnlyTest.scala index 54880a3e52..ff6d8b51a7 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PersistentActorCompileOnlyTest.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PersistentActorCompileOnlyTest.scala @@ -35,15 +35,15 @@ object PersistentActorCompileOnlyTest { emptyState = ExampleState(Nil), commandHandler = CommandHandler.command { - case Cmd(data, sender) ⇒ + case Cmd(data, sender) => Effect.persist(Evt(data)) - .thenRun { _ ⇒ + .thenRun { _ => sender ! Ack } }, eventHandler = { - case (state, Evt(data)) ⇒ state.copy(data :: state.events) + case (state, Evt(data)) => state.copy(data :: state.events) }) } @@ -71,35 +71,35 @@ object PersistentActorCompileOnlyTest { val response: Future[RecoveryComplete.Response] = sideEffectProcessor.ask(Request(correlationId, data, _)) - response.map(response ⇒ AcknowledgeSideEffect(response.correlationId)) + response.map(response => AcknowledgeSideEffect(response.correlationId)) .foreach(sender ! _) } - val behavior: Behavior[Command] = Behaviors.setup(ctx ⇒ + val behavior: Behavior[Command] = Behaviors.setup(ctx => EventSourcedBehavior[Command, Event, EventsInFlight]( persistenceId = PersistenceId("recovery-complete-id"), emptyState = EventsInFlight(0, Map.empty), - commandHandler = (state, cmd) ⇒ cmd match { - case DoSideEffect(data) ⇒ - Effect.persist(IntentRecorded(state.nextCorrelationId, data)).thenRun { _ ⇒ + commandHandler = (state, cmd) => cmd match { + case DoSideEffect(data) => + Effect.persist(IntentRecorded(state.nextCorrelationId, data)).thenRun { _ => performSideEffect(ctx.self, state.nextCorrelationId, data) } - case AcknowledgeSideEffect(correlationId) ⇒ + case AcknowledgeSideEffect(correlationId) => Effect.persist(SideEffectAcknowledged(correlationId)) }, - eventHandler = (state, evt) ⇒ evt match { - case IntentRecorded(correlationId, data) ⇒ + eventHandler = (state, evt) => evt match { + case IntentRecorded(correlationId, data) => EventsInFlight( nextCorrelationId = correlationId + 1, - dataByCorrelationId = state.dataByCorrelationId + (correlationId → data)) - case SideEffectAcknowledged(correlationId) ⇒ + dataByCorrelationId = state.dataByCorrelationId + (correlationId -> data)) + case SideEffectAcknowledged(correlationId) => state.copy(dataByCorrelationId = state.dataByCorrelationId - correlationId) - }).onRecoveryCompleted(state ⇒ + }).onRecoveryCompleted(state => state.dataByCorrelationId.foreach { - case (correlationId, data) ⇒ performSideEffect(ctx.self, correlationId, data) + case (correlationId, data) => performSideEffect(ctx.self, correlationId, data) } ) ) @@ -121,27 +121,27 @@ object PersistentActorCompileOnlyTest { val b: Behavior[Command] = EventSourcedBehavior[Command, Event, Mood]( persistenceId = PersistenceId("myPersistenceId"), emptyState = Happy, - commandHandler = { (state, command) ⇒ + commandHandler = { (state, command) => state match { - case Happy ⇒ command match { - case Greet(whom) ⇒ + case Happy => command match { + case Greet(whom) => println(s"Super happy to meet you $whom!") Effect.none - case MoodSwing ⇒ Effect.persist(MoodChanged(Sad)) + case MoodSwing => Effect.persist(MoodChanged(Sad)) } - case Sad ⇒ command match { - case Greet(whom) ⇒ + case Sad => command match { + case Greet(whom) => println(s"hi $whom") Effect.none - case MoodSwing ⇒ Effect.persist(MoodChanged(Happy)) + case MoodSwing => Effect.persist(MoodChanged(Happy)) } } }, eventHandler = { - case (_, MoodChanged(to)) ⇒ to + case (_, MoodChanged(to)) => to }) - Behaviors.withTimers((timers: TimerScheduler[Command]) ⇒ { + Behaviors.withTimers((timers: TimerScheduler[Command]) => { timers.startPeriodicTimer("swing", MoodSwing, 10.seconds) b }) @@ -164,13 +164,13 @@ object PersistentActorCompileOnlyTest { persistenceId = PersistenceId("asdf"), emptyState = State(Nil), commandHandler = CommandHandler.command { - case RegisterTask(task) ⇒ Effect.persist(TaskRegistered(task)) - case TaskDone(task) ⇒ Effect.persist(TaskRemoved(task)) + case RegisterTask(task) => Effect.persist(TaskRegistered(task)) + case TaskDone(task) => Effect.persist(TaskRemoved(task)) }, - eventHandler = (state, evt) ⇒ evt match { - case TaskRegistered(task) ⇒ State(task :: state.tasksInFlight) - case TaskRemoved(task) ⇒ State(state.tasksInFlight.filter(_ != task)) - }).snapshotWhen { (state, e, seqNr) ⇒ state.tasksInFlight.isEmpty } + eventHandler = (state, evt) => evt match { + case TaskRegistered(task) => State(task :: state.tasksInFlight) + case TaskRemoved(task) => State(state.tasksInFlight.filter(_ != task)) + }).snapshotWhen { (state, e, seqNr) => state.tasksInFlight.isEmpty } } object SpawnChild { @@ -187,23 +187,23 @@ object PersistentActorCompileOnlyTest { def worker(task: Task): Behavior[Nothing] = ??? - val behavior: Behavior[Command] = Behaviors.setup(ctx ⇒ + val behavior: Behavior[Command] = Behaviors.setup(ctx => EventSourcedBehavior[Command, Event, State]( persistenceId = PersistenceId("asdf"), emptyState = State(Nil), - commandHandler = (_, cmd) ⇒ cmd match { - case RegisterTask(task) ⇒ + commandHandler = (_, cmd) => cmd match { + case RegisterTask(task) => Effect.persist(TaskRegistered(task)) - .thenRun { _ ⇒ + .thenRun { _ => val child = ctx.spawn[Nothing](worker(task), task) // This assumes *any* termination of the child may trigger a `TaskDone`: ctx.watchWith(child, TaskDone(task)) } - case TaskDone(task) ⇒ Effect.persist(TaskRemoved(task)) + case TaskDone(task) => Effect.persist(TaskRemoved(task)) }, - eventHandler = (state, evt) ⇒ evt match { - case TaskRegistered(task) ⇒ State(task :: state.tasksInFlight) - case TaskRemoved(task) ⇒ State(state.tasksInFlight.filter(_ != task)) + eventHandler = (state, evt) => evt match { + case TaskRegistered(task) => State(task :: state.tasksInFlight) + case TaskRemoved(task) => State(state.tasksInFlight.filter(_ != task)) }) ) @@ -241,52 +241,52 @@ object PersistentActorCompileOnlyTest { def isFullyHydrated(basket: Basket, ids: List[Id]) = basket.items.map(_.id) == ids - val behavior: Behavior[Command] = Behaviors.setup { ctx ⇒ + val behavior: Behavior[Command] = Behaviors.setup { ctx => var basket = Basket(Nil) var stash: Seq[Command] = Nil - val adapt = ctx.messageAdapter((m: MetaData) ⇒ GotMetaData(m)) + val adapt = ctx.messageAdapter((m: MetaData) => GotMetaData(m)) def addItem(id: Id, self: ActorRef[Command]) = Effect .persist[Event, List[Id]](ItemAdded(id)) - .thenRun(_ ⇒ metadataRegistry ! GetMetaData(id, adapt)) + .thenRun(_ => metadataRegistry ! GetMetaData(id, adapt)) EventSourcedBehavior[Command, Event, List[Id]]( persistenceId = PersistenceId("basket-1"), emptyState = Nil, - commandHandler = { (state, cmd) ⇒ + commandHandler = { (state, cmd) => if (isFullyHydrated(basket, state)) cmd match { - case AddItem(id) ⇒ addItem(id, ctx.self) - case RemoveItem(id) ⇒ Effect.persist(ItemRemoved(id)) - case GotMetaData(data) ⇒ + case AddItem(id) => addItem(id, ctx.self) + case RemoveItem(id) => Effect.persist(ItemRemoved(id)) + case GotMetaData(data) => basket = basket.updatedWith(data) Effect.none - case GetTotalPrice(sender) ⇒ + case GetTotalPrice(sender) => sender ! basket.items.map(_.price).sum Effect.none } else cmd match { - case AddItem(id) ⇒ addItem(id, ctx.self) - case RemoveItem(id) ⇒ Effect.persist(ItemRemoved(id)) - case GotMetaData(data) ⇒ + case AddItem(id) => addItem(id, ctx.self) + case RemoveItem(id) => Effect.persist(ItemRemoved(id)) + case GotMetaData(data) => basket = basket.updatedWith(data) if (isFullyHydrated(basket, state)) { stash.foreach(ctx.self ! _) stash = Nil } Effect.none - case cmd: GetTotalPrice ⇒ + case cmd: GetTotalPrice => stash :+= cmd Effect.none } }, - eventHandler = (state, evt) ⇒ evt match { - case ItemAdded(id) ⇒ id +: state - case ItemRemoved(id) ⇒ state.filter(_ != id) - }).onRecoveryCompleted(state ⇒ - state.foreach(id ⇒ metadataRegistry ! GetMetaData(id, adapt)) + eventHandler = (state, evt) => evt match { + case ItemAdded(id) => id +: state + case ItemRemoved(id) => state.filter(_ != id) + }).onRecoveryCompleted(state => + state.foreach(id => metadataRegistry ! GetMetaData(id, adapt)) ) } } @@ -313,23 +313,23 @@ object PersistentActorCompileOnlyTest { //#commonChainedEffects // Example factoring out a chained effect rather than using `andThen` - val commonChainedEffects = SideEffect[Mood](_ ⇒ println("Command processed")) + val commonChainedEffects = SideEffect[Mood](_ => println("Command processed")) // Then in a command handler: Effect.persist(Remembered("Yep")) // persist event .andThen(commonChainedEffects) // add on common chained effect //#commonChainedEffects - val commandHandler: CommandHandler[Command, Event, Mood] = { (state, cmd) ⇒ + val commandHandler: CommandHandler[Command, Event, Mood] = { (state, cmd) => cmd match { - case Greet(whom) ⇒ + case Greet(whom) => println(s"Hi there, I'm $state!") Effect.none - case CheerUp(sender) ⇒ + case CheerUp(sender) => changeMoodIfNeeded(state, Happy) - .thenRun { _ ⇒ + .thenRun { _ => sender ! Ack }.andThen(commonChainedEffects) - case Remember(memory) ⇒ + case Remember(memory) => // A more elaborate example to show we still have full control over the effects // if needed (e.g. when some logic is factored out but you want to add more effects) val commonEffects: Effect[Event, Mood] = changeMoodIfNeeded(state, Happy) @@ -339,8 +339,8 @@ object PersistentActorCompileOnlyTest { } private val eventHandler: EventHandler[Mood, Event] = { - case (_, MoodChanged(to)) ⇒ to - case (state, Remembered(_)) ⇒ state + case (_, MoodChanged(to)) => to + case (state, Remembered(_)) => state } EventSourcedBehavior[Command, Event, Mood]( @@ -361,14 +361,14 @@ object PersistentActorCompileOnlyTest { class State private val commandHandler: CommandHandler[Command, Event, State] = CommandHandler.command { - case Enough ⇒ + case Enough => Effect.persist(Done) - .thenRun((_: State) ⇒ println("yay")) + .thenRun((_: State) => println("yay")) .thenStop } - private val eventHandler: (State, Event) ⇒ State = { - case (state, Done) ⇒ state + private val eventHandler: (State, Event) => State = { + case (state, Done) => state } EventSourcedBehavior[Command, Event, State]( @@ -387,15 +387,15 @@ object PersistentActorCompileOnlyTest { persistenceId = PersistenceId("myPersistenceId"), emptyState = new First, commandHandler = CommandHandler.command { - cmd ⇒ + cmd => Effect.persist(cmd).thenRun { - case _: First ⇒ println("first") - case _: Second ⇒ println("second") + case _: First => println("first") + case _: Second => println("second") } }, eventHandler = { - case (_: First, _) ⇒ new Second - case (state, _) ⇒ state + case (_: First, _) => new Second + case (state, _) => state }) } diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PrimitiveStateSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PrimitiveStateSpec.scala index a1ae0469ba..ba916b64c8 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PrimitiveStateSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/PrimitiveStateSpec.scala @@ -28,17 +28,17 @@ class PrimitiveStateSpec extends ScalaTestWithActorTestKit(PrimitiveStateSpec.co EventSourcedBehavior[Int, Int, Int]( persistenceId, emptyState = 0, - commandHandler = (_, command) ⇒ { + commandHandler = (_, command) => { if (command < 0) Effect.stop() else Effect.persist(command) }, - eventHandler = (state, event) ⇒ { + eventHandler = (state, event) => { probe.tell("eventHandler:" + state + ":" + event) state + event } - ).onRecoveryCompleted { n ⇒ + ).onRecoveryCompleted { n => probe.tell("onRecoveryCompleted:" + n) } diff --git a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/SnapshotMutableStateSpec.scala b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/SnapshotMutableStateSpec.scala index 7033ddda3e..da8beb3c63 100644 --- a/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/SnapshotMutableStateSpec.scala +++ b/akka-persistence-typed/src/test/scala/akka/persistence/typed/scaladsl/SnapshotMutableStateSpec.scala @@ -31,7 +31,7 @@ object SnapshotMutableStateSpec { def loadAsync(persistenceId: String, criteria: SnapshotSelectionCriteria): Future[Option[SelectedSnapshot]] = { Future.successful(state.get(persistenceId).map { - case (snap, meta) ⇒ SelectedSnapshot(meta, snap) + case (snap, meta) => SelectedSnapshot(meta, snap) }) } @@ -79,22 +79,22 @@ object SnapshotMutableStateSpec { EventSourcedBehavior[Command, Event, MutableState]( persistenceId, emptyState = new MutableState(0), - commandHandler = (state, cmd) ⇒ cmd match { - case Increment ⇒ + commandHandler = (state, cmd) => cmd match { + case Increment => Effect.persist(Incremented) - case GetValue(replyTo) ⇒ + case GetValue(replyTo) => replyTo ! state.value Effect.none }, - eventHandler = (state, evt) ⇒ evt match { - case Incremented ⇒ + eventHandler = (state, evt) => evt match { + case Incremented => state.value += 1 probe ! s"incremented-${state.value}" state }).onSnapshot { - case (meta, Success(_)) ⇒ probe ! s"snapshot-success-${meta.sequenceNr}" - case (meta, Failure(_)) ⇒ probe ! s"snapshot-failure-${meta.sequenceNr}" + case (meta, Success(_)) => probe ! s"snapshot-success-${meta.sequenceNr}" + case (meta, Failure(_)) => probe ! s"snapshot-failure-${meta.sequenceNr}" } } @@ -113,10 +113,10 @@ class SnapshotMutableStateSpec extends ScalaTestWithActorTestKit(SnapshotMutable val pid = nextPid() val probe = TestProbe[String]() def snapshotState3: Behavior[Command] = - counter(pid, probe.ref).snapshotWhen { (state, _, _) ⇒ state.value == 3 } + counter(pid, probe.ref).snapshotWhen { (state, _, _) => state.value == 3 } val c = spawn(snapshotState3) - (1 to 5).foreach { n ⇒ + (1 to 5).foreach { n => c ! Increment probe.expectMessage(s"incremented-$n") if (n == 3) { diff --git a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithCommandHandlersInState.scala b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithCommandHandlersInState.scala index cbe16779ed..71898351a9 100644 --- a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithCommandHandlersInState.scala +++ b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithCommandHandlersInState.scala @@ -62,18 +62,18 @@ object AccountExampleWithCommandHandlersInState { case object EmptyAccount extends Account { override def applyCommand(cmd: AccountCommand[_]): ReplyEffect = cmd match { - case c: CreateAccount ⇒ + case c: CreateAccount => Effect.persist(AccountCreated) - .thenReply(c)(_ ⇒ Confirmed) - case _ ⇒ + .thenReply(c)(_ => Confirmed) + case _ => // CreateAccount before handling any other commands Effect.unhandled.thenNoReply() } override def applyEvent(event: AccountEvent): Account = event match { - case AccountCreated ⇒ OpenedAccount(Zero) - case _ ⇒ throw new IllegalStateException(s"unexpected event [$event] in state [EmptyAccount]") + case AccountCreated => OpenedAccount(Zero) + case _ => throw new IllegalStateException(s"unexpected event [$event] in state [EmptyAccount]") } } case class OpenedAccount(balance: BigDecimal) extends Account { @@ -81,40 +81,40 @@ object AccountExampleWithCommandHandlersInState { override def applyCommand(cmd: AccountCommand[_]): ReplyEffect = cmd match { - case c @ Deposit(amount) ⇒ + case c @ Deposit(amount) => Effect.persist(Deposited(amount)) - .thenReply(c)(_ ⇒ Confirmed) + .thenReply(c)(_ => Confirmed) - case c @ Withdraw(amount) ⇒ + case c @ Withdraw(amount) => if (canWithdraw(amount)) { Effect.persist(Withdrawn(amount)) - .thenReply(c)(_ ⇒ Confirmed) + .thenReply(c)(_ => Confirmed) } else { Effect.reply(c)(Rejected(s"Insufficient balance $balance to be able to withdraw $amount")) } - case c: GetBalance ⇒ + case c: GetBalance => Effect.reply(c)(CurrentBalance(balance)) - case c: CloseAccount ⇒ + case c: CloseAccount => if (balance == Zero) Effect.persist(AccountClosed) - .thenReply(c)(_ ⇒ Confirmed) + .thenReply(c)(_ => Confirmed) else Effect.reply(c)(Rejected("Can't close account with non-zero balance")) - case c: CreateAccount ⇒ + case c: CreateAccount => Effect.reply(c)(Rejected("Account is already created")) } override def applyEvent(event: AccountEvent): Account = event match { - case Deposited(amount) ⇒ copy(balance = balance + amount) - case Withdrawn(amount) ⇒ copy(balance = balance - amount) - case AccountClosed ⇒ ClosedAccount - case AccountCreated ⇒ throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") + case Deposited(amount) => copy(balance = balance + amount) + case Withdrawn(amount) => copy(balance = balance - amount) + case AccountClosed => ClosedAccount + case AccountCreated => throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") } def canWithdraw(amount: BigDecimal): Boolean = { @@ -125,13 +125,13 @@ object AccountExampleWithCommandHandlersInState { case object ClosedAccount extends Account { override def applyCommand(cmd: AccountCommand[_]): ReplyEffect = cmd match { - case c @ (_: Deposit | _: Withdraw) ⇒ + case c @ (_: Deposit | _: Withdraw) => Effect.reply(c)(Rejected("Account is closed")) - case c: GetBalance ⇒ + case c: GetBalance => Effect.reply(c)(CurrentBalance(Zero)) - case c: CloseAccount ⇒ + case c: CloseAccount => Effect.reply(c)(Rejected("Account is already closed")) - case c: CreateAccount ⇒ + case c: CreateAccount => Effect.reply(c)(Rejected("Account is already created")) } @@ -143,8 +143,8 @@ object AccountExampleWithCommandHandlersInState { EventSourcedBehavior.withEnforcedReplies[AccountCommand[AccountCommandReply], AccountEvent, Account]( PersistenceId(s"Account|$accountNumber"), EmptyAccount, - (state, cmd) ⇒ state.applyCommand(cmd), - (state, event) ⇒ state.applyEvent(event) + (state, cmd) => state.applyCommand(cmd), + (state, event) => state.applyEvent(event) ) } diff --git a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithEventHandlersInState.scala b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithEventHandlersInState.scala index bbb171c846..314c38b841 100644 --- a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithEventHandlersInState.scala +++ b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithEventHandlersInState.scala @@ -65,8 +65,8 @@ object AccountExampleWithEventHandlersInState { } case object EmptyAccount extends Account { override def applyEvent(event: AccountEvent): Account = event match { - case AccountCreated ⇒ OpenedAccount(Zero) - case _ ⇒ throw new IllegalStateException(s"unexpected event [$event] in state [EmptyAccount]") + case AccountCreated => OpenedAccount(Zero) + case _ => throw new IllegalStateException(s"unexpected event [$event] in state [EmptyAccount]") } } case class OpenedAccount(balance: BigDecimal) extends Account { @@ -74,10 +74,10 @@ object AccountExampleWithEventHandlersInState { override def applyEvent(event: AccountEvent): Account = event match { - case Deposited(amount) ⇒ copy(balance = balance + amount) - case Withdrawn(amount) ⇒ copy(balance = balance - amount) - case AccountClosed ⇒ ClosedAccount - case AccountCreated ⇒ throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") + case Deposited(amount) => copy(balance = balance + amount) + case Withdrawn(amount) => copy(balance = balance - amount) + case AccountClosed => ClosedAccount + case AccountCreated => throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") } def canWithdraw(amount: BigDecimal): Boolean = { @@ -105,55 +105,55 @@ object AccountExampleWithEventHandlersInState { } //#withEnforcedReplies - private val commandHandler: (Account, AccountCommand[_]) ⇒ ReplyEffect[AccountEvent, Account] = { - (state, cmd) ⇒ + private val commandHandler: (Account, AccountCommand[_]) => ReplyEffect[AccountEvent, Account] = { + (state, cmd) => state match { - case EmptyAccount ⇒ cmd match { - case c: CreateAccount ⇒ createAccount(c) - case _ ⇒ Effect.unhandled.thenNoReply() // CreateAccount before handling any other commands + case EmptyAccount => cmd match { + case c: CreateAccount => createAccount(c) + case _ => Effect.unhandled.thenNoReply() // CreateAccount before handling any other commands } - case acc @ OpenedAccount(_) ⇒ cmd match { - case c: Deposit ⇒ deposit(c) - case c: Withdraw ⇒ withdraw(acc, c) - case c: GetBalance ⇒ getBalance(acc, c) - case c: CloseAccount ⇒ closeAccount(acc, c) - case c: CreateAccount ⇒ Effect.reply(c)(Rejected("Account is already created")) + case acc @ OpenedAccount(_) => cmd match { + case c: Deposit => deposit(c) + case c: Withdraw => withdraw(acc, c) + case c: GetBalance => getBalance(acc, c) + case c: CloseAccount => closeAccount(acc, c) + case c: CreateAccount => Effect.reply(c)(Rejected("Account is already created")) } - case ClosedAccount ⇒ + case ClosedAccount => cmd match { - case c @ (_: Deposit | _: Withdraw) ⇒ + case c @ (_: Deposit | _: Withdraw) => Effect.reply(c)(Rejected("Account is closed")) - case c: GetBalance ⇒ + case c: GetBalance => Effect.reply(c)(CurrentBalance(Zero)) - case c: CloseAccount ⇒ + case c: CloseAccount => Effect.reply(c)(Rejected("Account is already closed")) - case c: CreateAccount ⇒ + case c: CreateAccount => Effect.reply(c)(Rejected("Account is already created")) } } } - private val eventHandler: (Account, AccountEvent) ⇒ Account = { - (state, event) ⇒ state.applyEvent(event) + private val eventHandler: (Account, AccountEvent) => Account = { + (state, event) => state.applyEvent(event) } private def createAccount(cmd: CreateAccount): ReplyEffect[AccountEvent, Account] = { Effect.persist(AccountCreated) - .thenReply(cmd)(_ ⇒ Confirmed) + .thenReply(cmd)(_ => Confirmed) } private def deposit(cmd: Deposit): ReplyEffect[AccountEvent, Account] = { Effect.persist(Deposited(cmd.amount)) - .thenReply(cmd)(_ ⇒ Confirmed) + .thenReply(cmd)(_ => Confirmed) } //#reply private def withdraw(acc: OpenedAccount, cmd: Withdraw): ReplyEffect[AccountEvent, Account] = { if (acc.canWithdraw(cmd.amount)) { Effect.persist(Withdrawn(cmd.amount)) - .thenReply(cmd)(_ ⇒ Confirmed) + .thenReply(cmd)(_ => Confirmed) } else { Effect.reply(cmd)(Rejected(s"Insufficient balance ${acc.balance} to be able to withdraw ${cmd.amount}")) @@ -168,7 +168,7 @@ object AccountExampleWithEventHandlersInState { private def closeAccount(acc: OpenedAccount, cmd: CloseAccount): ReplyEffect[AccountEvent, Account] = { if (acc.balance == Zero) Effect.persist(AccountClosed) - .thenReply(cmd)(_ ⇒ Confirmed) + .thenReply(cmd)(_ => Confirmed) else Effect.reply(cmd)(Rejected("Can't close account with non-zero balance")) } diff --git a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithOptionState.scala b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithOptionState.scala index 7740915584..6a4381ee89 100644 --- a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithOptionState.scala +++ b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/AccountExampleWithOptionState.scala @@ -64,40 +64,40 @@ object AccountExampleWithOptionState { override def applyCommand(cmd: AccountCommand[_]): ReplyEffect = cmd match { - case c @ Deposit(amount) ⇒ + case c @ Deposit(amount) => Effect.persist(Deposited(amount)) - .thenReply(c)(_ ⇒ Confirmed) + .thenReply(c)(_ => Confirmed) - case c @ Withdraw(amount) ⇒ + case c @ Withdraw(amount) => if (canWithdraw(amount)) { Effect.persist(Withdrawn(amount)) - .thenReply(c)(_ ⇒ Confirmed) + .thenReply(c)(_ => Confirmed) } else { Effect.reply(c)(Rejected(s"Insufficient balance $balance to be able to withdraw $amount")) } - case c: GetBalance ⇒ + case c: GetBalance => Effect.reply(c)(CurrentBalance(balance)) - case c: CloseAccount ⇒ + case c: CloseAccount => if (balance == Zero) Effect.persist(AccountClosed) - .thenReply(c)(_ ⇒ Confirmed) + .thenReply(c)(_ => Confirmed) else Effect.reply(c)(Rejected("Can't close account with non-zero balance")) - case c: CreateAccount ⇒ + case c: CreateAccount => Effect.reply(c)(Rejected("Account is already created")) } override def applyEvent(event: AccountEvent): Account = event match { - case Deposited(amount) ⇒ copy(balance = balance + amount) - case Withdrawn(amount) ⇒ copy(balance = balance - amount) - case AccountClosed ⇒ ClosedAccount - case AccountCreated ⇒ throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") + case Deposited(amount) => copy(balance = balance + amount) + case Withdrawn(amount) => copy(balance = balance - amount) + case AccountClosed => ClosedAccount + case AccountCreated => throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") } def canWithdraw(amount: BigDecimal): Boolean = { @@ -108,13 +108,13 @@ object AccountExampleWithOptionState { case object ClosedAccount extends Account { override def applyCommand(cmd: AccountCommand[_]): ReplyEffect = cmd match { - case c @ (_: Deposit | _: Withdraw) ⇒ + case c @ (_: Deposit | _: Withdraw) => Effect.reply(c)(Rejected("Account is closed")) - case c: GetBalance ⇒ + case c: GetBalance => Effect.reply(c)(CurrentBalance(Zero)) - case c: CloseAccount ⇒ + case c: CloseAccount => Effect.reply(c)(Rejected("Account is already closed")) - case c: CreateAccount ⇒ + case c: CreateAccount => Effect.reply(c)(Rejected("Account is already created")) } @@ -126,23 +126,23 @@ object AccountExampleWithOptionState { EventSourcedBehavior.withEnforcedReplies[AccountCommand[AccountCommandReply], AccountEvent, Option[Account]]( PersistenceId(s"Account|$accountNumber"), None, - (state, cmd) ⇒ state match { - case None ⇒ onFirstCommand(cmd) - case Some(account) ⇒ account.applyCommand(cmd) + (state, cmd) => state match { + case None => onFirstCommand(cmd) + case Some(account) => account.applyCommand(cmd) }, - (state, event) ⇒ state match { - case None ⇒ Some(onFirstEvent(event)) - case Some(account) ⇒ Some(account.applyEvent(event)) + (state, event) => state match { + case None => Some(onFirstEvent(event)) + case Some(account) => Some(account.applyEvent(event)) } ) } def onFirstCommand(cmd: AccountCommand[_]): ReplyEffect = { cmd match { - case c: CreateAccount ⇒ + case c: CreateAccount => Effect.persist(AccountCreated) - .thenReply(c)(_ ⇒ Confirmed) - case _ ⇒ + .thenReply(c)(_ => Confirmed) + case _ => // CreateAccount before handling any other commands Effect.unhandled.thenNoReply() } @@ -150,8 +150,8 @@ object AccountExampleWithOptionState { def onFirstEvent(event: AccountEvent): Account = { event match { - case AccountCreated ⇒ OpenedAccount(Zero) - case _ ⇒ throw new IllegalStateException(s"unexpected event [$event] in state [EmptyAccount]") + case AccountCreated => OpenedAccount(Zero) + case _ => throw new IllegalStateException(s"unexpected event [$event] in state [EmptyAccount]") } } diff --git a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BasicPersistentBehaviorCompileOnly.scala b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BasicPersistentBehaviorCompileOnly.scala index 1422d07b7e..5800f529ab 100644 --- a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BasicPersistentBehaviorCompileOnly.scala +++ b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BasicPersistentBehaviorCompileOnly.scala @@ -32,21 +32,21 @@ object BasicPersistentBehaviorCompileOnly { //#command-handler import akka.persistence.typed.scaladsl.Effect - val commandHandler: (State, Command) ⇒ Effect[Event, State] = { - (state, command) ⇒ + val commandHandler: (State, Command) => Effect[Event, State] = { + (state, command) => command match { - case Add(data) ⇒ Effect.persist(Added(data)) - case Clear ⇒ Effect.persist(Cleared) + case Add(data) => Effect.persist(Added(data)) + case Clear => Effect.persist(Cleared) } } //#command-handler //#event-handler - val eventHandler: (State, Event) ⇒ State = { - (state, event) ⇒ + val eventHandler: (State, Event) => State = { + (state, event) => event match { - case Added(data) ⇒ state.copy((data :: state.history).take(5)) - case Cleared ⇒ State(Nil) + case Added(data) => state.copy((data :: state.history).take(5)) + case Cleared => State(Nil) } } //#event-handler @@ -72,10 +72,10 @@ object BasicPersistentBehaviorCompileOnly { persistenceId = PersistenceId("abc"), emptyState = State(), commandHandler = - (state, cmd) ⇒ + (state, cmd) => throw new RuntimeException("TODO: process the command & return an Effect"), eventHandler = - (state, evt) ⇒ + (state, evt) => throw new RuntimeException("TODO: process the event return the next state") ) //#structure @@ -86,12 +86,12 @@ object BasicPersistentBehaviorCompileOnly { persistenceId = PersistenceId("abc"), emptyState = State(), commandHandler = - (state, cmd) ⇒ + (state, cmd) => throw new RuntimeException("TODO: process the command & return an Effect"), eventHandler = - (state, evt) ⇒ + (state, evt) => throw new RuntimeException("TODO: process the event return the next state") - ).onRecoveryCompleted { state ⇒ + ).onRecoveryCompleted { state => throw new RuntimeException("TODO: add some end-of-recovery side-effect here") } //#recovery @@ -102,12 +102,12 @@ object BasicPersistentBehaviorCompileOnly { persistenceId = PersistenceId("abc"), emptyState = State(), commandHandler = - (state, cmd) ⇒ + (state, cmd) => throw new RuntimeException("TODO: process the command & return an Effect"), eventHandler = - (state, evt) ⇒ + (state, evt) => throw new RuntimeException("TODO: process the event return the next state") - ).withTagger(_ ⇒ Set("tag1", "tag2")) + ).withTagger(_ => Set("tag1", "tag2")) //#tagging //#wrapPersistentBehavior @@ -115,18 +115,18 @@ object BasicPersistentBehaviorCompileOnly { persistenceId = PersistenceId("abc"), emptyState = State(), commandHandler = - (state, cmd) ⇒ + (state, cmd) => throw new RuntimeException("TODO: process the command & return an Effect"), eventHandler = - (state, evt) ⇒ + (state, evt) => throw new RuntimeException("TODO: process the event return the next state") - ).onRecoveryCompleted { state ⇒ + ).onRecoveryCompleted { state => throw new RuntimeException("TODO: add some end-of-recovery side-effect here") } val debugAlwaysSnapshot: Behavior[Command] = Behaviors.setup { - context ⇒ - samplePersistentBehavior.snapshotWhen((state, _, _) ⇒ { + context => + samplePersistentBehavior.snapshotWhen((state, _, _) => { context.log.info( "Snapshot actor {} => state: {}", context.self.path.name, state) @@ -149,19 +149,19 @@ object BasicPersistentBehaviorCompileOnly { import akka.persistence.typed.scaladsl.EventSourcedBehavior.CommandHandler val behaviorWithContext: Behavior[String] = - Behaviors.setup { context ⇒ + Behaviors.setup { context => EventSourcedBehavior[String, String, State]( persistenceId = PersistenceId("myPersistenceId"), emptyState = new State, commandHandler = CommandHandler.command { - cmd ⇒ + cmd => context.log.info("Got command {}", cmd) - Effect.persist(cmd).thenRun { state ⇒ + Effect.persist(cmd).thenRun { state => context.log.info("event persisted, new state {}", state) } }, eventHandler = { - case (state, _) ⇒ state + case (state, _) => state }) } // #actor-context @@ -171,10 +171,10 @@ object BasicPersistentBehaviorCompileOnly { persistenceId = PersistenceId("abc"), emptyState = State(), commandHandler = - (state, cmd) ⇒ + (state, cmd) => throw new RuntimeException("TODO: process the command & return an Effect"), eventHandler = - (state, evt) ⇒ + (state, evt) => throw new RuntimeException("TODO: process the event return the next state") ).snapshotEvery(100) //#snapshottingEveryN @@ -185,14 +185,14 @@ object BasicPersistentBehaviorCompileOnly { persistenceId = PersistenceId("abc"), emptyState = State(), commandHandler = - (state, cmd) ⇒ + (state, cmd) => throw new RuntimeException("TODO: process the command & return an Effect"), eventHandler = - (state, evt) ⇒ + (state, evt) => throw new RuntimeException("TODO: process the event return the next state") ).snapshotWhen { - case (state, BookingCompleted(_), sequenceNumber) ⇒ true - case (state, event, sequenceNumber) ⇒ false + case (state, BookingCompleted(_), sequenceNumber) => true + case (state, event, sequenceNumber) => false } //#snapshottingPredicate @@ -203,10 +203,10 @@ object BasicPersistentBehaviorCompileOnly { persistenceId = PersistenceId("abc"), emptyState = State(), commandHandler = - (state, cmd) ⇒ + (state, cmd) => throw new RuntimeException("TODO: process the command & return an Effect"), eventHandler = - (state, evt) ⇒ + (state, evt) => throw new RuntimeException("TODO: process the event return the next state") ).withSnapshotSelectionCriteria(SnapshotSelectionCriteria.None) //#snapshotSelection diff --git a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BlogPostExample.scala b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BlogPostExample.scala index 3848c5f238..7c6c9137a2 100644 --- a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BlogPostExample.scala +++ b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/BlogPostExample.scala @@ -64,24 +64,24 @@ object BlogPostExample { //#behavior //#command-handler - private val commandHandler: (BlogState, BlogCommand) ⇒ Effect[BlogEvent, BlogState] = { (state, command) ⇒ + private val commandHandler: (BlogState, BlogCommand) => Effect[BlogEvent, BlogState] = { (state, command) => state match { - case BlankState ⇒ command match { - case cmd: AddPost ⇒ addPost(cmd) - case _ ⇒ Effect.unhandled + case BlankState => command match { + case cmd: AddPost => addPost(cmd) + case _ => Effect.unhandled } - case draftState: DraftState ⇒ command match { - case cmd: ChangeBody ⇒ changeBody(draftState, cmd) - case Publish(replyTo) ⇒ publish(draftState, replyTo) - case GetPost(replyTo) ⇒ getPost(draftState, replyTo) - case _: AddPost ⇒ Effect.unhandled + case draftState: DraftState => command match { + case cmd: ChangeBody => changeBody(draftState, cmd) + case Publish(replyTo) => publish(draftState, replyTo) + case GetPost(replyTo) => getPost(draftState, replyTo) + case _: AddPost => Effect.unhandled } - case publishedState: PublishedState ⇒ command match { - case GetPost(replyTo) ⇒ getPost(publishedState, replyTo) - case _ ⇒ Effect.unhandled + case publishedState: PublishedState => command match { + case GetPost(replyTo) => getPost(publishedState, replyTo) + case _ => Effect.unhandled } } } @@ -89,7 +89,7 @@ object BlogPostExample { private def addPost(cmd: AddPost): Effect[BlogEvent, BlogState] = { //#reply val evt = PostAdded(cmd.content.postId, cmd.content) - Effect.persist(evt).thenRun { _ ⇒ + Effect.persist(evt).thenRun { _ => // After persist is done additional side effects can be performed cmd.replyTo ! AddPostDone(cmd.content.postId) } @@ -98,13 +98,13 @@ object BlogPostExample { private def changeBody(state: DraftState, cmd: ChangeBody): Effect[BlogEvent, BlogState] = { val evt = BodyChanged(state.postId, cmd.newBody) - Effect.persist(evt).thenRun { _ ⇒ + Effect.persist(evt).thenRun { _ => cmd.replyTo ! Done } } private def publish(state: DraftState, replyTo: ActorRef[Done]): Effect[BlogEvent, BlogState] = { - Effect.persist(Published(state.postId)).thenRun { _ ⇒ + Effect.persist(Published(state.postId)).thenRun { _ => println(s"Blog post ${state.postId} was published") replyTo ! Done } @@ -122,27 +122,27 @@ object BlogPostExample { //#command-handler //#event-handler - private val eventHandler: (BlogState, BlogEvent) ⇒ BlogState = { (state, event) ⇒ + private val eventHandler: (BlogState, BlogEvent) => BlogState = { (state, event) => state match { - case BlankState ⇒ event match { - case PostAdded(_, content) ⇒ + case BlankState => event match { + case PostAdded(_, content) => DraftState(content) - case _ ⇒ throw new IllegalStateException(s"unexpected event [$event] in state [$state]") + case _ => throw new IllegalStateException(s"unexpected event [$event] in state [$state]") } - case draftState: DraftState ⇒ event match { + case draftState: DraftState => event match { - case BodyChanged(_, newBody) ⇒ + case BodyChanged(_, newBody) => draftState.withBody(newBody) - case Published(_) ⇒ + case Published(_) => PublishedState(draftState.content) - case _ ⇒ throw new IllegalStateException(s"unexpected event [$event] in state [$state]") + case _ => throw new IllegalStateException(s"unexpected event [$event] in state [$state]") } - case _: PublishedState ⇒ + case _: PublishedState => // no more changes after published throw new IllegalStateException(s"unexpected event [$event] in state [$state]") } diff --git a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/MovieWatchList.scala b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/MovieWatchList.scala index 4d13a16114..b66d624733 100644 --- a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/MovieWatchList.scala +++ b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/MovieWatchList.scala @@ -24,20 +24,20 @@ object MovieWatchList { final case class MovieList(movieIds: Set[String]) { def applyEvent(event: Event): MovieList = { event match { - case MovieAdded(movieId) ⇒ copy(movieIds = movieIds + movieId) - case MovieRemoved(movieId) ⇒ copy(movieIds = movieIds + movieId) + case MovieAdded(movieId) => copy(movieIds = movieIds + movieId) + case MovieRemoved(movieId) => copy(movieIds = movieIds + movieId) } } } private val commandHandler: CommandHandler[Command, Event, MovieList] = { - (state, cmd) ⇒ + (state, cmd) => cmd match { - case AddMovie(movieId) ⇒ + case AddMovie(movieId) => Effect.persist(MovieAdded(movieId)) - case RemoveMovie(movieId) ⇒ + case RemoveMovie(movieId) => Effect.persist(MovieRemoved(movieId)) - case GetMovieList(replyTo) ⇒ + case GetMovieList(replyTo) => replyTo ! state Effect.none } @@ -48,7 +48,7 @@ object MovieWatchList { persistenceId = PersistenceId(s"movies-$userId"), emptyState = MovieList(Set.empty), commandHandler, - eventHandler = (state, event) ⇒ state.applyEvent(event) + eventHandler = (state, event) => state.applyEvent(event) ) } diff --git a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/StashingExample.scala b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/StashingExample.scala index 81b1669664..9958f3584a 100644 --- a/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/StashingExample.scala +++ b/akka-persistence-typed/src/test/scala/docs/akka/persistence/typed/StashingExample.scala @@ -33,37 +33,37 @@ object StashingExample { EventSourcedBehavior[Command, Event, State]( persistenceId = persistenceId, emptyState = State(None), - commandHandler = (state, command) ⇒ onCommand(state, command), - eventHandler = (state, event) ⇒ applyEvent(state, event) + commandHandler = (state, command) => onCommand(state, command), + eventHandler = (state, event) => applyEvent(state, event) ).onPersistFailure(SupervisorStrategy.restartWithBackoff(1.second, 30.seconds, 0.2)) private def onCommand(state: State, command: Command): Effect[Event, State] = { state.taskIdInProgress match { - case None ⇒ + case None => command match { - case StartTask(taskId) ⇒ + case StartTask(taskId) => Effect.persist(TaskStarted(taskId)) - case _ ⇒ + case _ => Effect.unhandled } - case Some(inProgress) ⇒ + case Some(inProgress) => command match { - case StartTask(taskId) ⇒ + case StartTask(taskId) => if (inProgress == taskId) Effect.none // duplicate, already in progress else // other task in progress, wait with new task until later Effect.stash() - case NextStep(taskId, instruction) ⇒ + case NextStep(taskId, instruction) => if (inProgress == taskId) Effect.persist(TaskStep(taskId, instruction)) else // other task in progress, wait with new task until later Effect.stash() - case EndTask(taskId) ⇒ + case EndTask(taskId) => if (inProgress == taskId) Effect.persist(TaskCompleted(taskId)) .thenUnstashAll() // continue with next task @@ -76,9 +76,9 @@ object StashingExample { private def applyEvent(state: State, event: Event): State = { event match { - case TaskStarted(taskId) ⇒ State(Option(taskId)) - case TaskStep(_, _) ⇒ state - case TaskCompleted(_) ⇒ State(None) + case TaskStarted(taskId) => State(Option(taskId)) + case TaskStep(_, _) => state + case TaskCompleted(_) => State(None) } } } diff --git a/akka-persistence/src/main/scala/akka/persistence/AtLeastOnceDelivery.scala b/akka-persistence/src/main/scala/akka/persistence/AtLeastOnceDelivery.scala index c2b68b4979..ba98fddc40 100644 --- a/akka-persistence/src/main/scala/akka/persistence/AtLeastOnceDelivery.scala +++ b/akka-persistence/src/main/scala/akka/persistence/AtLeastOnceDelivery.scala @@ -133,7 +133,7 @@ trait AtLeastOnceDelivery extends PersistentActor with AtLeastOnceDeliveryLike { * This method will throw [[AtLeastOnceDelivery.MaxUnconfirmedMessagesExceededException]] * if [[#numberOfUnconfirmed]] is greater than or equal to [[#maxUnconfirmedMessages]]. */ - def deliver(destination: ActorPath)(deliveryIdToMessage: Long ⇒ Any): Unit = { + def deliver(destination: ActorPath)(deliveryIdToMessage: Long => Any): Unit = { internalDeliver(destination)(deliveryIdToMessage) } @@ -157,7 +157,7 @@ trait AtLeastOnceDelivery extends PersistentActor with AtLeastOnceDeliveryLike { * This method will throw [[AtLeastOnceDelivery.MaxUnconfirmedMessagesExceededException]] * if [[#numberOfUnconfirmed]] is greater than or equal to [[#maxUnconfirmedMessages]]. */ - def deliver(destination: ActorSelection)(deliveryIdToMessage: Long ⇒ Any): Unit = { + def deliver(destination: ActorSelection)(deliveryIdToMessage: Long => Any): Unit = { internalDeliver(destination)(deliveryIdToMessage) } @@ -256,7 +256,7 @@ trait AtLeastOnceDeliveryLike extends Eventsourced { * INTERNAL API */ @InternalApi - private[akka] final def internalDeliver(destination: ActorPath)(deliveryIdToMessage: Long ⇒ Any): Unit = { + private[akka] final def internalDeliver(destination: ActorPath)(deliveryIdToMessage: Long => Any): Unit = { if (unconfirmed.size >= maxUnconfirmedMessages) throw new MaxUnconfirmedMessagesExceededException( s"Too many unconfirmed messages, maximum allowed is [$maxUnconfirmedMessages]") @@ -275,7 +275,7 @@ trait AtLeastOnceDeliveryLike extends Eventsourced { * INTERNAL API */ @InternalApi - private[akka] final def internalDeliver(destination: ActorSelection)(deliveryIdToMessage: Long ⇒ Any): Unit = { + private[akka] final def internalDeliver(destination: ActorSelection)(deliveryIdToMessage: Long => Any): Unit = { val isWildcardSelection = destination.pathString.contains("*") require(!isWildcardSelection, "Delivering to wildcard actor selections is not supported by AtLeastOnceDelivery. " + "Introduce an mediator Actor which this AtLeastOnceDelivery Actor will deliver the messages to," + @@ -310,10 +310,10 @@ trait AtLeastOnceDeliveryLike extends Eventsourced { unconfirmed .iterator - .filter { case (_, delivery) ⇒ delivery.timestamp <= deadline } + .filter { case (_, delivery) => delivery.timestamp <= deadline } .take(redeliveryBurstLimit) .foreach { - case (deliveryId, delivery) ⇒ + case (deliveryId, delivery) => send(deliveryId, delivery, now) if (delivery.attempt == warnAfterNumberOfUnconfirmedAttempts) @@ -344,7 +344,7 @@ trait AtLeastOnceDeliveryLike extends Eventsourced { def getDeliverySnapshot: AtLeastOnceDeliverySnapshot = AtLeastOnceDeliverySnapshot( deliverySequenceNr, - unconfirmed.iterator.map { case (deliveryId, d) ⇒ UnconfirmedDelivery(deliveryId, d.destination, d.message) }.to(immutable.IndexedSeq)) + unconfirmed.iterator.map { case (deliveryId, d) => UnconfirmedDelivery(deliveryId, d.destination, d.message) }.to(immutable.IndexedSeq)) /** * If snapshot from [[#getDeliverySnapshot]] was saved it will be received during recovery @@ -353,8 +353,8 @@ trait AtLeastOnceDeliveryLike extends Eventsourced { def setDeliverySnapshot(snapshot: AtLeastOnceDeliverySnapshot): Unit = { deliverySequenceNr = snapshot.currentDeliveryId val now = System.nanoTime() - unconfirmed = scala.collection.immutable.SortedMap.from(snapshot.unconfirmedDeliveries.iterator.map(d ⇒ - d.deliveryId → Delivery(d.destination, d.message, now, 0))) + unconfirmed = scala.collection.immutable.SortedMap.from(snapshot.unconfirmedDeliveries.iterator.map(d => + d.deliveryId -> Delivery(d.destination, d.message, now, 0))) } /** @@ -386,10 +386,10 @@ trait AtLeastOnceDeliveryLike extends Eventsourced { */ override protected[akka] def aroundReceive(receive: Receive, message: Any): Unit = message match { - case RedeliveryTick ⇒ + case RedeliveryTick => redeliverOverdue() - case _ ⇒ + case _ => super.aroundReceive(receive, message) } } @@ -425,7 +425,7 @@ abstract class UntypedPersistentActorWithAtLeastOnceDelivery extends UntypedPers * if [[#numberOfUnconfirmed]] is greater than or equal to [[#maxUnconfirmedMessages]]. */ def deliver(destination: ActorPath, deliveryIdToMessage: akka.japi.Function[java.lang.Long, Object]): Unit = - internalDeliver(destination)(id ⇒ deliveryIdToMessage.apply(id)) + internalDeliver(destination)(id => deliveryIdToMessage.apply(id)) /** * Java API: Send the message created by the `deliveryIdToMessage` function to @@ -448,7 +448,7 @@ abstract class UntypedPersistentActorWithAtLeastOnceDelivery extends UntypedPers * if [[#numberOfUnconfirmed]] is greater than or equal to [[#maxUnconfirmedMessages]]. */ def deliver(destination: ActorSelection, deliveryIdToMessage: akka.japi.Function[java.lang.Long, Object]): Unit = - internalDeliver(destination)(id ⇒ deliveryIdToMessage.apply(id)) + internalDeliver(destination)(id => deliveryIdToMessage.apply(id)) } /** @@ -483,7 +483,7 @@ abstract class AbstractPersistentActorWithAtLeastOnceDelivery extends AbstractPe * if [[#numberOfUnconfirmed]] is greater than or equal to [[#maxUnconfirmedMessages]]. */ def deliver(destination: ActorPath, deliveryIdToMessage: akka.japi.Function[java.lang.Long, Object]): Unit = - internalDeliver(destination)(id ⇒ deliveryIdToMessage.apply(id)) + internalDeliver(destination)(id => deliveryIdToMessage.apply(id)) /** * Java API: Send the message created by the `deliveryIdToMessage` function to @@ -506,5 +506,5 @@ abstract class AbstractPersistentActorWithAtLeastOnceDelivery extends AbstractPe * if [[#numberOfUnconfirmed]] is greater than or equal to [[#maxUnconfirmedMessages]]. */ def deliver(destination: ActorSelection, deliveryIdToMessage: akka.japi.Function[java.lang.Long, Object]): Unit = - internalDeliver(destination)(id ⇒ deliveryIdToMessage.apply(id)) + internalDeliver(destination)(id => deliveryIdToMessage.apply(id)) } diff --git a/akka-persistence/src/main/scala/akka/persistence/Eventsourced.scala b/akka-persistence/src/main/scala/akka/persistence/Eventsourced.scala index d6fe156f79..9324fadcbd 100644 --- a/akka-persistence/src/main/scala/akka/persistence/Eventsourced.scala +++ b/akka-persistence/src/main/scala/akka/persistence/Eventsourced.scala @@ -28,13 +28,13 @@ private[persistence] object Eventsourced { private[akka] sealed trait PendingHandlerInvocation { def evt: Any - def handler: Any ⇒ Unit + def handler: Any => Unit } /** INTERNAL API: forces actor to stash incoming commands until all these invocations are handled */ - private[akka] final case class StashingHandlerInvocation(evt: Any, handler: Any ⇒ Unit) extends PendingHandlerInvocation + private[akka] final case class StashingHandlerInvocation(evt: Any, handler: Any => Unit) extends PendingHandlerInvocation /** INTERNAL API: does not force the actor to stash commands; Originates from either `persistAsync` or `defer` calls */ - private[akka] final case class AsyncHandlerInvocation(evt: Any, handler: Any ⇒ Unit) extends PendingHandlerInvocation + private[akka] final case class AsyncHandlerInvocation(evt: Any, handler: Any => Unit) extends PendingHandlerInvocation /** INTERNAL API: message used to detect that recovery timed out */ private[akka] final case class RecoveryTick(snapshot: Boolean) @@ -63,16 +63,16 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas private[persistence] lazy val journal = { val journalPluginConfig = this match { - case c: RuntimePluginConfig ⇒ c.journalPluginConfig - case _ ⇒ ConfigFactory.empty + case c: RuntimePluginConfig => c.journalPluginConfig + case _ => ConfigFactory.empty } extension.journalFor(journalPluginId, journalPluginConfig) } private[persistence] lazy val snapshotStore = { val snapshotPluginConfig = this match { - case c: RuntimePluginConfig ⇒ c.snapshotPluginConfig - case _ ⇒ ConfigFactory.empty + case c: RuntimePluginConfig => c.snapshotPluginConfig + case _ => ConfigFactory.empty } extension.snapshotStoreFor(snapshotPluginId, snapshotPluginConfig) } @@ -84,8 +84,8 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas // no longer used, but kept for binary compatibility private val maxMessageBatchSize = { val journalPluginConfig = this match { - case c: RuntimePluginConfig ⇒ c.journalPluginConfig - case _ ⇒ ConfigFactory.empty + case c: RuntimePluginConfig => c.journalPluginConfig + case _ => ConfigFactory.empty } extension.journalConfigFor(journalPluginId, journalPluginConfig).getInt("max-message-batch-size") } @@ -105,10 +105,10 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas private val internalStash = createStash() - private val unstashFilterPredicate: Any ⇒ Boolean = { - case _: WriteMessageSuccess ⇒ false - case _: ReplayedMessage ⇒ false - case _ ⇒ true + private val unstashFilterPredicate: Any => Boolean = { + case _: WriteMessageSuccess => false + case _: ReplayedMessage => false + case _ => true } /** @@ -147,10 +147,10 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas */ protected def onRecoveryFailure(cause: Throwable, event: Option[Any]): Unit = event match { - case Some(evt) ⇒ + case Some(evt) => log.error(cause, "Exception in receiveRecover when replaying event type [{}] with sequence number [{}] for " + "persistenceId [{}].", evt.getClass.getName, lastSequenceNr, persistenceId) - case None ⇒ + case None => log.error(cause, "Persistence failure when replaying events for persistenceId [{}]. " + "Last known sequence number [{}]", persistenceId, lastSequenceNr) } @@ -190,14 +190,14 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas private def stashInternally(currMsg: Any): Unit = try internalStash.stash() catch { - case e: StashOverflowException ⇒ + case e: StashOverflowException => internalStashOverflowStrategy match { - case DiscardToDeadLetterStrategy ⇒ + case DiscardToDeadLetterStrategy => val snd = sender() context.system.deadLetters.tell(DeadLetter(currMsg, snd, self), snd) - case ReplyToStrategy(response) ⇒ + case ReplyToStrategy(response) => sender() ! response - case ThrowOverflowExceptionStrategy ⇒ + case ThrowOverflowExceptionStrategy => throw e } } @@ -208,8 +208,8 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas private def startRecovery(recovery: Recovery): Unit = { val timeout = { val journalPluginConfig = this match { - case c: RuntimePluginConfig ⇒ c.journalPluginConfig - case _ ⇒ ConfigFactory.empty + case c: RuntimePluginConfig => c.journalPluginConfig + case _ => ConfigFactory.empty } extension.journalConfigFor(journalPluginId, journalPluginConfig).getMillisDuration("recovery-event-timeout") } @@ -245,16 +245,16 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas unstashAll(unstashFilterPredicate) } finally { message match { - case Some(WriteMessageSuccess(m, _)) ⇒ + case Some(WriteMessageSuccess(m, _)) => flushJournalBatch() super.aroundPreRestart(reason, Some(m)) - case Some(LoopMessageSuccess(m, _)) ⇒ + case Some(LoopMessageSuccess(m, _)) => flushJournalBatch() super.aroundPreRestart(reason, Some(m)) - case Some(ReplayedMessage(m)) ⇒ + case Some(ReplayedMessage(m)) => flushJournalBatch() super.aroundPreRestart(reason, Some(m)) - case mo ⇒ + case mo => flushJournalBatch() super.aroundPreRestart(reason, mo) } @@ -276,18 +276,18 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas override def unhandled(message: Any): Unit = { message match { - case RecoveryCompleted ⇒ // mute - case SaveSnapshotFailure(m, e) ⇒ + case RecoveryCompleted => // mute + case SaveSnapshotFailure(m, e) => log.warning("Failed to saveSnapshot given metadata [{}] due to: [{}: {}]", m, e.getClass.getCanonicalName, e.getMessage) - case DeleteSnapshotFailure(m, e) ⇒ + case DeleteSnapshotFailure(m, e) => log.warning("Failed to deleteSnapshot given metadata [{}] due to: [{}: {}]", m, e.getClass.getCanonicalName, e.getMessage) - case DeleteSnapshotsFailure(c, e) ⇒ + case DeleteSnapshotsFailure(c, e) => log.warning("Failed to deleteSnapshots given criteria [{}] due to: [{}: {}]", c, e.getClass.getCanonicalName, e.getMessage) - case DeleteMessagesFailure(e, toSequenceNr) ⇒ + case DeleteMessagesFailure(e, toSequenceNr) => log.warning( "Failed to deleteMessages toSequenceNr [{}] for persistenceId [{}] due to [{}: {}].", toSequenceNr, persistenceId, e.getClass.getCanonicalName, e.getMessage) - case m ⇒ super.unhandled(m) + case m => super.unhandled(m) } } @@ -342,10 +342,10 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas * Internal API */ @InternalApi - final private[akka] def internalPersist[A](event: A)(handler: A ⇒ Unit): Unit = { + final private[akka] def internalPersist[A](event: A)(handler: A => Unit): Unit = { if (recoveryRunning) throw new IllegalStateException("Cannot persist during replay. Events can be persisted when receiving RecoveryCompleted or later.") pendingStashingPersistInvocations += 1 - pendingInvocations addLast StashingHandlerInvocation(event, handler.asInstanceOf[Any ⇒ Unit]) + pendingInvocations addLast StashingHandlerInvocation(event, handler.asInstanceOf[Any => Unit]) eventBatch ::= AtomicWrite(PersistentRepr(event, persistenceId = persistenceId, sequenceNr = nextSequenceNr(), writerUuid = writerUuid, sender = sender())) } @@ -354,12 +354,12 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas * Internal API */ @InternalApi - final private[akka] def internalPersistAll[A](events: immutable.Seq[A])(handler: A ⇒ Unit): Unit = { + final private[akka] def internalPersistAll[A](events: immutable.Seq[A])(handler: A => Unit): Unit = { if (recoveryRunning) throw new IllegalStateException("Cannot persist during replay. Events can be persisted when receiving RecoveryCompleted or later.") if (events.nonEmpty) { - events.foreach { event ⇒ + events.foreach { event => pendingStashingPersistInvocations += 1 - pendingInvocations addLast StashingHandlerInvocation(event, handler.asInstanceOf[Any ⇒ Unit]) + pendingInvocations addLast StashingHandlerInvocation(event, handler.asInstanceOf[Any => Unit]) } eventBatch ::= AtomicWrite(events.map(PersistentRepr.apply(_, persistenceId = persistenceId, sequenceNr = nextSequenceNr(), writerUuid = writerUuid, sender = sender()))) @@ -370,9 +370,9 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas * Internal API */ @InternalApi - final private[akka] def internalPersistAsync[A](event: A)(handler: A ⇒ Unit): Unit = { + final private[akka] def internalPersistAsync[A](event: A)(handler: A => Unit): Unit = { if (recoveryRunning) throw new IllegalStateException("Cannot persist during replay. Events can be persisted when receiving RecoveryCompleted or later.") - pendingInvocations addLast AsyncHandlerInvocation(event, handler.asInstanceOf[Any ⇒ Unit]) + pendingInvocations addLast AsyncHandlerInvocation(event, handler.asInstanceOf[Any => Unit]) eventBatch ::= AtomicWrite(PersistentRepr(event, persistenceId = persistenceId, sequenceNr = nextSequenceNr(), writerUuid = writerUuid, sender = sender())) } @@ -381,11 +381,11 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas * Internal API */ @InternalApi - final private[akka] def internalPersistAllAsync[A](events: immutable.Seq[A])(handler: A ⇒ Unit): Unit = { + final private[akka] def internalPersistAllAsync[A](events: immutable.Seq[A])(handler: A => Unit): Unit = { if (recoveryRunning) throw new IllegalStateException("Cannot persist during replay. Events can be persisted when receiving RecoveryCompleted or later.") if (events.nonEmpty) { - events.foreach { event ⇒ - pendingInvocations addLast AsyncHandlerInvocation(event, handler.asInstanceOf[Any ⇒ Unit]) + events.foreach { event => + pendingInvocations addLast AsyncHandlerInvocation(event, handler.asInstanceOf[Any => Unit]) } eventBatch ::= AtomicWrite(events.map(PersistentRepr(_, persistenceId = persistenceId, sequenceNr = nextSequenceNr(), writerUuid = writerUuid, sender = sender()))) @@ -396,12 +396,12 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas * Internal API */ @InternalApi - final private[akka] def internalDeferAsync[A](event: A)(handler: A ⇒ Unit): Unit = { + final private[akka] def internalDeferAsync[A](event: A)(handler: A => Unit): Unit = { if (recoveryRunning) throw new IllegalStateException("Cannot defer during replay. Events can be deferred when receiving RecoveryCompleted or later.") if (pendingInvocations.isEmpty) { handler(event) } else { - pendingInvocations addLast AsyncHandlerInvocation(event, handler.asInstanceOf[Any ⇒ Unit]) + pendingInvocations addLast AsyncHandlerInvocation(event, handler.asInstanceOf[Any => Unit]) eventBatch = NonPersistentRepr(event, sender()) :: eventBatch } } @@ -410,13 +410,13 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas * Internal API */ @InternalApi - final private[akka] def internalDefer[A](event: A)(handler: A ⇒ Unit): Unit = { + final private[akka] def internalDefer[A](event: A)(handler: A => Unit): Unit = { if (recoveryRunning) throw new IllegalStateException("Cannot defer during replay. Events can be deferred when receiving RecoveryCompleted or later.") if (pendingInvocations.isEmpty) { handler(event) } else { pendingStashingPersistInvocations += 1 - pendingInvocations addLast StashingHandlerInvocation(event, handler.asInstanceOf[Any ⇒ Unit]) + pendingInvocations addLast StashingHandlerInvocation(event, handler.asInstanceOf[Any => Unit]) eventBatch = NonPersistentRepr(event, sender()) :: eventBatch } } @@ -480,9 +480,9 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas override def stash(): Unit = { context.asInstanceOf[ActorCell].currentMessage match { - case Envelope(_: JournalProtocol.Response, _) ⇒ + case Envelope(_: JournalProtocol.Response, _) => throw new IllegalStateException("Do not call stash inside of persist callback or during recovery.") - case _ ⇒ super.stash() + case _ => super.stash() } } @@ -514,10 +514,10 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas override def recoveryRunning: Boolean = true override def stateReceive(receive: Receive, message: Any) = message match { - case RecoveryPermitter.RecoveryPermitGranted ⇒ + case RecoveryPermitter.RecoveryPermitGranted => startRecovery(recovery) - case other ⇒ + case other => stashInternally(other) } } @@ -540,7 +540,7 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas private val recoveryBehavior: Receive = { val _receiveRecover = try receiveRecover catch { - case NonFatal(e) ⇒ + case NonFatal(e) => try onRecoveryFailure(e, Some(e)) finally context.stop(self) returnRecoveryPermit() @@ -548,11 +548,11 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas } { - case PersistentRepr(payload, _) if recoveryRunning && _receiveRecover.isDefinedAt(payload) ⇒ + case PersistentRepr(payload, _) if recoveryRunning && _receiveRecover.isDefinedAt(payload) => _receiveRecover(payload) - case s: SnapshotOffer if _receiveRecover.isDefinedAt(s) ⇒ + case s: SnapshotOffer if _receiveRecover.isDefinedAt(s) => _receiveRecover(s) - case RecoveryCompleted if _receiveRecover.isDefinedAt(RecoveryCompleted) ⇒ + case RecoveryCompleted if _receiveRecover.isDefinedAt(RecoveryCompleted) => _receiveRecover(RecoveryCompleted) } @@ -563,10 +563,10 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas override def recoveryRunning: Boolean = true override def stateReceive(receive: Receive, message: Any) = try message match { - case LoadSnapshotResult(sso, toSnr) ⇒ + case LoadSnapshotResult(sso, toSnr) => timeoutCancellable.cancel() sso.foreach { - case SelectedSnapshot(metadata, snapshot) ⇒ + case SelectedSnapshot(metadata, snapshot) => val offer = SnapshotOffer(metadata, snapshot) if (recoveryBehavior.isDefinedAt(offer)) { setLastSequenceNr(metadata.sequenceNr) @@ -579,22 +579,22 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas changeState(recovering(recoveryBehavior, timeout)) journal ! ReplayMessages(lastSequenceNr + 1L, toSnr, replayMax, persistenceId, self) - case LoadSnapshotFailed(cause) ⇒ + case LoadSnapshotFailed(cause) => timeoutCancellable.cancel() try onRecoveryFailure(cause, event = None) finally context.stop(self) returnRecoveryPermit() - case RecoveryTick(true) ⇒ + case RecoveryTick(true) => try onRecoveryFailure( new RecoveryTimedOut(s"Recovery timed out, didn't get snapshot within $timeout"), event = None) finally context.stop(self) returnRecoveryPermit() - case other ⇒ + case other => stashInternally(other) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => returnRecoveryPermit() throw e } @@ -630,18 +630,18 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas override def recoveryRunning: Boolean = _recoveryRunning override def stateReceive(receive: Receive, message: Any) = try message match { - case ReplayedMessage(p) ⇒ + case ReplayedMessage(p) => try { eventSeenInInterval = true updateLastSequenceNr(p) Eventsourced.super.aroundReceive(recoveryBehavior, p) } catch { - case NonFatal(t) ⇒ + case NonFatal(t) => timeoutCancellable.cancel() try onRecoveryFailure(t, Some(p.payload)) finally context.stop(self) returnRecoveryPermit() } - case RecoverySuccess(highestSeqNr) ⇒ + case RecoverySuccess(highestSeqNr) => timeoutCancellable.cancel() onReplaySuccess() // callback for subclass implementation sequenceNr = highestSeqNr @@ -651,25 +651,25 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas finally transitToProcessingState() // in finally in case exception and resume strategy // if exception from RecoveryCompleted the permit is returned in below catch returnRecoveryPermit() - case ReplayMessagesFailure(cause) ⇒ + case ReplayMessagesFailure(cause) => timeoutCancellable.cancel() try onRecoveryFailure(cause, event = None) finally context.stop(self) returnRecoveryPermit() - case RecoveryTick(false) if !eventSeenInInterval ⇒ + case RecoveryTick(false) if !eventSeenInInterval => timeoutCancellable.cancel() try onRecoveryFailure( new RecoveryTimedOut(s"Recovery timed out, didn't get event within $timeout, highest sequence number seen $lastSequenceNr"), event = None) finally context.stop(self) returnRecoveryPermit() - case RecoveryTick(false) ⇒ + case RecoveryTick(false) => eventSeenInInterval = false - case RecoveryTick(true) ⇒ + case RecoveryTick(true) => // snapshot tick, ignore - case other ⇒ + case other => stashInternally(other) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => returnRecoveryPermit() throw e } @@ -709,7 +709,7 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas override def recoveryRunning: Boolean = false val common: Receive = { - case WriteMessageSuccess(p, id) ⇒ + case WriteMessageSuccess(p, id) => // instanceId mismatch can happen for persistAsync and defer in case of actor restart // while message is in flight, in that case we ignore the call to the handler if (id == instanceId) { @@ -718,10 +718,10 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas peekApplyHandler(p.payload) onWriteMessageComplete(err = false) } catch { - case NonFatal(e) ⇒ onWriteMessageComplete(err = true); throw e + case NonFatal(e) => onWriteMessageComplete(err = true); throw e } } - case WriteMessageRejected(p, cause, id) ⇒ + case WriteMessageRejected(p, cause, id) => // instanceId mismatch can happen for persistAsync and defer in case of actor restart // while message is in flight, in that case the handler has already been discarded if (id == instanceId) { @@ -729,14 +729,14 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas onWriteMessageComplete(err = false) onPersistRejected(cause, p.payload, p.sequenceNr) } - case WriteMessageFailure(p, cause, id) ⇒ + case WriteMessageFailure(p, cause, id) => // instanceId mismatch can happen for persistAsync and defer in case of actor restart // while message is in flight, in that case the handler has already been discarded if (id == instanceId) { onWriteMessageComplete(err = false) try onPersistFailure(cause, p.payload, p.sequenceNr) finally context.stop(self) } - case LoopMessageSuccess(l, id) ⇒ + case LoopMessageSuccess(l, id) => // instanceId mismatch can happen for persistAsync and defer in case of actor restart // while message is in flight, in that case we ignore the call to the handler if (id == instanceId) { @@ -744,18 +744,18 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas peekApplyHandler(l) onWriteMessageComplete(err = false) } catch { - case NonFatal(e) ⇒ onWriteMessageComplete(err = true); throw e + case NonFatal(e) => onWriteMessageComplete(err = true); throw e } } - case WriteMessagesSuccessful ⇒ + case WriteMessagesSuccessful => writeInProgress = false flushJournalBatch() - case WriteMessagesFailed(_) ⇒ + case WriteMessagesFailed(_) => writeInProgress = false () // it will be stopped by the first WriteMessageFailure message - case _: RecoveryTick ⇒ + case _: RecoveryTick => // we may have one of these in the mailbox before the scheduled timeout // is cancelled when recovery has completed, just consume it so the concrete actor never sees it } @@ -776,7 +776,7 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas Eventsourced.super.aroundReceive(receive, message) aroundReceiveComplete(err = false) } catch { - case NonFatal(e) ⇒ aroundReceiveComplete(err = true); throw e + case NonFatal(e) => aroundReceiveComplete(err = true); throw e } private def aroundReceiveComplete(err: Boolean): Unit = { @@ -806,12 +806,12 @@ private[persistence] trait Eventsourced extends Snapshotter with PersistenceStas override def onWriteMessageComplete(err: Boolean): Unit = { pendingInvocations.pop() match { - case _: StashingHandlerInvocation ⇒ + case _: StashingHandlerInvocation => // enables an early return to `processingCommands`, because if this counter hits `0`, // we know the remaining pendingInvocations are all `persistAsync` created, which // means we can go back to processing commands also - and these callbacks will be called as soon as possible pendingStashingPersistInvocations -= 1 - case _ ⇒ // do nothing + case _ => // do nothing } if (pendingStashingPersistInvocations == 0) { diff --git a/akka-persistence/src/main/scala/akka/persistence/Persistence.scala b/akka-persistence/src/main/scala/akka/persistence/Persistence.scala index c96a9bd69f..25c81f31df 100644 --- a/akka-persistence/src/main/scala/akka/persistence/Persistence.scala +++ b/akka-persistence/src/main/scala/akka/persistence/Persistence.scala @@ -266,10 +266,10 @@ class Persistence(val system: ExtendedActorSystem) extends Extension { */ private[akka] final def adaptersFor(journalPluginActor: ActorRef): EventAdapters = { pluginExtensionId.get().values collectFirst { - case ext if ext(system).actor == journalPluginActor ⇒ ext(system).adapters + case ext if ext(system).actor == journalPluginActor => ext(system).adapters } match { - case Some(adapters) ⇒ adapters - case _ ⇒ IdentityEventAdapters + case Some(adapters) => adapters + case _ => IdentityEventAdapters } } @@ -290,10 +290,10 @@ class Persistence(val system: ExtendedActorSystem) extends Extension { */ private[akka] final def configFor(journalPluginActor: ActorRef): Config = pluginExtensionId.get().values.collectFirst { - case ext if ext(system).actor == journalPluginActor ⇒ ext(system).config + case ext if ext(system).actor == journalPluginActor => ext(system).config } match { - case Some(conf) ⇒ conf - case None ⇒ throw new IllegalArgumentException(s"Unknown plugin actor $journalPluginActor") + case Some(conf) => conf + case None => throw new IllegalArgumentException(s"Unknown plugin actor $journalPluginActor") } /** @@ -324,9 +324,9 @@ class Persistence(val system: ExtendedActorSystem) extends Extension { @tailrec private def pluginHolderFor(configPath: String, fallbackPath: String, additionalConfig: Config): PluginHolder = { val extensionIdMap = pluginExtensionId.get extensionIdMap.get(configPath) match { - case Some(extensionId) ⇒ + case Some(extensionId) => extensionId(system) - case None ⇒ + case None => val extensionId = new PluginHolderExtensionId(configPath, fallbackPath, additionalConfig) pluginExtensionId.compareAndSet(extensionIdMap, extensionIdMap.updated(configPath, extensionId)) pluginHolderFor(configPath, fallbackPath, additionalConfig) // Recursive invocation. @@ -336,9 +336,9 @@ class Persistence(val system: ExtendedActorSystem) extends Extension { private def createPlugin(configPath: String, pluginConfig: Config): ActorRef = { val pluginActorName = configPath val pluginClassName = pluginConfig.getString("class") match { - case "" ⇒ throw new IllegalArgumentException("Plugin class name must be defined in config property " + + case "" => throw new IllegalArgumentException("Plugin class name must be defined in config property " + s"[$configPath.class]") - case className ⇒ className + case className => className } log.debug(s"Create plugin: $pluginActorName $pluginClassName") val pluginClass = system.dynamicAccess.getClassFor[Any](pluginClassName).get @@ -347,12 +347,12 @@ class Persistence(val system: ExtendedActorSystem) extends Extension { Reflect.findConstructor(pluginClass, List(pluginConfig, configPath)) // will throw if not found List(pluginConfig, configPath) } catch { - case NonFatal(_) ⇒ + case NonFatal(_) => try { Reflect.findConstructor(pluginClass, List(pluginConfig)) // will throw if not found List(pluginConfig) } catch { - case NonFatal(_) ⇒ Nil + case NonFatal(_) => Nil } // otherwise use empty constructor } val pluginActorProps = Props(Deploy(dispatcher = pluginDispatcherId), pluginClass, pluginActorArgs) diff --git a/akka-persistence/src/main/scala/akka/persistence/PersistencePlugin.scala b/akka-persistence/src/main/scala/akka/persistence/PersistencePlugin.scala index 21f80266d5..c4788928aa 100644 --- a/akka-persistence/src/main/scala/akka/persistence/PersistencePlugin.scala +++ b/akka-persistence/src/main/scala/akka/persistence/PersistencePlugin.scala @@ -49,9 +49,9 @@ private[akka] abstract class PersistencePlugin[ScalaDsl, JavaDsl, T: ClassTag](s val configPath = pluginId val extensionIdMap = plugins.get extensionIdMap.get(configPath) match { - case Some(extensionId) ⇒ + case Some(extensionId) => extensionId(system) - case None ⇒ + case None => val extensionId = new ExtensionId[PluginHolder[ScalaDsl, JavaDsl]] { override def createExtension(system: ExtendedActorSystem): PluginHolder[ScalaDsl, JavaDsl] = { val provider = createPlugin(configPath, readJournalPluginConfig) @@ -82,13 +82,13 @@ private[akka] abstract class PersistencePlugin[ScalaDsl, JavaDsl, T: ClassTag](s instantiate((classOf[ExtendedActorSystem], system) :: (classOf[Config], pluginConfig) :: (classOf[String], configPath) :: Nil) .recoverWith { - case x: NoSuchMethodException ⇒ instantiate( + case x: NoSuchMethodException => instantiate( (classOf[ExtendedActorSystem], system) :: (classOf[Config], pluginConfig) :: Nil) } - .recoverWith { case x: NoSuchMethodException ⇒ instantiate((classOf[ExtendedActorSystem], system) :: Nil) } - .recoverWith { case x: NoSuchMethodException ⇒ instantiate(Nil) } + .recoverWith { case x: NoSuchMethodException => instantiate((classOf[ExtendedActorSystem], system) :: Nil) } + .recoverWith { case x: NoSuchMethodException => instantiate(Nil) } .recoverWith { - case ex: Exception ⇒ Failure.apply( + case ex: Exception => Failure.apply( new IllegalArgumentException("Unable to create read journal plugin instance for path " + s"[$configPath], class [$pluginClassName]!", ex)) }.get diff --git a/akka-persistence/src/main/scala/akka/persistence/Persistent.scala b/akka-persistence/src/main/scala/akka/persistence/Persistent.scala index c6a4af55c4..7c7a677edc 100644 --- a/akka-persistence/src/main/scala/akka/persistence/Persistent.scala +++ b/akka-persistence/src/main/scala/akka/persistence/Persistent.scala @@ -40,10 +40,10 @@ final case class AtomicWrite(payload: immutable.Seq[PersistentRepr]) extends Per // only check that all persistenceIds are equal when there's more than one in the Seq if (payload match { - case l: List[PersistentRepr] ⇒ l.tail.nonEmpty // avoids calling .size - case v: Vector[PersistentRepr] ⇒ v.size > 1 - case _ ⇒ true // some other collection type, let's just check - }) payload.foreach { pr ⇒ + case l: List[PersistentRepr] => l.tail.nonEmpty // avoids calling .size + case v: Vector[PersistentRepr] => v.size > 1 + case _ => true // some other collection type, let's just check + }) payload.foreach { pr => if (pr.persistenceId != payload.head.persistenceId) throw new IllegalArgumentException( "AtomicWrite must contain messages for the same persistenceId, " + diff --git a/akka-persistence/src/main/scala/akka/persistence/PersistentActor.scala b/akka-persistence/src/main/scala/akka/persistence/PersistentActor.scala index f78db46330..c8e424e155 100644 --- a/akka-persistence/src/main/scala/akka/persistence/PersistentActor.scala +++ b/akka-persistence/src/main/scala/akka/persistence/PersistentActor.scala @@ -4,7 +4,7 @@ package akka.persistence -import java.lang.{ Iterable ⇒ JIterable } +import java.lang.{ Iterable => JIterable } import akka.actor._ import akka.japi.Procedure @@ -195,7 +195,7 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param event event to be persisted * @param handler handler for each persisted `event` */ - def persist[A](event: A)(handler: A ⇒ Unit): Unit = { + def persist[A](event: A)(handler: A => Unit): Unit = { internalPersist(event)(handler) } @@ -207,7 +207,7 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param events events to be persisted * @param handler handler for each persisted `events` */ - def persistAll[A](events: immutable.Seq[A])(handler: A ⇒ Unit): Unit = { + def persistAll[A](events: immutable.Seq[A])(handler: A => Unit): Unit = { internalPersistAll(events)(handler) } @@ -234,7 +234,7 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param event event to be persisted * @param handler handler for each persisted `event` */ - def persistAsync[A](event: A)(handler: A ⇒ Unit): Unit = { + def persistAsync[A](event: A)(handler: A => Unit): Unit = { internalPersistAsync(event)(handler) } @@ -246,7 +246,7 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param events events to be persisted * @param handler handler for each persisted `events` */ - def persistAllAsync[A](events: immutable.Seq[A])(handler: A ⇒ Unit): Unit = { + def persistAllAsync[A](events: immutable.Seq[A])(handler: A => Unit): Unit = { internalPersistAllAsync(events)(handler) } @@ -267,7 +267,7 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param event event to be handled in the future, when preceding persist operations have been processes * @param handler handler for the given `event` */ - def deferAsync[A](event: A)(handler: A ⇒ Unit): Unit = { + def deferAsync[A](event: A)(handler: A => Unit): Unit = { internalDeferAsync(event)(handler) } @@ -289,7 +289,7 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param event event to be handled in the future, when preceding persist operations have been processes * @param handler handler for the given `event` */ - def defer[A](event: A)(handler: A ⇒ Unit): Unit = { + def defer[A](event: A)(handler: A => Unit): Unit = { internalDefer(event)(handler) } } @@ -303,11 +303,11 @@ abstract class UntypedPersistentActor extends UntypedActor with Eventsourced wit final def onReceive(message: Any) = onReceiveCommand(message) final def receiveRecover: Receive = { - case msg ⇒ onReceiveRecover(msg) + case msg => onReceiveRecover(msg) } final def receiveCommand: Receive = { - case msg ⇒ onReceiveCommand(msg) + case msg => onReceiveCommand(msg) } /** @@ -336,7 +336,7 @@ abstract class UntypedPersistentActor extends UntypedActor with Eventsourced wit * @param handler handler for each persisted `event` */ def persist[A](event: A, handler: Procedure[A]): Unit = - internalPersist(event)(event ⇒ handler(event)) + internalPersist(event)(event => handler(event)) /** * Java API: asynchronously persists `events` in specified order. This is equivalent to calling @@ -347,7 +347,7 @@ abstract class UntypedPersistentActor extends UntypedActor with Eventsourced wit * @param handler handler for each persisted `events` */ def persistAll[A](events: JIterable[A], handler: Procedure[A]): Unit = - internalPersistAll(Util.immutableSeq(events))(event ⇒ handler(event)) + internalPersistAll(Util.immutableSeq(events))(event => handler(event)) /** * JAVA API: asynchronously persists `event`. On successful persistence, `handler` is called with the @@ -373,7 +373,7 @@ abstract class UntypedPersistentActor extends UntypedActor with Eventsourced wit * @param handler handler for each persisted `event` */ def persistAsync[A](event: A)(handler: Procedure[A]): Unit = - internalPersistAsync(event)(event ⇒ handler(event)) + internalPersistAsync(event)(event => handler(event)) /** * JAVA API: asynchronously persists `events` in specified order. This is equivalent to calling @@ -384,7 +384,7 @@ abstract class UntypedPersistentActor extends UntypedActor with Eventsourced wit * @param handler handler for each persisted `events` */ def persistAllAsync[A](events: JIterable[A], handler: Procedure[A]): Unit = - internalPersistAllAsync(Util.immutableSeq(events))(event ⇒ handler(event)) + internalPersistAllAsync(Util.immutableSeq(events))(event => handler(event)) /** * Defer the handler execution until all pending handlers have been executed. @@ -404,7 +404,7 @@ abstract class UntypedPersistentActor extends UntypedActor with Eventsourced wit * @param handler handler for the given `event` */ def deferAsync[A](event: A)(handler: Procedure[A]): Unit = - internalDeferAsync(event)(event ⇒ handler(event)) + internalDeferAsync(event)(event => handler(event)) /** * Defer the handler execution until all pending handlers have been executed. It is guaranteed that no new commands @@ -425,7 +425,7 @@ abstract class UntypedPersistentActor extends UntypedActor with Eventsourced wit * @param handler handler for the given `event` */ def defer[A](event: A)(handler: Procedure[A]): Unit = { - internalDefer(event)(event ⇒ handler(event)) + internalDefer(event)(event => handler(event)) } /** @@ -547,7 +547,7 @@ abstract class AbstractPersistentActor extends AbstractActor with AbstractPersis * @param handler handler for each persisted `event` */ def persist[A](event: A, handler: Procedure[A]): Unit = - internalPersist(event)(event ⇒ handler(event)) + internalPersist(event)(event => handler(event)) /** * Java API: asynchronously persists `events` in specified order. This is equivalent to calling @@ -558,7 +558,7 @@ abstract class AbstractPersistentActor extends AbstractActor with AbstractPersis * @param handler handler for each persisted `events` */ def persistAll[A](events: JIterable[A], handler: Procedure[A]): Unit = - internalPersistAll(Util.immutableSeq(events))(event ⇒ handler(event)) + internalPersistAll(Util.immutableSeq(events))(event => handler(event)) /** * Java API: asynchronously persists `event`. On successful persistence, `handler` is called with the @@ -579,7 +579,7 @@ abstract class AbstractPersistentActor extends AbstractActor with AbstractPersis * @param handler handler for each persisted `event` */ def persistAsync[A](event: A, handler: Procedure[A]): Unit = - internalPersistAsync(event)(event ⇒ handler(event)) + internalPersistAsync(event)(event => handler(event)) /** * Java API: asynchronously persists `events` in specified order. This is equivalent to calling @@ -590,7 +590,7 @@ abstract class AbstractPersistentActor extends AbstractActor with AbstractPersis * @param handler handler for each persisted `events` */ def persistAllAsync[A](events: JIterable[A], handler: Procedure[A]): Unit = - internalPersistAllAsync(Util.immutableSeq(events))(event ⇒ handler(event)) + internalPersistAllAsync(Util.immutableSeq(events))(event => handler(event)) /** * Defer the handler execution until all pending handlers have been executed. @@ -610,7 +610,7 @@ abstract class AbstractPersistentActor extends AbstractActor with AbstractPersis * @param handler handler for the given `event` */ def deferAsync[A](event: A)(handler: Procedure[A]): Unit = - internalDeferAsync(event)(event ⇒ handler(event)) + internalDeferAsync(event)(event => handler(event)) /** * Defer the handler execution until all pending handlers have been executed. It is guaranteed that no new commands @@ -631,7 +631,7 @@ abstract class AbstractPersistentActor extends AbstractActor with AbstractPersis * @param handler handler for the given `event` */ def defer[A](event: A)(handler: Procedure[A]): Unit = { - internalDefer(event)(event ⇒ handler(event)) + internalDefer(event)(event => handler(event)) } } diff --git a/akka-persistence/src/main/scala/akka/persistence/RecoveryPermitter.scala b/akka-persistence/src/main/scala/akka/persistence/RecoveryPermitter.scala index 4e1c043ae6..5cb66b5ace 100644 --- a/akka-persistence/src/main/scala/akka/persistence/RecoveryPermitter.scala +++ b/akka-persistence/src/main/scala/akka/persistence/RecoveryPermitter.scala @@ -41,7 +41,7 @@ import akka.actor.Terminated private var maxPendingStats = 0 def receive = { - case RequestRecoveryPermit ⇒ + case RequestRecoveryPermit => context.watch(sender()) if (usedPermits >= maxPermits) { if (pending.isEmpty) @@ -52,10 +52,10 @@ import akka.actor.Terminated recoveryPermitGranted(sender()) } - case ReturnRecoveryPermit ⇒ + case ReturnRecoveryPermit => onReturnRecoveryPermit(sender()) - case Terminated(ref) ⇒ + case Terminated(ref) => // pre-mature termination should be rare if (!pending.remove(ref)) onReturnRecoveryPermit(ref) diff --git a/akka-persistence/src/main/scala/akka/persistence/SnapshotProtocol.scala b/akka-persistence/src/main/scala/akka/persistence/SnapshotProtocol.scala index c380faba49..0bf5109466 100644 --- a/akka-persistence/src/main/scala/akka/persistence/SnapshotProtocol.scala +++ b/akka-persistence/src/main/scala/akka/persistence/SnapshotProtocol.scala @@ -16,7 +16,7 @@ final case class SnapshotMetadata(persistenceId: String, sequenceNr: Long, times //#snapshot-metadata object SnapshotMetadata { - implicit val ordering: Ordering[SnapshotMetadata] = Ordering.fromLessThan[SnapshotMetadata] { (a, b) ⇒ + implicit val ordering: Ordering[SnapshotMetadata] = Ordering.fromLessThan[SnapshotMetadata] { (a, b) => if (a eq b) false else if (a.persistenceId != b.persistenceId) a.persistenceId.compareTo(b.persistenceId) < 0 else if (a.sequenceNr != b.sequenceNr) a.sequenceNr < b.sequenceNr diff --git a/akka-persistence/src/main/scala/akka/persistence/fsm/PersistentFSM.scala b/akka-persistence/src/main/scala/akka/persistence/fsm/PersistentFSM.scala index 2291dbc529..aedae4a8c5 100644 --- a/akka-persistence/src/main/scala/akka/persistence/fsm/PersistentFSM.scala +++ b/akka-persistence/src/main/scala/akka/persistence/fsm/PersistentFSM.scala @@ -35,17 +35,17 @@ private[akka] object SnapshotAfter extends ExtensionId[SnapshotAfter] with Exten private[akka] class SnapshotAfter(config: Config) extends Extension { val key = "akka.persistence.fsm.snapshot-after" val snapshotAfterValue = config.getString(key).toLowerCase match { - case "off" ⇒ None - case _ ⇒ Some(config.getInt(key)) + case "off" => None + case _ => Some(config.getInt(key)) } /** * Function that takes lastSequenceNr as the param, and returns whether the passed * sequence number should trigger auto snapshot or not */ - val isSnapshotAfterSeqNo: Long ⇒ Boolean = snapshotAfterValue match { - case Some(snapShotAfterValue) ⇒ seqNo: Long ⇒ seqNo % snapShotAfterValue == 0 - case None ⇒ seqNo: Long ⇒ false //always false, if snapshotAfter is not specified in config + val isSnapshotAfterSeqNo: Long => Boolean = snapshotAfterValue match { + case Some(snapShotAfterValue) => seqNo: Long => seqNo % snapShotAfterValue == 0 + case None => seqNo: Long => false //always false, if snapshotAfter is not specified in config } } @@ -80,7 +80,7 @@ trait PersistentFSM[S <: FSMState, D, E] extends PersistentActor with Persistent /** * Map from state identifier to state instance */ - lazy val statesMap: Map[String, S] = stateNames.map(name ⇒ (name.identifier, name)).toMap + lazy val statesMap: Map[String, S] = stateNames.map(name => (name.identifier, name)).toMap /** * Timeout set for the current state. Used when saving a snapshot @@ -119,10 +119,11 @@ trait PersistentFSM[S <: FSMState, D, E] extends PersistentActor with Persistent * Discover the latest recorded state */ override def receiveRecover: Receive = { - case domainEventTag(event) ⇒ startWith(stateName, applyEvent(event, stateData)) - case StateChangeEvent(stateIdentifier, timeout) ⇒ startWith(statesMap(stateIdentifier), stateData, timeout) - case SnapshotOffer(_, PersistentFSMSnapshot(stateIdentifier, data: D, timeout)) ⇒ startWith(statesMap(stateIdentifier), data, timeout) - case RecoveryCompleted ⇒ + case domainEventTag(event) => startWith(stateName, applyEvent(event, stateData)) + case StateChangeEvent(stateIdentifier, timeout) => startWith(statesMap(stateIdentifier), stateData, timeout) + case SnapshotOffer(_, PersistentFSMSnapshot(stateIdentifier, data: D, timeout)) => + startWith(statesMap(stateIdentifier), data, timeout) + case RecoveryCompleted => initialize() onRecoveryCompleted() } @@ -163,11 +164,11 @@ trait PersistentFSM[S <: FSMState, D, E] extends PersistentActor with Persistent } persistAll[Any](eventsToPersist) { - case domainEventTag(event) ⇒ + case domainEventTag(event) => nextData = applyEvent(event, nextData) doSnapshot = doSnapshot || snapshotAfterExtension.isSnapshotAfterSeqNo(lastSequenceNr) applyStateOnLastHandler() - case StateChangeEvent(stateIdentifier, timeout) ⇒ + case StateChangeEvent(stateIdentifier, timeout) => doSnapshot = doSnapshot || snapshotAfterExtension.isSnapshotAfterSeqNo(lastSequenceNr) applyStateOnLastHandler() } @@ -206,7 +207,10 @@ object PersistentFSM { * @tparam D state data type */ @InternalApi - private[persistence] case class PersistentFSMSnapshot[D](stateIdentifier: String, data: D, timeout: Option[FiniteDuration]) extends Message + private[persistence] case class PersistentFSMSnapshot[D](stateIdentifier: String, + data: D, + timeout: Option[FiniteDuration]) + extends Message /** * FSMState base trait, makes possible for simple default serialization by conversion to String @@ -290,17 +294,17 @@ object PersistentFSM { * INTERNAL API */ @InternalApi - private[persistence] final case class Timer(name: String, msg: Any, repeat: Boolean, generation: Int, - owner: AnyRef)(context: ActorContext) - extends NoSerializationVerificationNeeded { + private[persistence] final case class Timer(name: String, msg: Any, repeat: Boolean, generation: Int, owner: AnyRef)( + context: ActorContext) + extends NoSerializationVerificationNeeded { private var ref: Option[Cancellable] = _ private val scheduler = context.system.scheduler private implicit val executionContext = context.dispatcher def schedule(actor: ActorRef, timeout: FiniteDuration): Unit = { val timerMsg = msg match { - case m: AutoReceivedMessage ⇒ m - case _ ⇒ this + case m: AutoReceivedMessage => m + case _ => this } ref = Some( if (repeat) scheduler.schedule(timeout, timeout, actor, timerMsg) @@ -333,20 +337,27 @@ object PersistentFSM { * accumulated while processing the last message, possibly domain event and handler * to be executed after FSM moves to the new state (also triggered when staying in the same state) */ - final case class State[S, D, E]( - stateName: S, - stateData: D, - timeout: Option[FiniteDuration] = None, - stopReason: Option[Reason] = None, - replies: List[Any] = Nil, - domainEvents: Seq[E] = Nil, - afterTransitionDo: D ⇒ Unit = { _: D ⇒ })(private[akka] val notifies: Boolean = true) { + final case class State[S, D, E](stateName: S, + stateData: D, + timeout: Option[FiniteDuration] = None, + stopReason: Option[Reason] = None, + replies: List[Any] = Nil, + domainEvents: Seq[E] = Nil, + afterTransitionDo: D => Unit = { _: D => + })(private[akka] val notifies: Boolean = true) { /** * Copy object and update values if needed. */ @InternalApi - private[akka] def copy(stateName: S = stateName, stateData: D = stateData, timeout: Option[FiniteDuration] = timeout, stopReason: Option[Reason] = stopReason, replies: List[Any] = replies, notifies: Boolean = notifies, domainEvents: Seq[E] = domainEvents, afterTransitionDo: D ⇒ Unit = afterTransitionDo): State[S, D, E] = { + private[akka] def copy(stateName: S = stateName, + stateData: D = stateData, + timeout: Option[FiniteDuration] = timeout, + stopReason: Option[Reason] = stopReason, + replies: List[Any] = replies, + notifies: Boolean = notifies, + domainEvents: Seq[E] = domainEvents, + afterTransitionDo: D => Unit = afterTransitionDo): State[S, D, E] = { State(stateName, stateData, timeout, stopReason, replies, domainEvents, afterTransitionDo)(notifies) } @@ -358,8 +369,8 @@ object PersistentFSM { * Use Duration.Inf to deactivate an existing timeout. */ def forMax(timeout: Duration): State[S, D, E] = timeout match { - case f: FiniteDuration ⇒ copy(timeout = Some(f)) - case _ ⇒ copy(timeout = PersistentFSM.SomeMaxFiniteDuration) // we need to differentiate "not set" from disabled + case f: FiniteDuration => copy(timeout = Some(f)) + case _ => copy(timeout = PersistentFSM.SomeMaxFiniteDuration) // we need to differentiate "not set" from disabled } /** @@ -385,7 +396,9 @@ object PersistentFSM { @InternalApi @Deprecated - @deprecated("Internal API easily to be confused with regular FSM's using. Use regular events (`applying`). Internally, `copy` can be used instead.", "2.5.5") + @deprecated( + "Internal API easily to be confused with regular FSM's using. Use regular events (`applying`). Internally, `copy` can be used instead.", + "2.5.5") private[akka] def using(@deprecatedName('nextStateDate) nextStateData: D): State[S, D, E] = { copy(stateData = nextStateData) } @@ -413,7 +426,7 @@ object PersistentFSM { /** * Register a handler to be triggered after the state has been persisted successfully */ - def andThen(handler: D ⇒ Unit): State[S, D, E] = { + def andThen(handler: D => Unit): State[S, D, E] = { copy(afterTransitionDo = handler) } } @@ -428,7 +441,8 @@ object PersistentFSM { * Case class representing the state of the [[akka.actor.FSM]] whithin the * `onTermination` block. */ - final case class StopEvent[S, D](reason: Reason, currentState: S, stateData: D) extends NoSerializationVerificationNeeded + final case class StopEvent[S, D](reason: Reason, currentState: S, stateData: D) + extends NoSerializationVerificationNeeded } @@ -438,7 +452,9 @@ object PersistentFSM { * Persistent Finite State Machine actor abstract base class. * */ -abstract class AbstractPersistentFSM[S <: FSMState, D, E] extends AbstractPersistentFSMBase[S, D, E] with PersistentFSM[S, D, E] { +abstract class AbstractPersistentFSM[S <: FSMState, D, E] + extends AbstractPersistentFSMBase[S, D, E] + with PersistentFSM[S, D, E] { import java.util.function.Consumer /** @@ -446,8 +462,8 @@ abstract class AbstractPersistentFSM[S <: FSMState, D, E] extends AbstractPersis * @param action - Java 8 lambda expression defining the action * @return action represented as a Scala Functin */ - final def exec(action: Consumer[D]): D ⇒ Unit = - data ⇒ action.accept(data) + final def exec(action: Consumer[D]): D => Unit = + data => action.accept(data) /** * Adapter from Java [[Class]] to [[scala.reflect.ClassTag]] @@ -470,6 +486,6 @@ abstract class AbstractPersistentFSM[S <: FSMState, D, E] extends AbstractPersis * */ abstract class AbstractPersistentLoggingFSM[S <: FSMState, D, E] - extends AbstractPersistentFSM[S, D, E] - with LoggingPersistentFSM[S, D, E] - with PersistentFSM[S, D, E] + extends AbstractPersistentFSM[S, D, E] + with LoggingPersistentFSM[S, D, E] + with PersistentFSM[S, D, E] diff --git a/akka-persistence/src/main/scala/akka/persistence/fsm/PersistentFSMBase.scala b/akka-persistence/src/main/scala/akka/persistence/fsm/PersistentFSMBase.scala index 336736d35a..1b9e295ad6 100644 --- a/akka-persistence/src/main/scala/akka/persistence/fsm/PersistentFSMBase.scala +++ b/akka-persistence/src/main/scala/akka/persistence/fsm/PersistentFSMBase.scala @@ -192,7 +192,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging final class TransformHelper(func: StateFunction) { def using(andThen: PartialFunction[State, State]): StateFunction = - func andThen (andThen orElse { case x ⇒ x }) + func andThen (andThen orElse { case x => x }) } final def transform(func: StateFunction): TransformHelper = new TransformHelper(func) @@ -279,7 +279,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging * Convenience wrapper for using a total function instead of a partial * function literal. To be used with onTransition. */ - implicit final def total2pf(transitionHandler: (S, S) ⇒ Unit): TransitionHandler = + implicit final def total2pf(transitionHandler: (S, S) => Unit): TransitionHandler = new TransitionHandler { def isDefinedAt(in: (S, S)) = true def apply(in: (S, S)): Unit = { transitionHandler(in._1, in._2) } @@ -337,8 +337,8 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging * Return next state data (available in onTransition handlers) */ final def nextStateData = nextState match { - case null ⇒ throw new IllegalStateException("nextStateData is only available during onTransition") - case x ⇒ x.stateData + case null => throw new IllegalStateException("nextStateData is only available during onTransition") + case x => x.stateData } /* @@ -383,7 +383,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging * unhandled event handler */ private val handleEventDefault: StateFunction = { - case Event(value, stateData) ⇒ + case Event(value, stateData) => log.warning("unhandled event " + value + " in state " + stateName) stay } @@ -400,7 +400,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging private var transitionEvent: List[TransitionHandler] = Nil private def handleTransition(prev: S, next: S): Unit = { val tuple = (prev, next) - for (te ← transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) } + for (te <- transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) } } /* @@ -409,11 +409,11 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging * ******************************************* */ override def receive: Receive = { - case TimeoutMarker(gen) ⇒ + case TimeoutMarker(gen) => if (generation == gen) { processMsg(StateTimeout, "state timeout") } - case t @ Timer(name, msg, repeat, gen, owner) ⇒ + case t @ Timer(name, msg, repeat, gen, owner) => if ((owner eq this) && (timers contains name) && (timers(name).generation == gen)) { if (timeoutFuture.isDefined) { timeoutFuture.get.cancel() @@ -425,21 +425,21 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging } processMsg(msg, t) } - case SubscribeTransitionCallBack(actorRef) ⇒ + case SubscribeTransitionCallBack(actorRef) => // TODO Use context.watch(actor) and receive Terminated(actor) to clean up list listeners.add(actorRef) // send current state back as reference point actorRef ! CurrentState(self, currentState.stateName, currentState.timeout) - case Listen(actorRef) ⇒ + case Listen(actorRef) => // TODO Use context.watch(actor) and receive Terminated(actor) to clean up list listeners.add(actorRef) // send current state back as reference point actorRef ! CurrentState(self, currentState.stateName, currentState.timeout) - case UnsubscribeTransitionCallBack(actorRef) ⇒ + case UnsubscribeTransitionCallBack(actorRef) => listeners.remove(actorRef) - case Deafen(actorRef) ⇒ + case Deafen(actorRef) => listeners.remove(actorRef) - case value ⇒ + case value => if (timeoutFuture.isDefined) { timeoutFuture.get.cancel() timeoutFuture = None @@ -466,9 +466,9 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging private[akka] def applyState(nextState: State): Unit = { nextState.stopReason match { - case None ⇒ makeTransition(nextState) - case _ ⇒ - nextState.replies.reverse foreach { r ⇒ sender() ! r } + case None => makeTransition(nextState) + case _ => + nextState.replies.reverse foreach { r => sender() ! r } terminate(nextState) context.stop(self) } @@ -478,7 +478,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging if (!stateFunctions.contains(nextState.stateName)) { terminate(stay withStopReason Failure("Next state %s does not exist".format(nextState.stateName))) } else { - nextState.replies.reverse foreach { r ⇒ sender() ! r } + nextState.replies.reverse foreach { r => sender() ! r } if (currentState.stateName != nextState.stateName || nextState.notifies) { this.nextState = nextState handleTransition(currentState.stateName, nextState.stateName) @@ -488,9 +488,9 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging currentState = nextState val timeout = currentState.timeout match { - case PersistentFSM.SomeMaxFiniteDuration ⇒ None - case x: Some[FiniteDuration] ⇒ x - case None ⇒ stateTimeouts(currentState.stateName) + case PersistentFSM.SomeMaxFiniteDuration => None + case x: Some[FiniteDuration] => x + case None => stateTimeouts(currentState.stateName) } if (timeout.isDefined) { @@ -524,7 +524,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging if (currentState.stopReason.isEmpty) { val reason = nextState.stopReason.get logTermination(reason) - for (timer ← timers.values) timer.cancel() + for (timer <- timers.values) timer.cancel() timers.clear() currentState = nextState @@ -539,9 +539,9 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging * types are not logged. It is possible to override this behavior. */ protected def logTermination(reason: Reason): Unit = reason match { - case Failure(ex: Throwable) ⇒ log.error(ex, "terminating due to Failure") - case Failure(msg: AnyRef) ⇒ log.error(msg.toString) - case _ ⇒ + case Failure(ex: Throwable) => log.error(ex, "terminating due to Failure") + case Failure(msg: AnyRef) => log.error(msg.toString) + case _ => } } @@ -550,7 +550,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging * debug logging capabilities (analogous to [[akka.event.LoggingReceive]]). * */ -trait LoggingPersistentFSM[S, D, E] extends PersistentFSMBase[S, D, E] { this: Actor ⇒ +trait LoggingPersistentFSM[S, D, E] extends PersistentFSMBase[S, D, E] { this: Actor => import akka.persistence.fsm.PersistentFSM._ @@ -576,10 +576,10 @@ trait LoggingPersistentFSM[S, D, E] extends PersistentFSMBase[S, D, E] { this: A private[akka] abstract override def processEvent(event: Event, source: AnyRef): Unit = { if (debugEvent) { val srcstr = source match { - case s: String ⇒ s - case Timer(name, _, _, _, _) ⇒ "timer " + name - case a: ActorRef ⇒ a.toString - case _ ⇒ "unknown" + case s: String => s + case Timer(name, _, _, _, _) => "timer " + name + case a: ActorRef => a.toString + case _ => "unknown" } log.debug("processing {} from {} in state {}", event, srcstr, stateName) } @@ -604,7 +604,7 @@ trait LoggingPersistentFSM[S, D, E] extends PersistentFSMBase[S, D, E] { this: A * The log entries are lost when this actor is restarted. */ protected def getLog: IndexedSeq[LogEntry[S, D]] = { - val log = events zip states filter (_._1 ne null) map (x ⇒ LogEntry(x._2.asInstanceOf[S], x._1.stateData, x._1.event)) + val log = events zip states filter (_._1 ne null) map (x => LogEntry(x._2.asInstanceOf[S], x._1.stateData, x._1.event)) if (full) { IndexedSeq() ++ log.drop(pos) ++ log.take(pos) } else { @@ -640,7 +640,7 @@ abstract class AbstractPersistentFSMBase[S, D, E] extends PersistentFSMBase[S, D import akka.persistence.fsm.japi.pf.FSMStateFunctionBuilder import akka.persistence.fsm.japi.pf.FSMStopBuilder import akka.japi.pf.FI._ - import java.util.{ List ⇒ JList } + import java.util.{ List => JList } import PersistentFSM._ /** diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/AsyncRecovery.scala b/akka-persistence/src/main/scala/akka/persistence/journal/AsyncRecovery.scala index 5917f461c6..a9877eeb93 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/AsyncRecovery.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/AsyncRecovery.scala @@ -45,7 +45,7 @@ trait AsyncRecovery { * @see [[AsyncWriteJournal]] */ def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, - max: Long)(recoveryCallback: PersistentRepr ⇒ Unit): Future[Unit] + max: Long)(recoveryCallback: PersistentRepr => Unit): Future[Unit] /** * Plugin API: asynchronously reads the highest stored sequence number for the diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/AsyncWriteJournal.scala b/akka-persistence/src/main/scala/akka/persistence/journal/AsyncWriteJournal.scala index 2cc9c7426b..afbda0933d 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/AsyncWriteJournal.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/AsyncWriteJournal.scala @@ -36,11 +36,11 @@ trait AsyncWriteJournal extends Actor with WriteJournalBase with AsyncRecovery { private val replayFilterMode: ReplayFilter.Mode = toRootLowerCase(config.getString("replay-filter.mode")) match { - case "off" ⇒ ReplayFilter.Disabled - case "repair-by-discard-old" ⇒ ReplayFilter.RepairByDiscardOld - case "fail" ⇒ ReplayFilter.Fail - case "warn" ⇒ ReplayFilter.Warn - case other ⇒ throw new IllegalArgumentException( + case "off" => ReplayFilter.Disabled + case "repair-by-discard-old" => ReplayFilter.RepairByDiscardOld + case "fail" => ReplayFilter.Fail + case "warn" => ReplayFilter.Warn + case other => throw new IllegalArgumentException( s"invalid replay-filter.mode [$other], supported values [off, repair-by-discard-old, fail, warn]") } private def isReplayFilterEnabled: Boolean = replayFilterMode != ReplayFilter.Disabled @@ -57,21 +57,21 @@ trait AsyncWriteJournal extends Actor with WriteJournalBase with AsyncRecovery { val replayDebugEnabled: Boolean = config.getBoolean("replay-filter.debug") { - case WriteMessages(messages, persistentActor, actorInstanceId) ⇒ + case WriteMessages(messages, persistentActor, actorInstanceId) => val cctr = resequencerCounter - resequencerCounter += messages.foldLeft(1)((acc, m) ⇒ acc + m.size) + resequencerCounter += messages.foldLeft(1)((acc, m) => acc + m.size) val atomicWriteCount = messages.count(_.isInstanceOf[AtomicWrite]) val prepared = Try(preparePersistentBatch(messages)) val writeResult = (prepared match { - case Success(prep) ⇒ + case Success(prep) => // try in case the asyncWriteMessages throws try breaker.withCircuitBreaker(asyncWriteMessages(prep)) - catch { case NonFatal(e) ⇒ Future.failed(e) } - case f @ Failure(_) ⇒ + catch { case NonFatal(e) => Future.failed(e) } + case f @ Failure(_) => // exception from preparePersistentBatch => rejected - Future.successful(messages.collect { case a: AtomicWrite ⇒ f }) - }).map { results ⇒ + Future.successful(messages.collect { case a: AtomicWrite => f }) + }).map { results => if (results.nonEmpty && results.size != atomicWriteCount) throw new IllegalStateException("asyncWriteMessages returned invalid number of results. " + s"Expected [${prepared.get.size}], but got [${results.size}]") @@ -79,7 +79,7 @@ trait AsyncWriteJournal extends Actor with WriteJournalBase with AsyncRecovery { } writeResult.onComplete { - case Success(results) ⇒ + case Success(results) => resequencer ! Desequenced(WriteMessagesSuccessful, cctr, persistentActor, self) val resultsIter = @@ -87,41 +87,41 @@ trait AsyncWriteJournal extends Actor with WriteJournalBase with AsyncRecovery { else results.iterator var n = cctr + 1 messages.foreach { - case a: AtomicWrite ⇒ + case a: AtomicWrite => resultsIter.next() match { - case Success(_) ⇒ - a.payload.foreach { p ⇒ + case Success(_) => + a.payload.foreach { p => resequencer ! Desequenced(WriteMessageSuccess(p, actorInstanceId), n, persistentActor, p.sender) n += 1 } - case Failure(e) ⇒ - a.payload.foreach { p ⇒ + case Failure(e) => + a.payload.foreach { p => resequencer ! Desequenced(WriteMessageRejected(p, e, actorInstanceId), n, persistentActor, p.sender) n += 1 } } - case r: NonPersistentRepr ⇒ + case r: NonPersistentRepr => resequencer ! Desequenced(LoopMessageSuccess(r.payload, actorInstanceId), n, persistentActor, r.sender) n += 1 } - case Failure(e) ⇒ + case Failure(e) => resequencer ! Desequenced(WriteMessagesFailed(e), cctr, persistentActor, self) var n = cctr + 1 messages.foreach { - case a: AtomicWrite ⇒ - a.payload.foreach { p ⇒ + case a: AtomicWrite => + a.payload.foreach { p => resequencer ! Desequenced(WriteMessageFailure(p, e, actorInstanceId), n, persistentActor, p.sender) n += 1 } - case r: NonPersistentRepr ⇒ + case r: NonPersistentRepr => resequencer ! Desequenced(LoopMessageSuccess(r.payload, actorInstanceId), n, persistentActor, r.sender) n += 1 } } - case r @ ReplayMessages(fromSequenceNr, toSequenceNr, max, persistenceId, persistentActor) ⇒ + case r @ ReplayMessages(fromSequenceNr, toSequenceNr, max, persistenceId, persistentActor) => val replyTo = if (isReplayFilterEnabled) context.actorOf(ReplayFilter.props(persistentActor, replayFilterMode, replayFilterWindowSize, replayFilterMaxOldWriters, replayDebugEnabled)) @@ -134,7 +134,7 @@ trait AsyncWriteJournal extends Actor with WriteJournalBase with AsyncRecovery { * plugin does rely on this so if you change this change the Cassandra plugin. */ breaker.withCircuitBreaker(asyncReadHighestSequenceNr(persistenceId, readHighestSequenceNrFrom)) - .flatMap { highSeqNr ⇒ + .flatMap { highSeqNr => val toSeqNr = math.min(toSequenceNr, highSeqNr) if (toSeqNr <= 0L || fromSequenceNr > toSeqNr) Future.successful(highSeqNr) @@ -142,28 +142,28 @@ trait AsyncWriteJournal extends Actor with WriteJournalBase with AsyncRecovery { // Send replayed messages and replay result to persistentActor directly. No need // to resequence replayed messages relative to written and looped messages. // not possible to use circuit breaker here - asyncReplayMessages(persistenceId, fromSequenceNr, toSeqNr, max) { p ⇒ + asyncReplayMessages(persistenceId, fromSequenceNr, toSeqNr, max) { p => if (!p.deleted) // old records from 2.3 may still have the deleted flag - adaptFromJournal(p).foreach { adaptedPersistentRepr ⇒ + adaptFromJournal(p).foreach { adaptedPersistentRepr => replyTo.tell(ReplayedMessage(adaptedPersistentRepr), Actor.noSender) } - }.map(_ ⇒ highSeqNr) + }.map(_ => highSeqNr) } }.map { - highSeqNr ⇒ RecoverySuccess(highSeqNr) + highSeqNr => RecoverySuccess(highSeqNr) }.recover { - case e ⇒ ReplayMessagesFailure(e) + case e => ReplayMessagesFailure(e) }.pipeTo(replyTo).foreach { - _ ⇒ if (publish) context.system.eventStream.publish(r) + _ => if (publish) context.system.eventStream.publish(r) } - case d @ DeleteMessagesTo(persistenceId, toSequenceNr, persistentActor) ⇒ + case d @ DeleteMessagesTo(persistenceId, toSequenceNr, persistentActor) => breaker.withCircuitBreaker(asyncDeleteMessagesTo(persistenceId, toSequenceNr)) map { - _ ⇒ DeleteMessagesSuccess(toSequenceNr) + _ => DeleteMessagesSuccess(toSequenceNr) } recover { - case e ⇒ DeleteMessagesFailure(e, toSequenceNr) + case e => DeleteMessagesFailure(e, toSequenceNr) } pipeTo persistentActor onComplete { - _ ⇒ if (publish) context.system.eventStream.publish(d) + _ => if (publish) context.system.eventStream.publish(d) } } } @@ -276,7 +276,7 @@ private[persistence] object AsyncWriteJournal { private var delivered = 0L def receive = { - case d: Desequenced ⇒ resequence(d) + case d: Desequenced => resequence(d) } @scala.annotation.tailrec @@ -285,7 +285,7 @@ private[persistence] object AsyncWriteJournal { delivered = d.snr d.target.tell(d.msg, d.sender) } else { - delayed += (d.snr → d) + delayed += (d.snr -> d) } val ro = delayed.remove(delivered + 1) if (ro.isDefined) resequence(ro.get) diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/AsyncWriteProxy.scala b/akka-persistence/src/main/scala/akka/persistence/journal/AsyncWriteProxy.scala index 4bce5894d0..08c7233378 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/AsyncWriteProxy.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/AsyncWriteProxy.scala @@ -41,48 +41,48 @@ private[persistence] trait AsyncWriteProxy extends AsyncWriteJournal with Stash if (isInitialized) { if (msg != InitTimeout) super.aroundReceive(receive, msg) } else msg match { - case SetStore(ref) ⇒ + case SetStore(ref) => store = Some(ref) unstashAll() isInitialized = true - case InitTimeout ⇒ + case InitTimeout => isInitTimedOut = true unstashAll() // will trigger appropriate failures - case _ if isInitTimedOut ⇒ super.aroundReceive(receive, msg) - case _ ⇒ stash() + case _ if isInitTimedOut => super.aroundReceive(receive, msg) + case _ => stash() } implicit def timeout: Timeout def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = store match { - case Some(s) ⇒ (s ? WriteMessages(messages)).mapTo[immutable.Seq[Try[Unit]]] - case None ⇒ storeNotInitialized + case Some(s) => (s ? WriteMessages(messages)).mapTo[immutable.Seq[Try[Unit]]] + case None => storeNotInitialized } def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = store match { - case Some(s) ⇒ (s ? DeleteMessagesTo(persistenceId, toSequenceNr)).mapTo[Unit] - case None ⇒ storeNotInitialized + case Some(s) => (s ? DeleteMessagesTo(persistenceId, toSequenceNr)).mapTo[Unit] + case None => storeNotInitialized } - def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: PersistentRepr ⇒ Unit): Future[Unit] = + def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: PersistentRepr => Unit): Future[Unit] = store match { - case Some(s) ⇒ + case Some(s) => val replayCompletionPromise = Promise[Unit]() val mediator = context.actorOf(Props(classOf[ReplayMediator], replayCallback, replayCompletionPromise, timeout.duration).withDeploy(Deploy.local)) s.tell(ReplayMessages(persistenceId, fromSequenceNr, toSequenceNr, max), mediator) replayCompletionPromise.future - case None ⇒ storeNotInitialized + case None => storeNotInitialized } def asyncReadHighestSequenceNr(persistenceId: String, fromSequenceNr: Long): Future[Long] = store match { - case Some(s) ⇒ + case Some(s) => (s ? ReplayMessages(persistenceId, fromSequenceNr = 0L, toSequenceNr = 0L, max = 0L)).map { - case ReplaySuccess(highest) ⇒ highest + case ReplaySuccess(highest) => highest } - case None ⇒ storeNotInitialized + case None => storeNotInitialized } } @@ -122,20 +122,20 @@ private[persistence] object AsyncWriteTarget { @SerialVersionUID(1L) class AsyncReplayTimeoutException(msg: String) extends AkkaException(msg) -private class ReplayMediator(replayCallback: PersistentRepr ⇒ Unit, replayCompletionPromise: Promise[Unit], replayTimeout: Duration) extends Actor { +private class ReplayMediator(replayCallback: PersistentRepr => Unit, replayCompletionPromise: Promise[Unit], replayTimeout: Duration) extends Actor { import AsyncWriteTarget._ context.setReceiveTimeout(replayTimeout) def receive = { - case p: PersistentRepr ⇒ replayCallback(p) - case _: ReplaySuccess ⇒ + case p: PersistentRepr => replayCallback(p) + case _: ReplaySuccess => replayCompletionPromise.success(()) context.stop(self) - case ReplayFailure(cause) ⇒ + case ReplayFailure(cause) => replayCompletionPromise.failure(cause) context.stop(self) - case ReceiveTimeout ⇒ + case ReceiveTimeout => replayCompletionPromise.failure(new AsyncReplayTimeoutException(s"replay timed out after ${replayTimeout.toSeconds} seconds inactivity")) context.stop(self) } diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/EventAdapters.scala b/akka-persistence/src/main/scala/akka/persistence/journal/EventAdapters.scala index 812e1a96a2..5cb9516249 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/EventAdapters.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/EventAdapters.scala @@ -33,20 +33,20 @@ class EventAdapters( */ def get(clazz: Class[_]): EventAdapter = { map.get(clazz) match { - case null ⇒ // bindings are ordered from most specific to least specific + case null => // bindings are ordered from most specific to least specific val value = bindings filter { _._1 isAssignableFrom clazz } match { - case (_, bestMatch) +: _ ⇒ bestMatch - case _ ⇒ IdentityEventAdapter + case (_, bestMatch) +: _ => bestMatch + case _ => IdentityEventAdapter } map.putIfAbsent(clazz, value) match { - case null ⇒ + case null => log.debug(s"Using EventAdapter: {} for event [{}]", value.getClass.getName, clazz.getName) value - case some ⇒ some + case some => some } - case value ⇒ value + case value => value } } @@ -78,27 +78,27 @@ private[akka] object EventAdapters { val adapterNames = adapters.keys.toSet for { - (fqn, boundToAdapters) ← adapterBindings - boundAdapter ← boundToAdapters + (fqn, boundToAdapters) <- adapterBindings + boundAdapter <- boundToAdapters } require( adapterNames(boundAdapter.toString), s"$fqn was bound to undefined event-adapter: $boundAdapter (bindings: ${boundToAdapters.mkString("[", ", ", "]")}, known adapters: ${adapters.keys.mkString})") // A Map of handler from alias to implementation (i.e. class implementing akka.serialization.Serializer) // For example this defines a handler named 'country': `"country" -> com.example.comain.CountryTagsAdapter` - val handlers = for ((k: String, v: String) ← adapters) yield k → instantiateAdapter(v, system).get + val handlers = for ((k: String, v: String) <- adapters) yield k -> instantiateAdapter(v, system).get // bindings is a Seq of tuple representing the mapping from Class to handler. // It is primarily ordered by the most specific classes first, and secondly in the configured order. val bindings: immutable.Seq[ClassHandler] = { - val bs = for ((k: FQN, as: BoundAdapters) ← adapterBindings) + val bs = for ((k: FQN, as: BoundAdapters) <- adapterBindings) yield if (as.size == 1) (system.dynamicAccess.getClassFor[Any](k).get, handlers(as.head)) else (system.dynamicAccess.getClassFor[Any](k).get, NoopWriteEventAdapter(CombinedReadEventAdapter(as.map(handlers)))) sort(bs) } - val backing = bindings.foldLeft(new ConcurrentHashMap[Class[_], EventAdapter]) { case (map, (c, s)) ⇒ map.put(c, s); map } + val backing = bindings.foldLeft(new ConcurrentHashMap[Class[_], EventAdapter]) { case (map, (c, s)) => map.put(c, s); map } new EventAdapters(backing, bindings, system.log) } @@ -133,8 +133,8 @@ private[akka] object EventAdapters { * loading is performed by the system’s [[akka.actor.DynamicAccess]]. */ private def instantiate[T: ClassTag](fqn: FQN, system: ExtendedActorSystem): Try[T] = - system.dynamicAccess.createInstanceFor[T](fqn, List(classOf[ExtendedActorSystem] → system)) recoverWith { - case _: NoSuchMethodException ⇒ system.dynamicAccess.createInstanceFor[T](fqn, Nil) + system.dynamicAccess.createInstanceFor[T](fqn, List(classOf[ExtendedActorSystem] -> system)) recoverWith { + case _: NoSuchMethodException => system.dynamicAccess.createInstanceFor[T](fqn, Nil) } /** @@ -142,10 +142,10 @@ private[akka] object EventAdapters { * obeying any order between unrelated subtypes (insert sort). */ private def sort[T](in: Iterable[(Class[_], T)]): immutable.Seq[(Class[_], T)] = - in.foldLeft(new ArrayBuffer[(Class[_], T)](in.size)) { (buf, ca) ⇒ + in.foldLeft(new ArrayBuffer[(Class[_], T)](in.size)) { (buf, ca) => buf.indexWhere(_._1 isAssignableFrom ca._1) match { - case -1 ⇒ buf append ca - case x ⇒ buf insert (x, ca) + case -1 => buf append ca + case x => buf insert (x, ca) } buf }.to(immutable.Seq) @@ -153,7 +153,7 @@ private[akka] object EventAdapters { private final def configToMap(config: Config, path: String): Map[String, String] = { import scala.collection.JavaConverters._ if (config.hasPath(path)) { - config.getConfig(path).root.unwrapped.asScala.toMap map { case (k, v) ⇒ k → v.toString } + config.getConfig(path).root.unwrapped.asScala.toMap map { case (k, v) => k -> v.toString } } else Map.empty } @@ -161,8 +161,8 @@ private[akka] object EventAdapters { import scala.collection.JavaConverters._ if (config.hasPath(path)) { config.getConfig(path).root.unwrapped.asScala.toMap map { - case (k, v: util.ArrayList[_]) if v.isInstanceOf[util.ArrayList[_]] ⇒ k → v.asScala.map(_.toString).toList - case (k, v) ⇒ k → List(v.toString) + case (k, v: util.ArrayList[_]) if v.isInstanceOf[util.ArrayList[_]] => k -> v.asScala.map(_.toString).toList + case (k, v) => k -> List(v.toString) } } else Map.empty } diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/PersistencePluginProxy.scala b/akka-persistence/src/main/scala/akka/persistence/journal/PersistencePluginProxy.scala index 4c0343701f..48b7f2f063 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/PersistencePluginProxy.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/PersistencePluginProxy.scala @@ -64,9 +64,9 @@ final class PersistencePluginProxy(config: Config) extends Actor with Stash with private val pluginId = self.path.name private val pluginType: PluginType = pluginId match { - case "akka.persistence.journal.proxy" ⇒ Journal - case "akka.persistence.snapshot-store.proxy" ⇒ SnapshotStore - case other ⇒ + case "akka.persistence.journal.proxy" => Journal + case "akka.persistence.snapshot-store.proxy" => SnapshotStore + case other => throw new IllegalArgumentException("Unknown plugin type: " + other) } @@ -80,10 +80,10 @@ final class PersistencePluginProxy(config: Config) extends Actor with Stash with override def preStart(): Unit = { if (startTarget) { val target = pluginType match { - case Journal ⇒ + case Journal => log.info("Starting target journal [{}]", targetPluginId) Persistence(context.system).journalFor(targetPluginId) - case SnapshotStore ⇒ + case SnapshotStore => log.info("Starting target snapshot-store [{}]", targetPluginId) Persistence(context.system).snapshotStoreFor(targetPluginId) } @@ -96,7 +96,7 @@ final class PersistencePluginProxy(config: Config) extends Actor with Stash with log.info("Setting target {} address to {}", pluginType.qualifier, targetAddress) PersistencePluginProxy.setTargetLocation(context.system, AddressFromURIString(targetAddress)) } catch { - case _: URISyntaxException ⇒ log.warning("Invalid URL provided for target {} address: {}", pluginType.qualifier, targetAddress) + case _: URISyntaxException => log.warning("Invalid URL provided for target {} address: {}", pluginType.qualifier, targetAddress) } } @@ -113,15 +113,15 @@ final class PersistencePluginProxy(config: Config) extends Actor with Stash with def receive = init def init: Receive = { - case TargetLocation(address) ⇒ + case TargetLocation(address) => context.setReceiveTimeout(1.second) // for retries context.become(identifying(address)) - case InitTimeout ⇒ + case InitTimeout => log.info("Initialization timed-out (after {}), Use `PersistencePluginProxy.setTargetLocation` or set `target-{}-address`", initTimeout, pluginType.qualifier) context.become(initTimedOut) unstashAll() // will trigger appropriate failures - case Terminated(_) ⇒ - case msg ⇒ + case Terminated(_) => + case msg => stash() } @@ -138,67 +138,67 @@ final class PersistencePluginProxy(config: Config) extends Actor with Stash with } def identifying(address: Address): Receive = ({ - case ActorIdentity(`targetPluginId`, Some(target)) ⇒ + case ActorIdentity(`targetPluginId`, Some(target)) => log.info("Found target {} at [{}]", pluginType.qualifier, address) context.setReceiveTimeout(Duration.Undefined) context.watch(target) unstashAll() context.become(active(target, address == selfAddress)) - case _: ActorIdentity ⇒ // will retry after ReceiveTimeout - case Terminated(_) ⇒ - case ReceiveTimeout ⇒ + case _: ActorIdentity => // will retry after ReceiveTimeout + case Terminated(_) => + case ReceiveTimeout => sendIdentify(address) }: Receive).orElse(init) def active(targetJournal: ActorRef, targetAtThisNode: Boolean): Receive = { - case TargetLocation(address) ⇒ + case TargetLocation(address) => if (targetAtThisNode && address != selfAddress) becomeIdentifying(address) - case Terminated(`targetJournal`) ⇒ + case Terminated(`targetJournal`) => context.unwatch(targetJournal) context.become(initTimedOut) - case Terminated(_) ⇒ - case InitTimeout ⇒ - case msg ⇒ + case Terminated(_) => + case InitTimeout => + case msg => targetJournal forward msg } def initTimedOut: Receive = { - case req: JournalProtocol.Request ⇒ req match { // exhaustive match - case WriteMessages(messages, persistentActor, actorInstanceId) ⇒ + case req: JournalProtocol.Request => req match { // exhaustive match + case WriteMessages(messages, persistentActor, actorInstanceId) => persistentActor ! WriteMessagesFailed(timeoutException) messages.foreach { - case a: AtomicWrite ⇒ - a.payload.foreach { p ⇒ + case a: AtomicWrite => + a.payload.foreach { p => persistentActor ! WriteMessageFailure(p, timeoutException, actorInstanceId) } - case r: NonPersistentRepr ⇒ + case r: NonPersistentRepr => persistentActor ! LoopMessageSuccess(r.payload, actorInstanceId) } - case ReplayMessages(fromSequenceNr, toSequenceNr, max, persistenceId, persistentActor) ⇒ + case ReplayMessages(fromSequenceNr, toSequenceNr, max, persistenceId, persistentActor) => persistentActor ! ReplayMessagesFailure(timeoutException) - case DeleteMessagesTo(persistenceId, toSequenceNr, persistentActor) ⇒ + case DeleteMessagesTo(persistenceId, toSequenceNr, persistentActor) => persistentActor ! DeleteMessagesFailure(timeoutException, toSequenceNr) } - case req: SnapshotProtocol.Request ⇒ req match { // exhaustive match - case LoadSnapshot(persistenceId, criteria, toSequenceNr) ⇒ + case req: SnapshotProtocol.Request => req match { // exhaustive match + case LoadSnapshot(persistenceId, criteria, toSequenceNr) => sender() ! LoadSnapshotFailed(timeoutException) - case SaveSnapshot(metadata, snapshot) ⇒ + case SaveSnapshot(metadata, snapshot) => sender() ! SaveSnapshotFailure(metadata, timeoutException) - case DeleteSnapshot(metadata) ⇒ + case DeleteSnapshot(metadata) => sender() ! DeleteSnapshotFailure(metadata, timeoutException) - case DeleteSnapshots(persistenceId, criteria) ⇒ + case DeleteSnapshots(persistenceId, criteria) => sender() ! DeleteSnapshotsFailure(criteria, timeoutException) } - case TargetLocation(address) ⇒ + case TargetLocation(address) => becomeIdentifying(address) - case Terminated(_) ⇒ + case Terminated(_) => - case other ⇒ + case other => val e = timeoutException() log.error(e, "Failed PersistencePluginProxy request: {}", e.getMessage) } diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/ReplayFilter.scala b/akka-persistence/src/main/scala/akka/persistence/journal/ReplayFilter.scala index 1b3c4f6cda..a5702673de 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/ReplayFilter.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/ReplayFilter.scala @@ -64,7 +64,7 @@ private[akka] class ReplayFilter(persistentActor: ActorRef, mode: ReplayFilter.M var seqNo = -1L def receive = { - case r @ ReplayedMessage(persistent) ⇒ + case r @ ReplayedMessage(persistent) => if (debugEnabled) log.debug("Replay: {}", persistent) try { @@ -81,10 +81,10 @@ private[akka] class ReplayFilter(persistentActor: ActorRef, mode: ReplayFilter.M "Perhaps, events were journaled out of sequence, or duplicate persistentId for different entities?" logIssue(errMsg) mode match { - case RepairByDiscardOld ⇒ // discard - case Fail ⇒ throw new IllegalStateException(errMsg) - case Warn ⇒ buffer.add(r) - case Disabled ⇒ throw new IllegalArgumentException("mode must not be Disabled") + case RepairByDiscardOld => // discard + case Fail => throw new IllegalStateException(errMsg) + case Warn => buffer.add(r) + case Disabled => throw new IllegalArgumentException("mode must not be Disabled") } } else { // note that it is alright with == seqNo, since such may be emitted EventSeq @@ -99,10 +99,10 @@ private[akka] class ReplayFilter(persistentActor: ActorRef, mode: ReplayFilter.M "Perhaps, the old writer kept journaling messages after the new writer created, or duplicate persistentId for different entities?" logIssue(errMsg) mode match { - case RepairByDiscardOld ⇒ // discard - case Fail ⇒ throw new IllegalStateException(errMsg) - case Warn ⇒ buffer.add(r) - case Disabled ⇒ throw new IllegalArgumentException("mode must not be Disabled") + case RepairByDiscardOld => // discard + case Fail => throw new IllegalStateException(errMsg) + case Warn => buffer.add(r) + case Disabled => throw new IllegalArgumentException("mode must not be Disabled") } } else { @@ -125,10 +125,10 @@ private[akka] class ReplayFilter(persistentActor: ActorRef, mode: ReplayFilter.M "Perhaps, the new writer journaled the event out of sequence, or duplicate persistentId for different entities?" logIssue(errMsg) mode match { - case RepairByDiscardOld ⇒ iter.remove() // discard - case Fail ⇒ throw new IllegalStateException(errMsg) - case Warn ⇒ // keep - case Disabled ⇒ throw new IllegalArgumentException("mode must not be Disabled") + case RepairByDiscardOld => iter.remove() // discard + case Fail => throw new IllegalStateException(errMsg) + case Warn => // keep + case Disabled => throw new IllegalArgumentException("mode must not be Disabled") } } @@ -138,10 +138,10 @@ private[akka] class ReplayFilter(persistentActor: ActorRef, mode: ReplayFilter.M } } catch { - case e: IllegalStateException if mode == Fail ⇒ fail(e) + case e: IllegalStateException if mode == Fail => fail(e) } - case msg @ (_: RecoverySuccess | _: ReplayMessagesFailure) ⇒ + case msg @ (_: RecoverySuccess | _: ReplayMessagesFailure) => if (debugEnabled) log.debug("Replay completed: {}", msg) sendBuffered() @@ -157,17 +157,17 @@ private[akka] class ReplayFilter(persistentActor: ActorRef, mode: ReplayFilter.M } def logIssue(errMsg: String): Unit = mode match { - case Warn | RepairByDiscardOld ⇒ log.warning(errMsg) - case Fail ⇒ log.error(errMsg) - case Disabled ⇒ throw new IllegalArgumentException("mode must not be Disabled") + case Warn | RepairByDiscardOld => log.warning(errMsg) + case Fail => log.error(errMsg) + case Disabled => throw new IllegalArgumentException("mode must not be Disabled") } def fail(cause: IllegalStateException): Unit = { buffer.clear() persistentActor.tell(ReplayMessagesFailure(cause), Actor.noSender) context.become { - case _: ReplayedMessage ⇒ // discard - case msg @ (_: RecoverySuccess | _: ReplayMessagesFailure) ⇒ + case _: ReplayedMessage => // discard + case msg @ (_: RecoverySuccess | _: ReplayMessagesFailure) => context.stop(self) } } diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/WriteJournalBase.scala b/akka-persistence/src/main/scala/akka/persistence/journal/WriteJournalBase.scala index 708a9f8428..09d13c8340 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/WriteJournalBase.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/WriteJournalBase.scala @@ -10,21 +10,21 @@ import scala.collection.immutable import akka.persistence.AtomicWrite private[akka] trait WriteJournalBase { - this: Actor ⇒ + this: Actor => val persistence = Persistence(context.system) private val eventAdapters = persistence.adaptersFor(self) protected def preparePersistentBatch(rb: immutable.Seq[PersistentEnvelope]): immutable.Seq[AtomicWrite] = rb.collect { // collect instead of flatMap to avoid Some allocations - case a: AtomicWrite ⇒ + case a: AtomicWrite => // don't store sender - a.copy(payload = a.payload.map(p ⇒ adaptToJournal(p.update(sender = Actor.noSender)))) + a.copy(payload = a.payload.map(p => adaptToJournal(p.update(sender = Actor.noSender)))) } /** INTERNAL API */ private[akka] final def adaptFromJournal(repr: PersistentRepr): immutable.Seq[PersistentRepr] = - eventAdapters.get(repr.payload.getClass).fromJournal(repr.payload, repr.manifest).events map { adaptedPayload ⇒ + eventAdapters.get(repr.payload.getClass).fromJournal(repr.payload, repr.manifest).events map { adaptedPayload => repr.withPayload(adaptedPayload) } diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/inmem/InmemJournal.scala b/akka-persistence/src/main/scala/akka/persistence/journal/inmem/InmemJournal.scala index e15cde67a3..eaa49f7167 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/inmem/InmemJournal.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/inmem/InmemJournal.scala @@ -18,7 +18,7 @@ import akka.persistence.AtomicWrite */ private[persistence] class InmemJournal extends AsyncWriteJournal with InmemMessages { override def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = { - for (w ← messages; p ← w.payload) + for (w <- messages; p <- w.payload) add(p) Future.successful(Nil) // all good } @@ -28,7 +28,7 @@ private[persistence] class InmemJournal extends AsyncWriteJournal with InmemMess } override def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)( - recoveryCallback: PersistentRepr ⇒ Unit): Future[Unit] = { + recoveryCallback: PersistentRepr => Unit): Future[Unit] = { val highest = highestSequenceNr(persistenceId) if (highest != 0L && max != 0L) read(persistenceId, fromSequenceNr, math.min(toSequenceNr, highest), max).foreach(recoveryCallback) @@ -54,29 +54,29 @@ private[persistence] trait InmemMessages { var messages = Map.empty[String, Vector[PersistentRepr]] def add(p: PersistentRepr): Unit = messages = messages + (messages.get(p.persistenceId) match { - case Some(ms) ⇒ p.persistenceId → (ms :+ p) - case None ⇒ p.persistenceId → Vector(p) + case Some(ms) => p.persistenceId -> (ms :+ p) + case None => p.persistenceId -> Vector(p) }) - def update(pid: String, snr: Long)(f: PersistentRepr ⇒ PersistentRepr): Unit = messages = messages.get(pid) match { - case Some(ms) ⇒ messages + (pid → ms.map(sp ⇒ if (sp.sequenceNr == snr) f(sp) else sp)) - case None ⇒ messages + def update(pid: String, snr: Long)(f: PersistentRepr => PersistentRepr): Unit = messages = messages.get(pid) match { + case Some(ms) => messages + (pid -> ms.map(sp => if (sp.sequenceNr == snr) f(sp) else sp)) + case None => messages } def delete(pid: String, snr: Long): Unit = messages = messages.get(pid) match { - case Some(ms) ⇒ messages + (pid → ms.filterNot(_.sequenceNr == snr)) - case None ⇒ messages + case Some(ms) => messages + (pid -> ms.filterNot(_.sequenceNr == snr)) + case None => messages } def read(pid: String, fromSnr: Long, toSnr: Long, max: Long): immutable.Seq[PersistentRepr] = messages.get(pid) match { - case Some(ms) ⇒ ms.filter(m ⇒ m.sequenceNr >= fromSnr && m.sequenceNr <= toSnr).take(safeLongToInt(max)) - case None ⇒ Nil + case Some(ms) => ms.filter(m => m.sequenceNr >= fromSnr && m.sequenceNr <= toSnr).take(safeLongToInt(max)) + case None => Nil } def highestSequenceNr(pid: String): Long = { val snro = for { - ms ← messages.get(pid) - m ← ms.lastOption + ms <- messages.get(pid) + m <- ms.lastOption } yield m.sequenceNr snro.getOrElse(0L) } diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncRecovery.scala b/akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncRecovery.scala index d95aeb0a94..c56f3140f0 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncRecovery.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncRecovery.scala @@ -8,16 +8,16 @@ import java.util.function.Consumer import scala.concurrent.Future import akka.actor.Actor -import akka.persistence.journal.{ AsyncRecovery ⇒ SAsyncReplay } +import akka.persistence.journal.{ AsyncRecovery => SAsyncReplay } import akka.persistence.PersistentRepr /** * Java API: asynchronous message replay and sequence number recovery interface. */ -abstract class AsyncRecovery extends SAsyncReplay with AsyncRecoveryPlugin { this: Actor ⇒ +abstract class AsyncRecovery extends SAsyncReplay with AsyncRecoveryPlugin { this: Actor => import context.dispatcher - final def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: (PersistentRepr) ⇒ Unit) = + final def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: (PersistentRepr) => Unit) = doAsyncReplayMessages(persistenceId, fromSequenceNr, toSequenceNr, max, new Consumer[PersistentRepr] { def accept(p: PersistentRepr) = replayCallback(p) }).map(Unit.unbox) diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncWriteJournal.scala b/akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncWriteJournal.scala index e6028450c0..285bde2d86 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncWriteJournal.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncWriteJournal.scala @@ -7,7 +7,7 @@ package akka.persistence.journal.japi import scala.collection.immutable import scala.collection.JavaConverters._ import akka.persistence._ -import akka.persistence.journal.{ AsyncWriteJournal ⇒ SAsyncWriteJournal } +import akka.persistence.journal.{ AsyncWriteJournal => SAsyncWriteJournal } import akka.util.ccompat._ import scala.concurrent.Future import scala.util.Try @@ -21,8 +21,8 @@ abstract class AsyncWriteJournal extends AsyncRecovery with SAsyncWriteJournal w import context.dispatcher final def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = - doAsyncWriteMessages(messages.asJava).map { results ⇒ - results.asScala.iterator.map { r ⇒ + doAsyncWriteMessages(messages.asJava).map { results => + results.asScala.iterator.map { r => if (r.isPresent) Failure(r.get) else successUnit }.to(immutable.IndexedSeq) diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbCompaction.scala b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbCompaction.scala index b6e4a2b0f0..6258496457 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbCompaction.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbCompaction.scala @@ -17,13 +17,13 @@ private[persistence] object LeveldbCompaction { * Exposure of LevelDB compaction capability to reduce journal size upon message deletions. */ private[persistence] trait LeveldbCompaction extends Actor with ActorLogging with CompactionSegmentManagement { - this: LeveldbStore ⇒ + this: LeveldbStore => import Key._ import LeveldbCompaction._ def receiveCompactionInternal: Receive = { - case TryCompactLeveldb(persistenceId, toSeqNr) ⇒ + case TryCompactLeveldb(persistenceId, toSeqNr) => tryCompactOnDelete(persistenceId, toSeqNr) } @@ -68,7 +68,7 @@ private[persistence] trait CompactionSegmentManagement { def compactionIntervals: Map[String, Long] def updateCompactionSegment(persistenceId: String, compactionSegment: Long): Unit = { - latestCompactionSegments += persistenceId → compactionSegment + latestCompactionSegments += persistenceId -> compactionSegment } def compactionLimit(persistenceId: String, toSeqNr: Long): Long = { diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbIdMapping.scala b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbIdMapping.scala index 42c838e812..db0bda80ed 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbIdMapping.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbIdMapping.scala @@ -14,7 +14,7 @@ import akka.util.ByteString.UTF_8 * * LevelDB backed persistent mapping of `String`-based persistent actor ids to numeric ids. */ -private[persistence] trait LeveldbIdMapping extends Actor { this: LeveldbStore ⇒ +private[persistence] trait LeveldbIdMapping extends Actor { this: LeveldbStore => import Key._ private val idOffset = 10 @@ -31,8 +31,8 @@ private[persistence] trait LeveldbIdMapping extends Actor { this: LeveldbStore */ def numericId(id: String): Int = idMapLock.synchronized { idMap.get(id) match { - case None ⇒ writeIdMapping(id, idMap.size + idOffset) - case Some(v) ⇒ v + case None => writeIdMapping(id, idMap.size + idOffset) + case Some(v) => v } } @@ -44,7 +44,7 @@ private[persistence] trait LeveldbIdMapping extends Actor { this: LeveldbStore idMap.keySet } - private def readIdMap(): Map[String, Int] = withIterator { iter ⇒ + private def readIdMap(): Map[String, Int] = withIterator { iter => iter.seek(keyToBytes(mappingKey(idOffset))) readIdMap(Map.empty, iter) } @@ -55,13 +55,13 @@ private[persistence] trait LeveldbIdMapping extends Actor { this: LeveldbStore val nextKey = keyFromBytes(nextEntry.getKey) if (!isMappingKey(nextKey)) pathMap else { val nextVal = new String(nextEntry.getValue, UTF_8) - readIdMap(pathMap + (nextVal → nextKey.mappingId), iter) + readIdMap(pathMap + (nextVal -> nextKey.mappingId), iter) } } } private def writeIdMapping(id: String, numericId: Int): Int = { - idMap = idMap + (id → numericId) + idMap = idMap + (id -> numericId) leveldb.put(keyToBytes(mappingKey(numericId)), id.getBytes(UTF_8)) newPersistenceIdAdded(id) numericId diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbJournal.scala b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbJournal.scala index 7b16c7231c..f0315cddde 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbJournal.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbJournal.scala @@ -31,38 +31,38 @@ private[persistence] class LeveldbJournal(cfg: Config) extends AsyncWriteJournal else context.system.settings.config.getConfig("akka.persistence.journal.leveldb") override def receivePluginInternal: Receive = receiveCompactionInternal orElse { - case r @ ReplayTaggedMessages(fromSequenceNr, toSequenceNr, max, tag, replyTo) ⇒ + case r @ ReplayTaggedMessages(fromSequenceNr, toSequenceNr, max, tag, replyTo) => import context.dispatcher val readHighestSequenceNrFrom = math.max(0L, fromSequenceNr - 1) asyncReadHighestSequenceNr(tagAsPersistenceId(tag), readHighestSequenceNrFrom) - .flatMap { highSeqNr ⇒ + .flatMap { highSeqNr => val toSeqNr = math.min(toSequenceNr, highSeqNr) if (highSeqNr == 0L || fromSequenceNr > toSeqNr) Future.successful(highSeqNr) else { asyncReplayTaggedMessages(tag, fromSequenceNr, toSeqNr, max) { - case ReplayedTaggedMessage(p, tag, offset) ⇒ - adaptFromJournal(p).foreach { adaptedPersistentRepr ⇒ + case ReplayedTaggedMessage(p, tag, offset) => + adaptFromJournal(p).foreach { adaptedPersistentRepr => replyTo.tell(ReplayedTaggedMessage(adaptedPersistentRepr, tag, offset), Actor.noSender) } - }.map(_ ⇒ highSeqNr) + }.map(_ => highSeqNr) } }.map { - highSeqNr ⇒ RecoverySuccess(highSeqNr) + highSeqNr => RecoverySuccess(highSeqNr) }.recover { - case e ⇒ ReplayMessagesFailure(e) + case e => ReplayMessagesFailure(e) }.pipeTo(replyTo) - case SubscribePersistenceId(persistenceId: String) ⇒ + case SubscribePersistenceId(persistenceId: String) => addPersistenceIdSubscriber(sender(), persistenceId) context.watch(sender()) - case SubscribeAllPersistenceIds ⇒ + case SubscribeAllPersistenceIds => addAllPersistenceIdsSubscriber(sender()) context.watch(sender()) - case SubscribeTag(tag: String) ⇒ + case SubscribeTag(tag: String) => addTagSubscriber(sender(), tag) context.watch(sender()) - case Terminated(ref) ⇒ + case Terminated(ref) => removeSubscriber(ref) } } @@ -121,11 +121,11 @@ private[persistence] class SharedLeveldbJournal extends AsyncWriteProxy { "akka.persistence.journal.leveldb-shared.timeout") override def receivePluginInternal: Receive = { - case cmd: LeveldbJournal.SubscriptionCommand ⇒ + case cmd: LeveldbJournal.SubscriptionCommand => // forward subscriptions, they are used by query-side store match { - case Some(s) ⇒ s.forward(cmd) - case None ⇒ + case Some(s) => s.forward(cmd) + case None => log.error("Failed {} request. " + "Store not initialized. Use `SharedLeveldbJournal.setStore(sharedStore, system)`", cmd) } diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbRecovery.scala b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbRecovery.scala index 99e0071c44..207c561370 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbRecovery.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbRecovery.scala @@ -15,7 +15,7 @@ import akka.persistence.journal.leveldb.LeveldbJournal.ReplayedTaggedMessage * * LevelDB backed message replay and sequence number recovery. */ -private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: LeveldbStore ⇒ +private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: LeveldbStore => import Key._ private lazy val replayDispatcherId = config.getString("replay-dispatcher") @@ -26,14 +26,14 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb Future(readHighestSequenceNr(nid))(replayDispatcher) } - def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: PersistentRepr ⇒ Unit): Future[Unit] = { + def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: PersistentRepr => Unit): Future[Unit] = { val nid = numericId(persistenceId) Future(replayMessages(nid, fromSequenceNr: Long, toSequenceNr, max: Long)(replayCallback))(replayDispatcher) } - def replayMessages(persistenceId: Int, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: PersistentRepr ⇒ Unit): Unit = { + def replayMessages(persistenceId: Int, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: PersistentRepr => Unit): Unit = { @scala.annotation.tailrec - def go(iter: DBIterator, key: Key, ctr: Long, replayCallback: PersistentRepr ⇒ Unit): Unit = { + def go(iter: DBIterator, key: Key, ctr: Long, replayCallback: PersistentRepr => Unit): Unit = { if (iter.hasNext) { val nextEntry = iter.next() val nextKey = keyFromBytes(nextEntry.getKey) @@ -66,23 +66,23 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb } else false } - withIterator { iter ⇒ + withIterator { iter => val startKey = Key(persistenceId, if (fromSequenceNr < 1L) 1L else fromSequenceNr, 0) iter.seek(keyToBytes(startKey)) go(iter, startKey, 0L, replayCallback) } } - def asyncReplayTaggedMessages(tag: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: ReplayedTaggedMessage ⇒ Unit): Future[Unit] = { + def asyncReplayTaggedMessages(tag: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: ReplayedTaggedMessage => Unit): Future[Unit] = { val tagNid = tagNumericId(tag) Future(replayTaggedMessages(tag, tagNid, fromSequenceNr: Long, toSequenceNr, max: Long)(replayCallback))(replayDispatcher) } def replayTaggedMessages(tag: String, tagNid: Int, fromSequenceNr: Long, toSequenceNr: Long, max: Long)( - replayCallback: ReplayedTaggedMessage ⇒ Unit): Unit = { + replayCallback: ReplayedTaggedMessage => Unit): Unit = { @scala.annotation.tailrec - def go(iter: DBIterator, key: Key, ctr: Long, replayCallback: ReplayedTaggedMessage ⇒ Unit): Unit = { + def go(iter: DBIterator, key: Key, ctr: Long, replayCallback: ReplayedTaggedMessage => Unit): Unit = { if (iter.hasNext) { val nextEntry = iter.next() val nextKey = keyFromBytes(nextEntry.getKey) @@ -98,7 +98,7 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb } } - withIterator { iter ⇒ + withIterator { iter => // fromSequenceNr is exclusive, i.e. start with +1 val startKey = Key(tagNid, if (fromSequenceNr < 1L) 1L else fromSequenceNr + 1, 0) iter.seek(keyToBytes(startKey)) @@ -110,8 +110,8 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb val ro = leveldbSnapshot() try { leveldb.get(keyToBytes(counterKey(persistenceId)), ro) match { - case null ⇒ 0L - case bytes ⇒ counterFromBytes(bytes) + case null => 0L + case bytes => counterFromBytes(bytes) } } finally { ro.snapshot().close() diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbStore.scala b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbStore.scala index a13d09efbf..88c137c2d3 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbStore.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/LeveldbStore.scala @@ -25,7 +25,7 @@ private[persistence] object LeveldbStore { val emptyConfig = ConfigFactory.empty() def toCompactionIntervalMap(obj: ConfigObject): Map[String, Long] = { - obj.unwrapped().asScala.map(entry ⇒ (entry._1, java.lang.Long.parseLong(entry._2.toString))).toMap + obj.unwrapped().asScala.map(entry => (entry._1, java.lang.Long.parseLong(entry._2.toString))).toMap } } @@ -66,13 +66,13 @@ private[persistence] trait LeveldbStore extends Actor with WriteJournalBase with var allTags = Set.empty[String] val result = Future.fromTry(Try { - withBatch(batch ⇒ messages.map { a ⇒ + withBatch(batch => messages.map { a => Try { - a.payload.foreach { p ⇒ + a.payload.foreach { p => val (p2, tags) = p.payload match { - case Tagged(payload, tags) ⇒ + case Tagged(payload, tags) => (p.withPayload(payload), tags) - case _ ⇒ (p, Set.empty[String]) + case _ => (p, Set.empty[String]) } if (tags.nonEmpty && hasTagSubscribers) allTags = allTags union tags @@ -89,7 +89,7 @@ private[persistence] trait LeveldbStore extends Actor with WriteJournalBase with }) if (hasPersistenceIdSubscribers) { - persistenceIds.foreach { pid ⇒ + persistenceIds.foreach { pid => notifyPersistenceIdChange(pid) } } @@ -100,11 +100,11 @@ private[persistence] trait LeveldbStore extends Actor with WriteJournalBase with def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = try Future.successful { - withBatch { batch ⇒ + withBatch { batch => val nid = numericId(persistenceId) // seek to first existing message - val fromSequenceNr = withIterator { iter ⇒ + val fromSequenceNr = withIterator { iter => val startKey = Key(nid, 1L, 0) iter.seek(keyToBytes(startKey)) if (iter.hasNext) keyFromBytes(iter.peekNext().getKey).sequenceNr else Long.MaxValue @@ -122,12 +122,12 @@ private[persistence] trait LeveldbStore extends Actor with WriteJournalBase with } } } catch { - case NonFatal(e) ⇒ Future.failed(e) + case NonFatal(e) => Future.failed(e) } def leveldbSnapshot(): ReadOptions = leveldbReadOptions.snapshot(leveldb.getSnapshot) - def withIterator[R](body: DBIterator ⇒ R): R = { + def withIterator[R](body: DBIterator => R): R = { val ro = leveldbSnapshot() val iterator = leveldb.iterator(ro) try { @@ -138,7 +138,7 @@ private[persistence] trait LeveldbStore extends Actor with WriteJournalBase with } } - def withBatch[R](body: WriteBatch ⇒ R): R = { + def withBatch[R](body: WriteBatch => R): R = { val batch = leveldb.createWriteBatch() try { val r = body(batch) @@ -158,7 +158,7 @@ private[persistence] trait LeveldbStore extends Actor with WriteJournalBase with batch.put(keyToBytes(counterKey(nid)), counterToBytes(persistent.sequenceNr)) batch.put(keyToBytes(Key(nid, persistent.sequenceNr, 0)), persistentBytes) - tags.foreach { tag ⇒ + tags.foreach { tag => val tagNid = tagNumericId(tag) val tagSeqNr = nextTagSequenceNr(tag) batch.put(keyToBytes(counterKey(tagNid)), counterToBytes(tagSeqNr)) @@ -168,8 +168,8 @@ private[persistence] trait LeveldbStore extends Actor with WriteJournalBase with private def nextTagSequenceNr(tag: String): Long = { val n = tagSequenceNr.get(tag) match { - case Some(n) ⇒ n - case None ⇒ readHighestSequenceNr(tagNumericId(tag)) + case Some(n) => n + case None => readHighestSequenceNr(tagNumericId(tag)) } tagSequenceNr = tagSequenceNr.updated(tag, n + 1) n + 1 @@ -197,11 +197,11 @@ private[persistence] trait LeveldbStore extends Actor with WriteJournalBase with persistenceIdSubscribers.addBinding(persistenceId, subscriber) protected def removeSubscriber(subscriber: ActorRef): Unit = { - val keys = persistenceIdSubscribers.collect { case (k, s) if s.contains(subscriber) ⇒ k } - keys.foreach { key ⇒ persistenceIdSubscribers.removeBinding(key, subscriber) } + val keys = persistenceIdSubscribers.collect { case (k, s) if s.contains(subscriber) => k } + keys.foreach { key => persistenceIdSubscribers.removeBinding(key, subscriber) } - val tagKeys = tagSubscribers.collect { case (k, s) if s.contains(subscriber) ⇒ k } - tagKeys.foreach { key ⇒ tagSubscribers.removeBinding(key, subscriber) } + val tagKeys = tagSubscribers.collect { case (k, s) if s.contains(subscriber) => k } + tagKeys.foreach { key => tagSubscribers.removeBinding(key, subscriber) } allPersistenceIdsSubscribers -= subscriber } diff --git a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/SharedLeveldbStore.scala b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/SharedLeveldbStore.scala index 6baff6c202..7ee8c8d6bc 100644 --- a/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/SharedLeveldbStore.scala +++ b/akka-persistence/src/main/scala/akka/persistence/journal/leveldb/SharedLeveldbStore.scala @@ -30,19 +30,19 @@ class SharedLeveldbStore(cfg: Config) extends LeveldbStore { else context.system.settings.config.getConfig("akka.persistence.journal.leveldb-shared.store") def receive = receiveCompactionInternal orElse { - case WriteMessages(messages) ⇒ + case WriteMessages(messages) => // TODO it would be nice to DRY this with AsyncWriteJournal, but this is using // AsyncWriteProxy message protocol val atomicWriteCount = messages.count(_.isInstanceOf[AtomicWrite]) val prepared = Try(preparePersistentBatch(messages)) val writeResult = (prepared match { - case Success(prep) ⇒ + case Success(prep) => // in case the asyncWriteMessages throws - try asyncWriteMessages(prep) catch { case NonFatal(e) ⇒ Future.failed(e) } - case f @ Failure(_) ⇒ + try asyncWriteMessages(prep) catch { case NonFatal(e) => Future.failed(e) } + case f @ Failure(_) => // exception from preparePersistentBatch => rejected - Future.successful(messages.collect { case a: AtomicWrite ⇒ f }) - }).map { results ⇒ + Future.successful(messages.collect { case a: AtomicWrite => f }) + }).map { results => if (results.nonEmpty && results.size != atomicWriteCount) throw new IllegalStateException("asyncWriteMessages returned invalid number of results. " + s"Expected [${prepared.get.size}], but got [${results.size}]") @@ -51,28 +51,28 @@ class SharedLeveldbStore(cfg: Config) extends LeveldbStore { writeResult.pipeTo(sender()) - case DeleteMessagesTo(pid, tsnr) ⇒ + case DeleteMessagesTo(pid, tsnr) => asyncDeleteMessagesTo(pid, tsnr).pipeTo(sender()) - case ReplayMessages(persistenceId, fromSequenceNr, toSequenceNr, max) ⇒ + case ReplayMessages(persistenceId, fromSequenceNr, toSequenceNr, max) => // TODO it would be nice to DRY this with AsyncWriteJournal, but this is using // AsyncWriteProxy message protocol val replyTo = sender() val readHighestSequenceNrFrom = math.max(0L, fromSequenceNr - 1) - asyncReadHighestSequenceNr(persistenceId, readHighestSequenceNrFrom).flatMap { highSeqNr ⇒ + asyncReadHighestSequenceNr(persistenceId, readHighestSequenceNrFrom).flatMap { highSeqNr => if (highSeqNr == 0L || max == 0L) Future.successful(highSeqNr) else { val toSeqNr = math.min(toSequenceNr, highSeqNr) - asyncReplayMessages(persistenceId, fromSequenceNr, toSeqNr, max) { p ⇒ + asyncReplayMessages(persistenceId, fromSequenceNr, toSeqNr, max) { p => if (!p.deleted) // old records from 2.3 may still have the deleted flag adaptFromJournal(p).foreach(replyTo ! _) - }.map(_ ⇒ highSeqNr) + }.map(_ => highSeqNr) } }.map { - highSeqNr ⇒ ReplaySuccess(highSeqNr) + highSeqNr => ReplaySuccess(highSeqNr) }.recover { - case e ⇒ ReplayFailure(e) + case e => ReplayFailure(e) }.pipeTo(replyTo) } } diff --git a/akka-persistence/src/main/scala/akka/persistence/serialization/MessageSerializer.scala b/akka-persistence/src/main/scala/akka/persistence/serialization/MessageSerializer.scala index 530eb3060d..08925aa4a3 100644 --- a/akka-persistence/src/main/scala/akka/persistence/serialization/MessageSerializer.scala +++ b/akka-persistence/src/main/scala/akka/persistence/serialization/MessageSerializer.scala @@ -8,7 +8,7 @@ import akka.actor.{ ActorPath, ExtendedActorSystem } import akka.persistence.AtLeastOnceDelivery._ import akka.persistence._ import akka.persistence.fsm.PersistentFSM.{ PersistentFSMSnapshot, StateChangeEvent } -import akka.persistence.serialization.{ MessageFormats ⇒ mf } +import akka.persistence.serialization.{ MessageFormats => mf } import akka.serialization._ import akka.protobuf._ import scala.collection.immutable @@ -46,12 +46,12 @@ class MessageSerializer(val system: ExtendedActorSystem) extends BaseSerializer * message's payload to a matching `akka.serialization.Serializer`. */ def toBinary(o: AnyRef): Array[Byte] = o match { - case p: PersistentRepr ⇒ persistentMessageBuilder(p).build().toByteArray - case a: AtomicWrite ⇒ atomicWriteBuilder(a).build().toByteArray - case a: AtLeastOnceDeliverySnapshot ⇒ atLeastOnceDeliverySnapshotBuilder(a).build.toByteArray - case s: StateChangeEvent ⇒ stateChangeBuilder(s).build.toByteArray - case p: PersistentFSMSnapshot[Any] ⇒ persistentFSMSnapshotBuilder(p).build.toByteArray - case _ ⇒ throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass}") + case p: PersistentRepr => persistentMessageBuilder(p).build().toByteArray + case a: AtomicWrite => atomicWriteBuilder(a).build().toByteArray + case a: AtLeastOnceDeliverySnapshot => atLeastOnceDeliverySnapshotBuilder(a).build.toByteArray + case s: StateChangeEvent => stateChangeBuilder(s).build.toByteArray + case p: PersistentFSMSnapshot[Any] => persistentFSMSnapshotBuilder(p).build.toByteArray + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass}") } /** @@ -59,15 +59,15 @@ class MessageSerializer(val system: ExtendedActorSystem) extends BaseSerializer * message's payload to a matching `akka.serialization.Serializer`. */ def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): Message = manifest match { - case None ⇒ persistent(mf.PersistentMessage.parseFrom(bytes)) - case Some(c) ⇒ c match { - case PersistentImplClass ⇒ persistent(mf.PersistentMessage.parseFrom(bytes)) - case PersistentReprClass ⇒ persistent(mf.PersistentMessage.parseFrom(bytes)) - case AtomicWriteClass ⇒ atomicWrite(mf.AtomicWrite.parseFrom(bytes)) - case AtLeastOnceDeliverySnapshotClass ⇒ atLeastOnceDeliverySnapshot(mf.AtLeastOnceDeliverySnapshot.parseFrom(bytes)) - case PersistentStateChangeEventClass ⇒ stateChange(mf.PersistentStateChangeEvent.parseFrom(bytes)) - case PersistentFSMSnapshotClass ⇒ persistentFSMSnapshot(mf.PersistentFSMSnapshot.parseFrom(bytes)) - case _ ⇒ throw new NotSerializableException(s"Can't deserialize object of type ${c}") + case None => persistent(mf.PersistentMessage.parseFrom(bytes)) + case Some(c) => c match { + case PersistentImplClass => persistent(mf.PersistentMessage.parseFrom(bytes)) + case PersistentReprClass => persistent(mf.PersistentMessage.parseFrom(bytes)) + case AtomicWriteClass => atomicWrite(mf.AtomicWrite.parseFrom(bytes)) + case AtLeastOnceDeliverySnapshotClass => atLeastOnceDeliverySnapshot(mf.AtLeastOnceDeliverySnapshot.parseFrom(bytes)) + case PersistentStateChangeEventClass => stateChange(mf.PersistentStateChangeEvent.parseFrom(bytes)) + case PersistentFSMSnapshotClass => persistentFSMSnapshot(mf.PersistentFSMSnapshot.parseFrom(bytes)) + case _ => throw new NotSerializableException(s"Can't deserialize object of type ${c}") } } @@ -78,7 +78,7 @@ class MessageSerializer(val system: ExtendedActorSystem) extends BaseSerializer def atLeastOnceDeliverySnapshotBuilder(snap: AtLeastOnceDeliverySnapshot): mf.AtLeastOnceDeliverySnapshot.Builder = { val builder = mf.AtLeastOnceDeliverySnapshot.newBuilder builder.setCurrentDeliveryId(snap.currentDeliveryId) - snap.unconfirmedDeliveries.foreach { unconfirmed ⇒ + snap.unconfirmedDeliveries.foreach { unconfirmed => val unconfirmedBuilder = mf.AtLeastOnceDeliverySnapshot.UnconfirmedDelivery.newBuilder. setDeliveryId(unconfirmed.deliveryId). @@ -92,8 +92,8 @@ class MessageSerializer(val system: ExtendedActorSystem) extends BaseSerializer private[persistence] def stateChangeBuilder(stateChange: StateChangeEvent): mf.PersistentStateChangeEvent.Builder = { val builder = mf.PersistentStateChangeEvent.newBuilder.setStateIdentifier(stateChange.stateIdentifier) stateChange.timeout match { - case None ⇒ builder - case Some(timeout) ⇒ builder.setTimeoutNanos(timeout.toNanos) + case None => builder + case Some(timeout) => builder.setTimeoutNanos(timeout.toNanos) } } @@ -102,15 +102,15 @@ class MessageSerializer(val system: ExtendedActorSystem) extends BaseSerializer .setStateIdentifier(persistentFSMSnapshot.stateIdentifier) .setData(persistentPayloadBuilder(persistentFSMSnapshot.data.asInstanceOf[AnyRef])) persistentFSMSnapshot.timeout match { - case None ⇒ builder - case Some(timeout) ⇒ builder.setTimeoutNanos(timeout.toNanos) + case None => builder + case Some(timeout) => builder.setTimeoutNanos(timeout.toNanos) } } def atLeastOnceDeliverySnapshot(atLeastOnceDeliverySnapshot: mf.AtLeastOnceDeliverySnapshot): AtLeastOnceDeliverySnapshot = { import scala.collection.JavaConverters._ val unconfirmedDeliveries = new VectorBuilder[UnconfirmedDelivery]() - atLeastOnceDeliverySnapshot.getUnconfirmedDeliveriesList().iterator().asScala foreach { next ⇒ + atLeastOnceDeliverySnapshot.getUnconfirmedDeliveriesList().iterator().asScala foreach { next => unconfirmedDeliveries += UnconfirmedDelivery(next.getDeliveryId, ActorPath.fromString(next.getDestination), payload(next.getPayload)) } @@ -138,7 +138,7 @@ class MessageSerializer(val system: ExtendedActorSystem) extends BaseSerializer private def atomicWriteBuilder(a: AtomicWrite) = { val builder = mf.AtomicWrite.newBuilder - a.payload.foreach { p ⇒ + a.payload.foreach { p => builder.addPayload(persistentMessageBuilder(p)) } builder diff --git a/akka-persistence/src/main/scala/akka/persistence/serialization/SnapshotSerializer.scala b/akka-persistence/src/main/scala/akka/persistence/serialization/SnapshotSerializer.scala index fae2a366b4..14cb15a8b7 100644 --- a/akka-persistence/src/main/scala/akka/persistence/serialization/SnapshotSerializer.scala +++ b/akka-persistence/src/main/scala/akka/persistence/serialization/SnapshotSerializer.scala @@ -38,8 +38,8 @@ class SnapshotSerializer(val system: ExtendedActorSystem) extends BaseSerializer * `akka.serialization.Serializer`. */ def toBinary(o: AnyRef): Array[Byte] = o match { - case Snapshot(data) ⇒ snapshotToBinary(data.asInstanceOf[AnyRef]) - case _ ⇒ throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass}") + case Snapshot(data) => snapshotToBinary(data.asInstanceOf[AnyRef]) + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass}") } /** diff --git a/akka-persistence/src/main/scala/akka/persistence/snapshot/SnapshotStore.scala b/akka-persistence/src/main/scala/akka/persistence/snapshot/SnapshotStore.scala index 0af5f5016e..880a077af1 100644 --- a/akka-persistence/src/main/scala/akka/persistence/snapshot/SnapshotStore.scala +++ b/akka-persistence/src/main/scala/akka/persistence/snapshot/SnapshotStore.scala @@ -32,59 +32,59 @@ trait SnapshotStore extends Actor with ActorLogging { final def receive = receiveSnapshotStore.orElse[Any, Unit](receivePluginInternal) final val receiveSnapshotStore: Actor.Receive = { - case LoadSnapshot(persistenceId, criteria, toSequenceNr) ⇒ + case LoadSnapshot(persistenceId, criteria, toSequenceNr) => if (criteria == SnapshotSelectionCriteria.None) { senderPersistentActor() ! LoadSnapshotResult(snapshot = None, toSequenceNr) } else { breaker.withCircuitBreaker(loadAsync(persistenceId, criteria.limit(toSequenceNr))) map { - sso ⇒ LoadSnapshotResult(sso, toSequenceNr) + sso => LoadSnapshotResult(sso, toSequenceNr) } recover { - case e ⇒ LoadSnapshotFailed(e) + case e => LoadSnapshotFailed(e) } pipeTo senderPersistentActor() } - case SaveSnapshot(metadata, snapshot) ⇒ + case SaveSnapshot(metadata, snapshot) => val md = metadata.copy(timestamp = System.currentTimeMillis) breaker.withCircuitBreaker(saveAsync(md, snapshot)) map { - _ ⇒ SaveSnapshotSuccess(md) + _ => SaveSnapshotSuccess(md) } recover { - case e ⇒ SaveSnapshotFailure(metadata, e) + case e => SaveSnapshotFailure(metadata, e) } to (self, senderPersistentActor()) - case evt: SaveSnapshotSuccess ⇒ + case evt: SaveSnapshotSuccess => try tryReceivePluginInternal(evt) finally senderPersistentActor ! evt // sender is persistentActor - case evt @ SaveSnapshotFailure(metadata, _) ⇒ + case evt @ SaveSnapshotFailure(metadata, _) => try { tryReceivePluginInternal(evt) breaker.withCircuitBreaker(deleteAsync(metadata)) } finally senderPersistentActor() ! evt // sender is persistentActor - case d @ DeleteSnapshot(metadata) ⇒ + case d @ DeleteSnapshot(metadata) => breaker.withCircuitBreaker(deleteAsync(metadata)).map { - case _ ⇒ DeleteSnapshotSuccess(metadata) + case _ => DeleteSnapshotSuccess(metadata) }.recover { - case e ⇒ DeleteSnapshotFailure(metadata, e) + case e => DeleteSnapshotFailure(metadata, e) }.pipeTo(self)(senderPersistentActor()).onComplete { - case _ ⇒ if (publish) context.system.eventStream.publish(d) + case _ => if (publish) context.system.eventStream.publish(d) } - case evt: DeleteSnapshotSuccess ⇒ + case evt: DeleteSnapshotSuccess => try tryReceivePluginInternal(evt) finally senderPersistentActor() ! evt - case evt: DeleteSnapshotFailure ⇒ + case evt: DeleteSnapshotFailure => try tryReceivePluginInternal(evt) finally senderPersistentActor() ! evt - case d @ DeleteSnapshots(persistenceId, criteria) ⇒ + case d @ DeleteSnapshots(persistenceId, criteria) => breaker.withCircuitBreaker(deleteAsync(persistenceId, criteria)).map { - case _ ⇒ DeleteSnapshotsSuccess(criteria) + case _ => DeleteSnapshotsSuccess(criteria) }.recover { - case e ⇒ DeleteSnapshotsFailure(criteria, e) + case e => DeleteSnapshotsFailure(criteria, e) }.pipeTo(self)(senderPersistentActor()).onComplete { - case _ ⇒ if (publish) context.system.eventStream.publish(d) + case _ => if (publish) context.system.eventStream.publish(d) } - case evt: DeleteSnapshotsFailure ⇒ + case evt: DeleteSnapshotsFailure => try tryReceivePluginInternal(evt) finally senderPersistentActor() ! evt // sender is persistentActor - case evt: DeleteSnapshotsSuccess ⇒ + case evt: DeleteSnapshotsSuccess => try tryReceivePluginInternal(evt) finally senderPersistentActor() ! evt } diff --git a/akka-persistence/src/main/scala/akka/persistence/snapshot/japi/SnapshotStore.scala b/akka-persistence/src/main/scala/akka/persistence/snapshot/japi/SnapshotStore.scala index 74e14ae2bb..99dbaf1e60 100644 --- a/akka-persistence/src/main/scala/akka/persistence/snapshot/japi/SnapshotStore.scala +++ b/akka-persistence/src/main/scala/akka/persistence/snapshot/japi/SnapshotStore.scala @@ -5,7 +5,7 @@ package akka.persistence.snapshot.japi import akka.persistence._ -import akka.persistence.snapshot.{ SnapshotStore ⇒ SSnapshotStore } +import akka.persistence.snapshot.{ SnapshotStore => SSnapshotStore } import akka.japi.Util._ import scala.concurrent.Future @@ -23,9 +23,9 @@ abstract class SnapshotStore extends SSnapshotStore with SnapshotStorePlugin { doSaveAsync(metadata, snapshot).map(Unit.unbox) override final def deleteAsync(metadata: SnapshotMetadata): Future[Unit] = - doDeleteAsync(metadata).map(_ ⇒ ()) + doDeleteAsync(metadata).map(_ => ()) override final def deleteAsync(persistenceId: String, criteria: SnapshotSelectionCriteria): Future[Unit] = - doDeleteAsync(persistenceId: String, criteria: SnapshotSelectionCriteria).map(_ ⇒ ()) + doDeleteAsync(persistenceId: String, criteria: SnapshotSelectionCriteria).map(_ => ()) } diff --git a/akka-persistence/src/main/scala/akka/persistence/snapshot/local/LocalSnapshotStore.scala b/akka-persistence/src/main/scala/akka/persistence/snapshot/local/LocalSnapshotStore.scala index e28c526bd1..02ce066c4d 100644 --- a/akka-persistence/src/main/scala/akka/persistence/snapshot/local/LocalSnapshotStore.scala +++ b/akka-persistence/src/main/scala/akka/persistence/snapshot/local/LocalSnapshotStore.scala @@ -51,8 +51,8 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt val metadata = snapshotMetadatas(persistenceId, criteria).sorted.takeRight(maxLoadAttempts) Future { load(metadata) match { - case Success(s) ⇒ s - case Failure(e) ⇒ throw e // all attempts failed, fail the future + case Success(s) => s + case Failure(e) => throw e // all attempts failed, fail the future } }(streamDispatcher) } @@ -70,21 +70,21 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt // usually snapshot-stores would keep one snapshot per sequenceNr however here in the file-based one we timestamp // snapshots and allow multiple to be kept around (for the same seqNr) if desired snapshotFiles(metadata).map(_.delete()) - }(streamDispatcher).map(_ ⇒ ())(streamDispatcher) + }(streamDispatcher).map(_ => ())(streamDispatcher) } override def deleteAsync(persistenceId: String, criteria: SnapshotSelectionCriteria): Future[Unit] = { val metadatas = snapshotMetadatas(persistenceId, criteria) Future.sequence { metadatas.map(deleteAsync) - }(scala.collection.immutable.IndexedSeq, streamDispatcher).map(_ ⇒ ())(streamDispatcher) + }(scala.collection.immutable.IndexedSeq, streamDispatcher).map(_ => ())(streamDispatcher) } override def receivePluginInternal: Receive = { - case SaveSnapshotSuccess(metadata) ⇒ saving -= metadata - case _: SaveSnapshotFailure ⇒ // ignore - case _: DeleteSnapshotsSuccess ⇒ // ignore - case _: DeleteSnapshotsFailure ⇒ // ignore + case SaveSnapshotSuccess(metadata) => saving -= metadata + case _: SaveSnapshotFailure => // ignore + case _: DeleteSnapshotsSuccess => // ignore + case _: DeleteSnapshotsFailure => // ignore } private def snapshotFiles(metadata: SnapshotMetadata): immutable.Seq[File] = { @@ -93,12 +93,12 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt @scala.annotation.tailrec private def load(metadata: immutable.Seq[SnapshotMetadata]): Try[Option[SelectedSnapshot]] = metadata.lastOption match { - case None ⇒ Success(None) // no snapshots stored - case Some(md) ⇒ + case None => Success(None) // no snapshots stored + case Some(md) => Try(withInputStream(md)(deserialize)) match { - case Success(s) ⇒ + case Success(s) => Success(Some(SelectedSnapshot(md, s.data))) - case Failure(e) ⇒ + case Failure(e) => val remaining = metadata.init log.error(e, s"Error loading snapshot [{}], remaining attempts: [{}]", md, remaining.size) if (remaining.isEmpty) @@ -120,16 +120,16 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt outputStream.write(serializationExtension.serialize(snapshot).get) } - protected def withOutputStream(metadata: SnapshotMetadata)(p: (OutputStream) ⇒ Unit): File = { + protected def withOutputStream(metadata: SnapshotMetadata)(p: (OutputStream) => Unit): File = { val tmpFile = snapshotFileForWrite(metadata, extension = "tmp") withStream(new BufferedOutputStream(Files.newOutputStream(tmpFile.toPath())), p) tmpFile } - private def withInputStream[T](metadata: SnapshotMetadata)(p: (InputStream) ⇒ T): T = + private def withInputStream[T](metadata: SnapshotMetadata)(p: (InputStream) => T): T = withStream(new BufferedInputStream(Files.newInputStream(snapshotFileForWrite(metadata).toPath())), p) - private def withStream[A <: Closeable, B](stream: A, p: A ⇒ B): B = + private def withStream[A <: Closeable, B](stream: A, p: A => B): B = try { p(stream) } finally { stream.close() } /** Only by persistenceId and sequenceNr, timestamp is informational - accommodates for 2.13.x series files */ @@ -140,11 +140,11 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt val files = snapshotDir.listFiles(new SnapshotFilenameFilter(persistenceId)) if (files eq null) Nil // if the dir was removed else { - files.map(_.getName).flatMap { filename ⇒ + files.map(_.getName).flatMap { filename => extractMetadata(filename).map { - case (pid, snr, tms) ⇒ SnapshotMetadata(URLDecoder.decode(pid, UTF_8), snr, tms) + case (pid, snr, tms) => SnapshotMetadata(URLDecoder.decode(pid, UTF_8), snr, tms) } - }.filter(md ⇒ criteria.matches(md) && !saving.contains(md)).toVector + }.filter(md => criteria.matches(md) && !saving.contains(md)).toVector } } @@ -181,8 +181,8 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt def accept(dir: File, name: String): Boolean = name match { - case FilenamePattern(pid, snr, tms) ⇒ matches(pid, snr, tms) - case _ ⇒ false + case FilenamePattern(pid, snr, tms) => matches(pid, snr, tms) + case _ => false } } diff --git a/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliveryCrashSpec.scala b/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliveryCrashSpec.scala index 0423adc26e..d62b85710f 100644 --- a/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliveryCrashSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliveryCrashSpec.scala @@ -17,13 +17,13 @@ object AtLeastOnceDeliveryCrashSpec { import scala.concurrent.duration._ override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 10.seconds) { - case _: IllegalStateException ⇒ Stop - case t ⇒ super.supervisorStrategy.decider.applyOrElse(t, (_: Any) ⇒ Escalate) + case _: IllegalStateException => Stop + case t => super.supervisorStrategy.decider.applyOrElse(t, (_: Any) => Escalate) } val crashingActor = context.actorOf(Props(new CrashingActor(testProbe)), "CrashingActor") - def receive: Receive = { case msg ⇒ crashingActor forward msg } + def receive: Receive = { case msg => crashingActor forward msg } } object CrashingActor { @@ -39,20 +39,20 @@ object AtLeastOnceDeliveryCrashSpec { override def persistenceId = self.path.name override def receiveRecover: Receive = { - case Message ⇒ send() - case CrashMessage ⇒ + case Message => send() + case CrashMessage => log.debug("Crash it") throw new IllegalStateException("Intentionally crashed") with NoStackTrace - case msg ⇒ log.debug("Recover message: " + msg) + case msg => log.debug("Recover message: " + msg) } override def receiveCommand: Receive = { - case Message ⇒ persist(Message)(_ ⇒ send()) - case CrashMessage ⇒ persist(CrashMessage) { evt ⇒ } + case Message => persist(Message)(_ => send()) + case CrashMessage => persist(CrashMessage) { evt => } } def send() = { - deliver(testProbe.path) { id ⇒ SendingMessage(id, false) } + deliver(testProbe.path) { id => SendingMessage(id, false) } } } diff --git a/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliveryFailureSpec.scala b/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliveryFailureSpec.scala index 1f35791630..459bea4c95 100644 --- a/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliveryFailureSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliveryFailureSpec.scala @@ -44,7 +44,7 @@ object AtLeastOnceDeliveryFailureSpec { case class MsgSent(i: Int) extends Evt case class MsgConfirmed(deliveryId: Long, i: Int) extends Evt - trait ChaosSupport { this: Actor ⇒ + trait ChaosSupport { this: Actor => def random = ThreadLocalRandom.current def probe: ActorRef @@ -73,12 +73,12 @@ object AtLeastOnceDeliveryFailureSpec { override def persistenceId = "chaosSender" def receiveCommand: Receive = { - case i: Int ⇒ + case i: Int => if (contains(i)) { log.debug(debugMessage(s"ignored duplicate ${i}")) sender() ! Ack(i) } else { - persist(MsgSent(i)) { evt ⇒ + persist(MsgSent(i)) { evt => updateState(evt) sender() ! Ack(i) if (shouldFail(liveProcessingFailureRate)) @@ -89,11 +89,11 @@ object AtLeastOnceDeliveryFailureSpec { } - case Confirm(deliveryId, i) ⇒ persist(MsgConfirmed(deliveryId, i))(updateState) + case Confirm(deliveryId, i) => persist(MsgConfirmed(deliveryId, i))(updateState) } def receiveRecover: Receive = { - case evt: Evt ⇒ + case evt: Evt => updateState(evt) if (shouldFail(replayProcessingFailureRate)) throw new TestException(debugMessage(s"replay failed at event $evt")) @@ -102,11 +102,11 @@ object AtLeastOnceDeliveryFailureSpec { } def updateState(evt: Evt): Unit = evt match { - case MsgSent(i) ⇒ + case MsgSent(i) => add(i) - deliver(destination.path)(deliveryId ⇒ Msg(deliveryId, i)) + deliver(destination.path)(deliveryId => Msg(deliveryId, i)) - case MsgConfirmed(deliveryId, i) ⇒ + case MsgConfirmed(deliveryId, i) => confirmDelivery(deliveryId) } @@ -127,7 +127,7 @@ object AtLeastOnceDeliveryFailureSpec { val confirmFailureRate = config.getDouble("confirm-failure-rate") def receive = { - case m @ Msg(deliveryId, i) ⇒ + case m @ Msg(deliveryId, i) => if (shouldFail(confirmFailureRate)) { log.debug(debugMessage("confirm message failed", m)) } else if (contains(i)) { @@ -153,13 +153,13 @@ object AtLeastOnceDeliveryFailureSpec { context.watch(context.actorOf(Props(classOf[ChaosSender], destination, probe), "sender")) def receive = { - case Start ⇒ 1 to numMessages foreach (snd ! _) - case Ack(i) ⇒ acks += i - case Terminated(_) ⇒ + case Start => 1 to numMessages foreach (snd ! _) + case Ack(i) => acks += i + case Terminated(_) => // snd will be stopped if recovery or persist fails log.debug(s"sender stopped, starting it again") snd = createSender() - 1 to numMessages foreach (i ⇒ if (!acks(i)) snd ! i) + 1 to numMessages foreach (i => if (!acks(i)) snd ! i) } } } diff --git a/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliverySpec.scala b/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliverySpec.scala index 049e5c1037..4ca19fa577 100644 --- a/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliverySpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/AtLeastOnceDeliverySpec.scala @@ -54,69 +54,69 @@ object AtLeastOnceDeliverySpec { var lastSnapshotAskedForBy: Option[ActorRef] = None def updateState(evt: Evt): Unit = evt match { - case AcceptedReq(payload, destination) if actorSelectionDelivery ⇒ - log.debug(s"deliver(destination, deliveryId ⇒ Action(deliveryId, $payload)), recovery: " + recoveryRunning) - deliver(context.actorSelection(destination))(deliveryId ⇒ Action(deliveryId, payload)) + case AcceptedReq(payload, destination) if actorSelectionDelivery => + log.debug(s"deliver(destination, deliveryId => Action(deliveryId, $payload)), recovery: " + recoveryRunning) + deliver(context.actorSelection(destination))(deliveryId => Action(deliveryId, payload)) - case AcceptedReq(payload, destination) ⇒ - log.debug(s"deliver(destination, deliveryId ⇒ Action(deliveryId, $payload)), recovery: " + recoveryRunning) - deliver(destination)(deliveryId ⇒ Action(deliveryId, payload)) + case AcceptedReq(payload, destination) => + log.debug(s"deliver(destination, deliveryId => Action(deliveryId, $payload)), recovery: " + recoveryRunning) + deliver(destination)(deliveryId => Action(deliveryId, payload)) - case ReqDone(id) ⇒ + case ReqDone(id) => log.debug(s"confirmDelivery($id), recovery: " + recoveryRunning) confirmDelivery(id) } val receiveCommand: Receive = { - case Req(payload) ⇒ + case Req(payload) => if (payload.isEmpty) sender() ! InvalidReq else { val destination = destinations(payload.take(1).toUpperCase) if (async) - persistAsync(AcceptedReq(payload, destination)) { evt ⇒ + persistAsync(AcceptedReq(payload, destination)) { evt => updateState(evt) sender() ! ReqAck } else - persist(AcceptedReq(payload, destination)) { evt ⇒ + persist(AcceptedReq(payload, destination)) { evt => updateState(evt) sender() ! ReqAck } } - case ActionAck(id) ⇒ + case ActionAck(id) => log.debug("Sender got ack {}", id) if (confirmDelivery(id)) if (async) - persistAsync(ReqDone(id)) { evt ⇒ updateState(evt) } + persistAsync(ReqDone(id)) { evt => updateState(evt) } else - persist(ReqDone(id)) { evt ⇒ updateState(evt) } + persist(ReqDone(id)) { evt => updateState(evt) } - case Boom ⇒ + case Boom => log.debug("Boom!") throw new RuntimeException("boom") with NoStackTrace - case SaveSnap ⇒ + case SaveSnap => log.debug("Save snapshot!") lastSnapshotAskedForBy = Some(sender()) saveSnapshot(Snap(getDeliverySnapshot)) - case success: SaveSnapshotSuccess ⇒ + case success: SaveSnapshotSuccess => log.debug("Snapshot success!") lastSnapshotAskedForBy.map(_ ! success) - case w: UnconfirmedWarning ⇒ + case w: UnconfirmedWarning => log.debug("Sender got unconfirmed warning {}", w) testActor ! w } def receiveRecover: Receive = { - case evt: Evt ⇒ + case evt: Evt => updateState(evt) - case SnapshotOffer(_, Snap(deliverySnapshot)) ⇒ + case SnapshotOffer(_, Snap(deliverySnapshot)) => setDeliverySnapshot(deliverySnapshot) } } @@ -129,7 +129,7 @@ object AtLeastOnceDeliverySpec { var allReceived = Set.empty[Long] def receive = { - case a @ Action(id, payload) ⇒ + case a @ Action(id, payload) => // discard duplicates (naive impl) if (!allReceived.contains(id)) { log.debug("Destination got {}, all count {}", a, allReceived.size + 1) @@ -146,7 +146,7 @@ object AtLeastOnceDeliverySpec { class Unreliable(dropMod: Int, target: ActorRef) extends Actor with ActorLogging { var count = 0 def receive = { - case msg ⇒ + case msg => count += 1 if (count % dropMod != 0) { log.debug("Pass msg {} count {}", msg, count) @@ -161,10 +161,10 @@ object AtLeastOnceDeliverySpec { override def persistenceId = name override def receiveCommand = { - case any ⇒ + case any => // this is not supported currently, so expecting exception - try deliver(context.actorSelection("*"))(id ⇒ s"$any$id") - catch { case ex: Exception ⇒ sender() ! Failure(ex) } + try deliver(context.actorSelection("*"))(id => s"$any$id") + catch { case ex: Exception => sender() ! Failure(ex) } } override def receiveRecover = Actor.emptyBehavior @@ -176,12 +176,12 @@ abstract class AtLeastOnceDeliverySpec(config: Config) extends PersistenceSpec(c import akka.persistence.AtLeastOnceDeliverySpec._ "AtLeastOnceDelivery" must { - List(true, false).foreach { deliverUsingActorSelection ⇒ + List(true, false).foreach { deliverUsingActorSelection => s"deliver messages in order when nothing is lost (using actorSelection: $deliverUsingActorSelection)" taggedAs (TimingTest) in { val probe = TestProbe() val probeA = TestProbe() - val destinations = Map("A" → system.actorOf(destinationProps(probeA.ref)).path) + val destinations = Map("A" -> system.actorOf(destinationProps(probeA.ref)).path) val snd = system.actorOf(senderProps(probe.ref, name, 1000.millis, 5, 1000, destinations, async = false), name) snd.tell(Req("a"), probe.ref) probe.expectMsg(ReqAck) @@ -193,7 +193,7 @@ abstract class AtLeastOnceDeliverySpec(config: Config) extends PersistenceSpec(c val probe = TestProbe() val probeA = TestProbe() val dst = system.actorOf(destinationProps(probeA.ref)) - val destinations = Map("A" → system.actorOf(unreliableProps(3, dst)).path) + val destinations = Map("A" -> system.actorOf(unreliableProps(3, dst)).path) val snd = system.actorOf(senderProps(probe.ref, name, 2.seconds, 5, 1000, destinations, async = false, actorSelectionDelivery = deliverUsingActorSelection), name) snd.tell(Req("a-1"), probe.ref) probe.expectMsg(ReqAck) @@ -224,7 +224,7 @@ abstract class AtLeastOnceDeliverySpec(config: Config) extends PersistenceSpec(c val probe = TestProbe() val probeA = TestProbe() val dst = system.actorOf(destinationProps(probeA.ref)) - val destinations = Map("A" → system.actorOf(unreliableProps(3, dst)).path) + val destinations = Map("A" -> system.actorOf(unreliableProps(3, dst)).path) val snd = system.actorOf(senderProps(probe.ref, name, 2.seconds, 5, 1000, destinations, async = false), name) snd.tell(Req("a-1"), probe.ref) probe.expectMsg(ReqAck) @@ -258,7 +258,7 @@ abstract class AtLeastOnceDeliverySpec(config: Config) extends PersistenceSpec(c val probe = TestProbe() val probeA = TestProbe() val dst = system.actorOf(destinationProps(probeA.ref)) - val destinations = Map("A" → system.actorOf(unreliableProps(2, dst)).path) + val destinations = Map("A" -> system.actorOf(unreliableProps(2, dst)).path) val snd = system.actorOf(senderProps(probe.ref, name, 2.seconds, 5, 1000, destinations, async = false), name) snd.tell(Req("a-1"), probe.ref) probe.expectMsg(ReqAck) @@ -295,7 +295,7 @@ abstract class AtLeastOnceDeliverySpec(config: Config) extends PersistenceSpec(c val probe = TestProbe() val probeA = TestProbe() val dst = system.actorOf(destinationProps(probeA.ref)) - val destinations = Map("A" → system.actorOf(unreliableProps(3, dst)).path) + val destinations = Map("A" -> system.actorOf(unreliableProps(3, dst)).path) val snd = system.actorOf(senderProps(probe.ref, name, 2.seconds, 5, 1000, destinations, async = false), name) snd.tell(Req("a-1"), probe.ref) probe.expectMsg(ReqAck) @@ -333,7 +333,7 @@ abstract class AtLeastOnceDeliverySpec(config: Config) extends PersistenceSpec(c val probe = TestProbe() val probeA = TestProbe() val probeB = TestProbe() - val destinations = Map("A" → probeA.ref.path, "B" → probeB.ref.path) + val destinations = Map("A" -> probeA.ref.path, "B" -> probeB.ref.path) val snd = system.actorOf(senderProps(probe.ref, name, 1000.millis, 3, 1000, destinations, async = false), name) snd.tell(Req("a-1"), probe.ref) snd.tell(Req("b-1"), probe.ref) @@ -342,7 +342,7 @@ abstract class AtLeastOnceDeliverySpec(config: Config) extends PersistenceSpec(c probe.expectMsg(ReqAck) probe.expectMsg(ReqAck) val unconfirmed = probe.receiveWhile(5.seconds) { - case UnconfirmedWarning(unconfirmed) ⇒ unconfirmed + case UnconfirmedWarning(unconfirmed) => unconfirmed }.flatten unconfirmed.map(_.destination).toSet should ===(Set(probeA.ref.path, probeB.ref.path)) unconfirmed.map(_.message).toSet should be(Set(Action(1, "a-1"), Action(2, "b-1"), Action(3, "b-2"))) @@ -358,47 +358,47 @@ abstract class AtLeastOnceDeliverySpec(config: Config) extends PersistenceSpec(c val dstB = system.actorOf(destinationProps(probeB.ref), "destination-b") val dstC = system.actorOf(destinationProps(probeC.ref), "destination-c") val destinations = Map( - "A" → system.actorOf(unreliableProps(2, dstA), "unreliable-a").path, - "B" → system.actorOf(unreliableProps(5, dstB), "unreliable-b").path, - "C" → system.actorOf(unreliableProps(3, dstC), "unreliable-c").path) + "A" -> system.actorOf(unreliableProps(2, dstA), "unreliable-a").path, + "B" -> system.actorOf(unreliableProps(5, dstB), "unreliable-b").path, + "C" -> system.actorOf(unreliableProps(3, dstC), "unreliable-c").path) val snd = system.actorOf(senderProps(probe.ref, name, 1000.millis, 5, 1000, destinations, async = true), name) val N = 100 - for (n ← 1 to N) { + for (n <- 1 to N) { snd.tell(Req("a-" + n), probe.ref) } - for (n ← 1 to N) { + for (n <- 1 to N) { snd.tell(Req("b-" + n), probe.ref) } - for (n ← 1 to N) { + for (n <- 1 to N) { snd.tell(Req("c-" + n), probe.ref) } val deliverWithin = 20.seconds - probeA.receiveN(N, deliverWithin).map { case a: Action ⇒ a.payload }.toSet should ===((1 to N).map(n ⇒ "a-" + n).toSet) - probeB.receiveN(N, deliverWithin).map { case a: Action ⇒ a.payload }.toSet should ===((1 to N).map(n ⇒ "b-" + n).toSet) - probeC.receiveN(N, deliverWithin).map { case a: Action ⇒ a.payload }.toSet should ===((1 to N).map(n ⇒ "c-" + n).toSet) + probeA.receiveN(N, deliverWithin).map { case a: Action => a.payload }.toSet should ===((1 to N).map(n => "a-" + n).toSet) + probeB.receiveN(N, deliverWithin).map { case a: Action => a.payload }.toSet should ===((1 to N).map(n => "b-" + n).toSet) + probeC.receiveN(N, deliverWithin).map { case a: Action => a.payload }.toSet should ===((1 to N).map(n => "c-" + n).toSet) } "limit the number of messages redelivered at once" taggedAs (TimingTest) in { val probe = TestProbe() val probeA = TestProbe() val dst = system.actorOf(destinationProps(probeA.ref)) - val destinations = Map("A" → system.actorOf(unreliableProps(2, dst)).path) + val destinations = Map("A" -> system.actorOf(unreliableProps(2, dst)).path) val snd = system.actorOf(senderProps(probe.ref, name, 2.seconds, 5, 2, destinations, async = true), name) val N = 10 - for (n ← 1 to N) { + for (n <- 1 to N) { snd.tell(Req("a-" + n), probe.ref) } // initially all odd messages should go through - for (n ← 1 to N if n % 2 == 1) probeA.expectMsg(Action(n, s"a-$n")) + for (n <- 1 to N if n % 2 == 1) probeA.expectMsg(Action(n, s"a-$n")) probeA.expectNoMsg(100.millis) // at each redelivery round, 2 (even) messages are sent, the first goes through // without throttling, at each round half of the messages would go through var toDeliver = (1 to N).filter(_ % 2 == 0).map(_.toLong).toSet - for (n ← 1 to N if n % 2 == 0) { + for (n <- 1 to N if n % 2 == 0) { toDeliver -= probeA.expectMsgType[Action].id probeA.expectNoMsg(100.millis) } diff --git a/akka-persistence/src/test/scala/akka/persistence/EndToEndEventAdapterSpec.scala b/akka-persistence/src/test/scala/akka/persistence/EndToEndEventAdapterSpec.scala index 2428f7a9ee..8132e16173 100644 --- a/akka-persistence/src/test/scala/akka/persistence/EndToEndEventAdapterSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/EndToEndEventAdapterSpec.scala @@ -31,40 +31,40 @@ object EndToEndEventAdapterSpec { override def manifest(event: Any): String = event.getClass.getCanonicalName override def toJournal(event: Any): Any = - event match { case m: AppModel ⇒ JSON(m.payload) } + event match { case m: AppModel => JSON(m.payload) } override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case m: JSON if m.payload.toString.startsWith("a") ⇒ EventSeq.single(A(m.payload)) - case _ ⇒ EventSeq.empty + case m: JSON if m.payload.toString.startsWith("a") => EventSeq.single(A(m.payload)) + case _ => EventSeq.empty } } class NewAEndToEndAdapter(system: ExtendedActorSystem) extends EventAdapter { override def manifest(event: Any): String = event.getClass.getCanonicalName override def toJournal(event: Any): Any = - event match { case m: AppModel ⇒ JSON(m.payload) } + event match { case m: AppModel => JSON(m.payload) } override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case m: JSON if m.payload.toString.startsWith("a") ⇒ EventSeq.single(NewA(m.payload)) - case _ ⇒ EventSeq.empty + case m: JSON if m.payload.toString.startsWith("a") => EventSeq.single(NewA(m.payload)) + case _ => EventSeq.empty } } class BEndToEndAdapter(system: ExtendedActorSystem) extends EventAdapter { override def manifest(event: Any): String = event.getClass.getCanonicalName override def toJournal(event: Any): Any = - event match { case m: AppModel ⇒ JSON(m.payload) } + event match { case m: AppModel => JSON(m.payload) } override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case m: JSON if m.payload.toString.startsWith("b") ⇒ EventSeq.single(B(m.payload)) - case _ ⇒ EventSeq.empty + case m: JSON if m.payload.toString.startsWith("b") => EventSeq.single(B(m.payload)) + case _ => EventSeq.empty } } class NewBEndToEndAdapter(system: ExtendedActorSystem) extends EventAdapter { override def manifest(event: Any): String = event.getClass.getCanonicalName override def toJournal(event: Any): Any = - event match { case m: AppModel ⇒ JSON(m.payload) } + event match { case m: AppModel => JSON(m.payload) } override def fromJournal(event: Any, manifest: String): EventSeq = event match { - case m: JSON if m.payload.toString.startsWith("b") ⇒ EventSeq.single(NewB(m.payload)) - case _ ⇒ EventSeq.empty + case m: JSON if m.payload.toString.startsWith("b") => EventSeq.single(NewB(m.payload)) + case _ => EventSeq.empty } } @@ -74,18 +74,18 @@ object EndToEndEventAdapterSpec { var state: List[Any] = Nil val persistIncoming: Receive = { - case GetState ⇒ + case GetState => state.reverse.foreach { sender() ! _ } - case in ⇒ - persist(in) { e ⇒ + case in => + persist(in) { e => state ::= e sender() ! e } } override def receiveRecover = { - case RecoveryCompleted ⇒ // ignore - case e ⇒ state ::= e + case RecoveryCompleted => // ignore + case e => state ::= e } override def receiveCommand = persistIncoming @@ -98,7 +98,7 @@ abstract class EndToEndEventAdapterSpec(journalName: String, journalConfig: Conf import EndToEndEventAdapterSpec._ val storageLocations = List("akka.persistence.journal.leveldb.dir") - .map(s ⇒ new File(journalConfig.getString(s))) + .map(s => new File(journalConfig.getString(s))) override protected def beforeAll(): Unit = { storageLocations.foreach(FileUtils.deleteDirectory) @@ -154,7 +154,7 @@ abstract class EndToEndEventAdapterSpec(journalName: String, journalConfig: Conf def persister(name: String, probe: Option[ActorRef] = None)(implicit system: ActorSystem) = system.actorOf(Props(classOf[EndToEndAdapterActor], name, "akka.persistence.journal." + journalName, probe)) - def withActorSystem[T](name: String, config: Config)(block: ActorSystem ⇒ T): T = { + def withActorSystem[T](name: String, config: Config)(block: ActorSystem => T): T = { val system = ActorSystem(name, journalConfig withFallback config) try block(system) finally Await.ready(system.terminate(), 3.seconds) } @@ -162,7 +162,7 @@ abstract class EndToEndEventAdapterSpec(journalName: String, journalConfig: Conf "EventAdapters in end-to-end scenarios" must { "use the same adapter when reading as was used when writing to the journal" in - withActorSystem("SimpleSystem", adaptersConfig) { implicit system ⇒ + withActorSystem("SimpleSystem", adaptersConfig) { implicit system => val p = TestProbe() implicit val ref = p.ref @@ -187,7 +187,7 @@ abstract class EndToEndEventAdapterSpec(journalName: String, journalConfig: Conf "allow using an adapter, when write was performed without an adapter" in { val persistentName = "p2" - withActorSystem("NoAdapterSystem", adaptersConfig) { implicit system ⇒ + withActorSystem("NoAdapterSystem", adaptersConfig) { implicit system => val p = TestProbe() implicit val ref = p.ref @@ -209,7 +209,7 @@ abstract class EndToEndEventAdapterSpec(journalName: String, journalConfig: Conf p.expectMsg(B("b1")) } - withActorSystem("NowAdaptersAddedSystem", newAdaptersConfig) { implicit system ⇒ + withActorSystem("NowAdaptersAddedSystem", newAdaptersConfig) { implicit system => val p = TestProbe() implicit val ref = p.ref @@ -228,7 +228,7 @@ abstract class EndToEndEventAdapterSpec(journalName: String, journalConfig: Conf .withoutPath(s"$journalPath.event-adapters.a") .withoutPath(s"""$journalPath.event-adapter-bindings."${classOf[EndToEndEventAdapterSpec].getCanonicalName}$$A"""") - withActorSystem("MissingAdapterSystem", journalConfig.withFallback(missingAdapterConfig)) { implicit system2 ⇒ + withActorSystem("MissingAdapterSystem", journalConfig.withFallback(missingAdapterConfig)) { implicit system2 => EventFilter[ActorInitializationException](occurrences = 1, pattern = ".*undefined event-adapter.*") intercept { intercept[IllegalArgumentException] { Persistence(system2).adaptersFor(s"akka.persistence.journal.$journalName").get(classOf[String]) diff --git a/akka-persistence/src/test/scala/akka/persistence/EventAdapterSpec.scala b/akka-persistence/src/test/scala/akka/persistence/EventAdapterSpec.scala index 98bfc4f8ad..d11e123f02 100644 --- a/akka-persistence/src/test/scala/akka/persistence/EventAdapterSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/EventAdapterSpec.scala @@ -35,13 +35,13 @@ object EventAdapterSpec { val Minor = Set("minor") override def toJournal(event: Any): Any = event match { - case e @ UserDataChanged(_, age) if age > 18 ⇒ Tagged(e, Adult) - case e @ UserDataChanged(_, age) ⇒ Tagged(e, Minor) - case e ⇒ NotTagged(e) + case e @ UserDataChanged(_, age) if age > 18 => Tagged(e, Adult) + case e @ UserDataChanged(_, age) => Tagged(e, Minor) + case e => NotTagged(e) } override def fromJournal(event: Any, manifest: String): EventSeq = EventSeq.single { event match { - case m: JournalModel ⇒ m.payload + case m: JournalModel => m.payload } } @@ -51,7 +51,7 @@ object EventAdapterSpec { class ReplayPassThroughAdapter extends UserAgeTaggingAdapter { override def fromJournal(event: Any, manifest: String): EventSeq = EventSeq.single { event match { - case m: JournalModel ⇒ event // don't unpack, just pass through the JournalModel + case m: JournalModel => event // don't unpack, just pass through the JournalModel } } } @@ -76,18 +76,18 @@ object EventAdapterSpec { var state: List[Any] = Nil val persistIncoming: Receive = { - case GetState ⇒ + case GetState => state.reverse.foreach { sender() ! _ } - case in ⇒ - persist(in) { e ⇒ + case in => + persist(in) { e => state ::= e sender() ! e } } override def receiveRecover = { - case RecoveryCompleted ⇒ // ignore - case e ⇒ state ::= e + case RecoveryCompleted => // ignore + case e => state ::= e } override def receiveCommand = persistIncoming } @@ -181,7 +181,7 @@ abstract class EventAdapterSpec(journalName: String, journalConfig: Config, adap } -trait ReplayPassThrough { this: EventAdapterSpec ⇒ +trait ReplayPassThrough { this: EventAdapterSpec => "EventAdapter" must { "store events after applying adapter" in { @@ -208,7 +208,7 @@ trait ReplayPassThrough { this: EventAdapterSpec ⇒ } -trait NoAdapters { this: EventAdapterSpec ⇒ +trait NoAdapters { this: EventAdapterSpec => "EventAdapter" must { "work when plugin defines no adapter" in { val p2 = persister("p2", journalId = "no-adapter") diff --git a/akka-persistence/src/test/scala/akka/persistence/EventSourcedActorDeleteFailureSpec.scala b/akka-persistence/src/test/scala/akka/persistence/EventSourcedActorDeleteFailureSpec.scala index 26e1768957..5e509bbf7d 100644 --- a/akka-persistence/src/test/scala/akka/persistence/EventSourcedActorDeleteFailureSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/EventSourcedActorDeleteFailureSpec.scala @@ -28,7 +28,7 @@ object EventSourcedActorDeleteFailureSpec { class DoesNotHandleDeleteFailureActor(name: String, probe: ActorRef) extends PersistentActor { override def persistenceId = name override def receiveCommand: Receive = { - case DeleteTo(n) ⇒ deleteMessages(n) + case DeleteTo(n) => deleteMessages(n) } override def receiveRecover: Receive = Actor.emptyBehavior } @@ -36,8 +36,8 @@ object EventSourcedActorDeleteFailureSpec { class HandlesDeleteFailureActor(name: String, probe: ActorRef) extends PersistentActor { override def persistenceId = name override def receiveCommand: Receive = { - case DeleteTo(n) ⇒ deleteMessages(n) - case f: DeleteMessagesFailure ⇒ probe ! f + case DeleteTo(n) => deleteMessages(n) + case f: DeleteMessagesFailure => probe ! f } override def receiveRecover: Receive = Actor.emptyBehavior } diff --git a/akka-persistence/src/test/scala/akka/persistence/EventSourcedActorFailureSpec.scala b/akka-persistence/src/test/scala/akka/persistence/EventSourcedActorFailureSpec.scala index 74c9994035..bc99635fbe 100644 --- a/akka-persistence/src/test/scala/akka/persistence/EventSourcedActorFailureSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/EventSourcedActorFailureSpec.scala @@ -35,7 +35,7 @@ object EventSourcedActorFailureSpec { } override def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)( - recoveryCallback: PersistentRepr ⇒ Unit): Future[Unit] = { + recoveryCallback: PersistentRepr => Unit): Future[Unit] = { val highest = highestSequenceNr(persistenceId) val readFromStore = read(persistenceId, fromSequenceNr, toSequenceNr, max) if (readFromStore.isEmpty) @@ -50,30 +50,30 @@ object EventSourcedActorFailureSpec { def isWrong(messages: immutable.Seq[AtomicWrite]): Boolean = messages.exists { - case a: AtomicWrite ⇒ - a.payload.exists { case PersistentRepr(Evt(s: String), _) ⇒ s.contains("wrong") } - case _ ⇒ false + case a: AtomicWrite => + a.payload.exists { case PersistentRepr(Evt(s: String), _) => s.contains("wrong") } + case _ => false } def checkSerializable(messages: immutable.Seq[AtomicWrite]): immutable.Seq[Try[Unit]] = messages.collect { - case a: AtomicWrite ⇒ + case a: AtomicWrite => a.payload.collectFirst { - case PersistentRepr(Evt(s: String), _: Long) if s.contains("not serializable") ⇒ s + case PersistentRepr(Evt(s: String), _: Long) if s.contains("not serializable") => s } match { - case Some(s) ⇒ Failure(new SimulatedSerializationException(s)) - case None ⇒ AsyncWriteJournal.successUnit + case Some(s) => Failure(new SimulatedSerializationException(s)) + case None => AsyncWriteJournal.successUnit } } def isCorrupt(events: Seq[PersistentRepr]): Boolean = - events.exists { case PersistentRepr(Evt(s: String), _) ⇒ s.contains("corrupt") } + events.exists { case PersistentRepr(Evt(s: String), _) => s.contains("corrupt") } } class OnRecoveryFailurePersistentActor(name: String, probe: ActorRef) extends ExamplePersistentActor(name) { val receiveCommand: Receive = commonBehavior orElse { - case c @ Cmd(txt) ⇒ persist(Evt(txt))(updateState) + case c @ Cmd(txt) => persist(Evt(txt))(updateState) } override protected def onRecoveryFailure(cause: Throwable, event: Option[Any]): Unit = @@ -82,20 +82,20 @@ object EventSourcedActorFailureSpec { class Supervisor(testActor: ActorRef) extends Actor { override def supervisorStrategy = OneForOneStrategy(loggingEnabled = false) { - case e ⇒ + case e => testActor ! e SupervisorStrategy.Restart } def receive = { - case props: Props ⇒ sender() ! context.actorOf(props) - case m ⇒ sender() ! m + case props: Props => sender() ! context.actorOf(props) + case m => sender() ! m } } class ResumingSupervisor(testActor: ActorRef) extends Supervisor(testActor) { override def supervisorStrategy = OneForOneStrategy(loggingEnabled = false) { - case e ⇒ + case e => testActor ! e SupervisorStrategy.Resume } @@ -106,11 +106,11 @@ object EventSourcedActorFailureSpec { def this(name: String) = this(name, None) override val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ persist(Evt(s"${data}"))(updateState) + case Cmd(data) => persist(Evt(s"${data}"))(updateState) } val failingRecover: Receive = { - case Evt(data) if data == "bad" ⇒ + case Evt(data) if data == "bad" => throw new SimulatedException("Simulated exception from receiveRecover") } @@ -120,7 +120,7 @@ object EventSourcedActorFailureSpec { class ThrowingActor1(name: String) extends ExamplePersistentActor(name) { override val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => persist(Evt(s"${data}"))(updateState) if (data == "err") throw new SimulatedException("Simulated exception 1") @@ -129,8 +129,8 @@ object EventSourcedActorFailureSpec { class ThrowingActor2(name: String) extends ExamplePersistentActor(name) { override val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ - persist(Evt(s"${data}")) { evt ⇒ + case Cmd(data) => + persist(Evt(s"${data}")) { evt => if (data == "err") throw new SimulatedException("Simulated exception 1") updateState(evt) diff --git a/akka-persistence/src/test/scala/akka/persistence/LoadPluginSpec.scala b/akka-persistence/src/test/scala/akka/persistence/LoadPluginSpec.scala index ed7982227a..c569384554 100644 --- a/akka-persistence/src/test/scala/akka/persistence/LoadPluginSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/LoadPluginSpec.scala @@ -15,7 +15,7 @@ object LoadJournalSpec { class JournalWithConfig(val config: Config) extends InmemJournal { override def receivePluginInternal: Actor.Receive = { - case GetConfig ⇒ sender() ! config + case GetConfig => sender() ! config } } } diff --git a/akka-persistence/src/test/scala/akka/persistence/ManyRecoveriesSpec.scala b/akka-persistence/src/test/scala/akka/persistence/ManyRecoveriesSpec.scala index 45a85ad504..ec7f7a6dec 100644 --- a/akka-persistence/src/test/scala/akka/persistence/ManyRecoveriesSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/ManyRecoveriesSpec.scala @@ -23,14 +23,14 @@ object ManyRecoveriesSpec { override def persistenceId = name override def receiveRecover: Receive = { - case Evt(s) ⇒ + case Evt(s) => latch.foreach(Await.ready(_, 10.seconds)) } override def receiveCommand: Receive = { - case Cmd(s) ⇒ persist(Evt(s)) { _ ⇒ + case Cmd(s) => persist(Evt(s)) { _ => sender() ! s"$persistenceId-$s-${lastSequenceNr}" } - case "stop" ⇒ + case "stop" => context.stop(self) } } @@ -54,25 +54,25 @@ class ManyRecoveriesSpec extends PersistenceSpec(ConfigFactory.parseString( "Many persistent actors" must { "be able to recovery without overloading" in { - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => system.actorOf(testProps(s"a$n", latch = None)) ! Cmd("A") expectMsg(s"a$n-A-1") } // this would starve (block) all threads without max-concurrent-recoveries val latch = TestLatch() - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => system.actorOf(testProps(s"a$n", Some(latch))) ! Cmd("B") } // this should be able to progress even though above is blocking, // 2 remaining non-blocked threads - (1 to 10).foreach { n ⇒ + (1 to 10).foreach { n => system.actorOf(TestActors.echoActorProps) ! n expectMsg(n) } latch.countDown() - receiveN(100).toSet should ===((1 to 100).map(n ⇒ s"a$n-B-2").toSet) + receiveN(100).toSet should ===((1 to 100).map(n => s"a$n-B-2").toSet) } } diff --git a/akka-persistence/src/test/scala/akka/persistence/OptimizedRecoverySpec.scala b/akka-persistence/src/test/scala/akka/persistence/OptimizedRecoverySpec.scala index f79ed2ed1e..52193b617a 100644 --- a/akka-persistence/src/test/scala/akka/persistence/OptimizedRecoverySpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/OptimizedRecoverySpec.scala @@ -29,28 +29,28 @@ object OptimizedRecoverySpec { var state = "" def receiveCommand = { - case TakeSnapshot ⇒ saveSnapshot(state) - case s: SaveSnapshotSuccess ⇒ probe ! s - case GetState ⇒ probe ! state - case Save(s) ⇒ persist(Saved(s, lastSequenceNr + 1)) { evt ⇒ + case TakeSnapshot => saveSnapshot(state) + case s: SaveSnapshotSuccess => probe ! s + case GetState => probe ! state + case Save(s) => persist(Saved(s, lastSequenceNr + 1)) { evt => state += evt.s probe ! evt } } def receiveRecover = { - case s: SnapshotOffer ⇒ + case s: SnapshotOffer => probe ! s state = s.snapshot.toString - case evt: Saved ⇒ + case evt: Saved => state += evt.s probe ! evt - case RecoveryCompleted ⇒ + case RecoveryCompleted => require(!recoveryRunning, "expected !recoveryRunning in RecoveryCompleted") probe ! RecoveryCompleted // verify that persist can be used here - persist(PersistFromRecoveryCompleted)(_ ⇒ probe ! PersistFromRecoveryCompleted) + persist(PersistFromRecoveryCompleted)(_ => probe ! PersistFromRecoveryCompleted) } } diff --git a/akka-persistence/src/test/scala/akka/persistence/OptionalSnapshotStoreSpec.scala b/akka-persistence/src/test/scala/akka/persistence/OptionalSnapshotStoreSpec.scala index 7b530a4bee..3d9e3272ce 100644 --- a/akka-persistence/src/test/scala/akka/persistence/OptionalSnapshotStoreSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/OptionalSnapshotStoreSpec.scala @@ -17,11 +17,11 @@ object OptionalSnapshotStoreSpec { override def persistenceId = name override def receiveCommand: Receive = { - case s: String ⇒ + case s: String => lastSender = sender() saveSnapshot(s) - case f: SaveSnapshotFailure ⇒ lastSender ! f - case s: SaveSnapshotSuccess ⇒ lastSender ! s + case f: SaveSnapshotFailure => lastSender ! f + case s: SaveSnapshotSuccess => lastSender ! s } override def receiveRecover: Receive = Actor.emptyBehavior } diff --git a/akka-persistence/src/test/scala/akka/persistence/PerformanceSpec.scala b/akka-persistence/src/test/scala/akka/persistence/PerformanceSpec.scala index fdf3827aaa..c77f26ff10 100644 --- a/akka-persistence/src/test/scala/akka/persistence/PerformanceSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/PerformanceSpec.scala @@ -42,12 +42,12 @@ object PerformanceSpec { var failAt: Long = -1 override val receiveRecover: Receive = { - case _ ⇒ if (lastSequenceNr % 1000 == 0) print("r") + case _ => if (lastSequenceNr % 1000 == 0) print("r") } val controlBehavior: Receive = { - case StopMeasure ⇒ deferAsync(StopMeasure)(_ ⇒ sender() ! StopMeasure) - case FailAt(sequenceNr) ⇒ failAt = sequenceNr + case StopMeasure => deferAsync(StopMeasure)(_ => sender() ! StopMeasure) + case FailAt(sequenceNr) => failAt = sequenceNr } } @@ -55,7 +55,7 @@ object PerformanceSpec { class CommandsourcedTestPersistentActor(name: String) extends PerformanceTestPersistentActor(name) { override val receiveCommand: Receive = controlBehavior orElse { - case cmd ⇒ persistAsync(cmd) { _ ⇒ + case cmd => persistAsync(cmd) { _ => if (lastSequenceNr % 1000 == 0) print(".") if (lastSequenceNr == failAt) throw new TestException("boom") } @@ -65,7 +65,7 @@ object PerformanceSpec { class EventsourcedTestPersistentActor(name: String) extends PerformanceTestPersistentActor(name) { override val receiveCommand: Receive = controlBehavior orElse { - case cmd ⇒ persist(cmd) { _ ⇒ + case cmd => persist(cmd) { _ => if (lastSequenceNr % 1000 == 0) print(".") if (lastSequenceNr == failAt) throw new TestException("boom") } @@ -78,13 +78,13 @@ object PerformanceSpec { class MixedTestPersistentActor(name: String) extends PerformanceTestPersistentActor(name) { var counter = 0 - val handler: Any ⇒ Unit = { evt ⇒ + val handler: Any => Unit = { evt => if (lastSequenceNr % 1000 == 0) print(".") if (lastSequenceNr == failAt) throw new TestException("boom") } val receiveCommand: Receive = controlBehavior orElse { - case cmd ⇒ + case cmd => counter += 1 if (counter % 10 == 0) persist(cmd)(handler) else persistAsync(cmd)(handler) @@ -94,19 +94,19 @@ object PerformanceSpec { class StashingEventsourcedTestPersistentActor(name: String) extends PerformanceTestPersistentActor(name) { val printProgress: PartialFunction[Any, Any] = { - case m ⇒ if (lastSequenceNr % 1000 == 0) print("."); m + case m => if (lastSequenceNr % 1000 == 0) print("."); m } val receiveCommand: Receive = printProgress andThen (controlBehavior orElse { - case "a" ⇒ persist("a")(_ ⇒ context.become(processC)) - case "b" ⇒ persist("b")(_ ⇒ ()) + case "a" => persist("a")(_ => context.become(processC)) + case "b" => persist("b")(_ => ()) }) val processC: Receive = printProgress andThen { - case "c" ⇒ - persist("c")(_ ⇒ context.unbecome()) + case "c" => + persist("c")(_ => context.unbecome()) unstashAll() - case other ⇒ stash() + case other => stash() } } } @@ -120,7 +120,7 @@ class PerformanceSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", failAt foreach { persistentActor ! FailAt(_) } val m = new Measure(loadCycles) m.startMeasure() - 1 to loadCycles foreach { i ⇒ persistentActor ! s"msg${i}" } + 1 to loadCycles foreach { i => persistentActor ! s"msg${i}" } persistentActor ! StopMeasure expectMsg(100.seconds, StopMeasure) println(f"\nthroughput = ${m.stopMeasure()}%.2f $description per second") @@ -145,7 +145,7 @@ class PerformanceSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", val persistentActor = namedPersistentActor[StashingEventsourcedTestPersistentActor] val m = new Measure(loadCycles) m.startMeasure() - val cmds = 1 to (loadCycles / 3) flatMap (_ ⇒ List("a", "b", "c")) + val cmds = 1 to (loadCycles / 3) flatMap (_ => List("a", "b", "c")) cmds foreach (persistentActor ! _) persistentActor ! StopMeasure expectMsg(100.seconds, StopMeasure) diff --git a/akka-persistence/src/test/scala/akka/persistence/PersistenceSpec.scala b/akka-persistence/src/test/scala/akka/persistence/PersistenceSpec.scala index 2c86d63193..7ba73183f1 100644 --- a/akka-persistence/src/test/scala/akka/persistence/PersistenceSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/PersistenceSpec.scala @@ -22,7 +22,7 @@ import akka.actor.Props import akka.testkit.AkkaSpec abstract class PersistenceSpec(config: Config) extends AkkaSpec(config) with BeforeAndAfterEach with Cleanup - with PersistenceMatchers { this: AkkaSpec ⇒ + with PersistenceMatchers { this: AkkaSpec => private var _name: String = _ lazy val extension = Persistence(system) @@ -72,11 +72,11 @@ object PersistenceSpec { """)) } -trait Cleanup { this: AkkaSpec ⇒ +trait Cleanup { this: AkkaSpec => val storageLocations = List( "akka.persistence.journal.leveldb.dir", "akka.persistence.journal.leveldb-shared.store.dir", - "akka.persistence.snapshot-store.local.dir").map(s ⇒ new File(system.settings.config.getString(s))) + "akka.persistence.snapshot-store.local.dir").map(s => new File(system.settings.config.getString(s))) override protected def atStartup(): Unit = { storageLocations.foreach(FileUtils.deleteDirectory) @@ -91,7 +91,7 @@ abstract class NamedPersistentActor(name: String) extends PersistentActor { override def persistenceId: String = name } -trait TurnOffRecoverOnStart { this: Eventsourced ⇒ +trait TurnOffRecoverOnStart { this: Eventsourced => override def recovery = Recovery.none } @@ -105,9 +105,9 @@ trait PersistenceMatchers { final class IndependentlyOrdered(prefixes: immutable.Seq[String]) extends Matcher[immutable.Seq[Any]] { override def apply(_left: immutable.Seq[Any]) = { val left = _left.map(_.toString) - val mapped = left.groupBy(l ⇒ prefixes.indexWhere(p ⇒ l.startsWith(p))) - (-1) // ignore other messages + val mapped = left.groupBy(l => prefixes.indexWhere(p => l.startsWith(p))) - (-1) // ignore other messages val results = for { - (pos, seq) ← mapped + (pos, seq) <- mapped nrs = seq.map(_.replaceFirst(prefixes(pos), "").toInt) sortedNrs = nrs.sorted if nrs != sortedNrs @@ -117,7 +117,7 @@ trait PersistenceMatchers { s"""Messages sequence with prefix ${prefixes(pos)} was sorted! Was: $seq"""") if (results.forall(_.matches)) MatchResult(true, "", "") - else results.find(r ⇒ !r.matches).get + else results.find(r => !r.matches).get } } diff --git a/akka-persistence/src/test/scala/akka/persistence/PersistentActorBoundedStashingSpec.scala b/akka-persistence/src/test/scala/akka/persistence/PersistentActorBoundedStashingSpec.scala index 9876b29bb4..7cec117aa3 100644 --- a/akka-persistence/src/test/scala/akka/persistence/PersistentActorBoundedStashingSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/PersistentActorBoundedStashingSpec.scala @@ -27,17 +27,17 @@ object PersistentActorBoundedStashingSpec { var events: List[Any] = Nil val updateState: Receive = { - case Evt(data) ⇒ events = data :: events + case Evt(data) => events = data :: events } val commonBehavior: Receive = { - case GetState ⇒ sender() ! events.reverse + case GetState => sender() ! events.reverse } def receiveRecover = updateState override def receiveCommand: Receive = commonBehavior orElse { - case Cmd(x: Any) ⇒ persist(Evt(x))(updateState) + case Cmd(x: Any) => persist(Evt(x))(updateState) } } @@ -96,7 +96,7 @@ class ThrowExceptionStrategyPersistentActorBoundedStashingSpec //after PA stopped, all stashed messages forward to deadletters //the message triggering the overflow is lost, so we get one less message than we sent - 1 to capacity foreach (i ⇒ expectMsg(DeadLetter(Cmd(i), testActor, persistentActor))) + 1 to capacity foreach (i => expectMsg(DeadLetter(Cmd(i), testActor, persistentActor))) // send another message to the now dead actor and make sure that it goes to dead letters persistentActor ! Cmd(capacity + 2) @@ -122,9 +122,9 @@ class DiscardStrategyPersistentActorBoundedStashingSpec //internal stash overflow after 10 1 to (2 * capacity) foreach (persistentActor ! Cmd(_)) //so, 11 to 20 discard to deadletter - (1 + capacity) to (2 * capacity) foreach (i ⇒ expectMsg(DeadLetter(Cmd(i), testActor, persistentActor))) + (1 + capacity) to (2 * capacity) foreach (i => expectMsg(DeadLetter(Cmd(i), testActor, persistentActor))) //allow "a" and 1 to 10 write complete - 1 to (1 + capacity) foreach (i ⇒ SteppingInmemJournal.step(journal)) + 1 to (1 + capacity) foreach (i => SteppingInmemJournal.step(journal)) persistentActor ! GetState @@ -150,9 +150,9 @@ class ReplyToStrategyPersistentActorBoundedStashingSpec //internal stash overflow after 10 1 to (2 * capacity) foreach (persistentActor ! Cmd(_)) //so, 11 to 20 reply to with "Reject" String - (1 + capacity) to (2 * capacity) foreach (i ⇒ expectMsg("RejectToStash")) + (1 + capacity) to (2 * capacity) foreach (i => expectMsg("RejectToStash")) //allow "a" and 1 to 10 write complete - 1 to (1 + capacity) foreach (i ⇒ SteppingInmemJournal.step(journal)) + 1 to (1 + capacity) foreach (i => SteppingInmemJournal.step(journal)) persistentActor ! GetState diff --git a/akka-persistence/src/test/scala/akka/persistence/PersistentActorJournalProtocolSpec.scala b/akka-persistence/src/test/scala/akka/persistence/PersistentActorJournalProtocolSpec.scala index 44351a8e0e..d9eb025bba 100644 --- a/akka-persistence/src/test/scala/akka/persistence/PersistentActorJournalProtocolSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/PersistentActorJournalProtocolSpec.scala @@ -44,30 +44,30 @@ akka.persistence.snapshot-store.plugin = "akka.persistence.no-snapshot-store" override def postStop(): Unit = monitor ! PostStop(persistenceId) def receiveRecover = { - case x ⇒ monitor ! x + case x => monitor ! x } def receiveCommand = behavior orElse { - case m: Multi ⇒ m.cmd.foreach(behavior) + case m: Multi => m.cmd.foreach(behavior) } val behavior: Receive = { - case p: Persist ⇒ P(p) - case p: PersistAsync ⇒ PA(p) - case Echo(id) ⇒ sender() ! Done(id, 0) - case Fail(ex) ⇒ throw ex + case p: Persist => P(p) + case p: PersistAsync => PA(p) + case Echo(id) => sender() ! Done(id, 0) + case Fail(ex) => throw ex } - val doNothing = (_: Any) ⇒ () + val doNothing = (_: Any) => () def P(p: Persist): Unit = { var sub = 0 - persistAll(p.msgs.toList) { e ⇒ + persistAll(p.msgs.toList) { e => sender() ! Done(p.id, { sub += 1; sub }) behavior.applyOrElse(e, doNothing) } } def PA(p: PersistAsync): Unit = { var sub = 0 - persistAllAsync(p.msgs.toList) { e ⇒ + persistAllAsync(p.msgs.toList) { e => sender() ! Done(p.id, { sub += 1; sub }) behavior.applyOrElse(e, doNothing) } @@ -91,7 +91,7 @@ class JournalProbe(implicit private val system: ExtendedActorSystem) extends Ext class JournalPuppet extends Actor { val ref = JournalPuppet(context.system).ref def receive = { - case x ⇒ ref forward x + case x => ref forward x } } @@ -109,13 +109,13 @@ class PersistentActorJournalProtocolSpec extends AkkaSpec(config) with ImplicitS w.persistentActor should ===(subject) w.messages.size should ===(msgs.size) w.messages.zip(msgs).foreach { - case (AtomicWrite(writes), msg) ⇒ + case (AtomicWrite(writes), msg) => writes.size should ===(msg.msg.size) writes.zip(msg.msg).foreach { - case (PersistentRepr(evt, _), m) ⇒ + case (PersistentRepr(evt, _), m) => evt should ===(m) } - case x ⇒ fail(s"unexpected $x") + case x => fail(s"unexpected $x") } } w @@ -124,10 +124,10 @@ class PersistentActorJournalProtocolSpec extends AkkaSpec(config) with ImplicitS def confirm(w: WriteMessages): Unit = { journal.send(w.persistentActor, WriteMessagesSuccessful) w.messages.foreach { - case AtomicWrite(msgs) ⇒ - msgs.foreach(msg ⇒ + case AtomicWrite(msgs) => + msgs.foreach(msg => w.persistentActor.tell(WriteMessageSuccess(msg, w.actorInstanceId), msg.sender)) - case NonPersistentRepr(msg, sender) ⇒ w.persistentActor.tell(msg, sender) + case NonPersistentRepr(msg, sender) => w.persistentActor.tell(msg, sender) } } @@ -200,19 +200,19 @@ class PersistentActorJournalProtocolSpec extends AkkaSpec(config) with ImplicitS "using large number of persist() calls" in { val subject = startActor("test-4") - subject ! Multi(Vector.tabulate(30)(i ⇒ Persist(i, s"a-$i")): _*) - val w1 = expectWrite(subject, Vector.tabulate(30)(i ⇒ Msgs(s"a-$i")): _*) + subject ! Multi(Vector.tabulate(30)(i => Persist(i, s"a-$i")): _*) + val w1 = expectWrite(subject, Vector.tabulate(30)(i => Msgs(s"a-$i")): _*) confirm(w1) - for (i ← 0 until 30) expectMsg(Done(i, 1)) + for (i <- 0 until 30) expectMsg(Done(i, 1)) subject ! PoisonPill expectMsg(PostStop("test-4")) journal.msgAvailable should ===(false) } "using large number of persistAsync() calls" in { - def msgs(start: Int, end: Int) = (start until end).map(i ⇒ Msgs(s"a-$i-1", s"a-$i-2")) - def commands(start: Int, end: Int) = (start until end).map(i ⇒ PersistAsync(i, s"a-$i-1", s"a-$i-2")) - def expectDone(start: Int, end: Int) = for (i ← start until end; j ← 1 to 2) expectMsg(Done(i, j)) + def msgs(start: Int, end: Int) = (start until end).map(i => Msgs(s"a-$i-1", s"a-$i-2")) + def commands(start: Int, end: Int) = (start until end).map(i => PersistAsync(i, s"a-$i-1", s"a-$i-2")) + def expectDone(start: Int, end: Int) = for (i <- start until end; j <- 1 to 2) expectMsg(Done(i, j)) val subject = startActor("test-5") subject ! PersistAsync(-1, "a" +: commands(20, 30): _*) @@ -221,7 +221,7 @@ class PersistentActorJournalProtocolSpec extends AkkaSpec(config) with ImplicitS val w0 = expectWrite(subject, Msgs("a" +: commands(20, 30): _*)) journal.expectNoMsg(300.millis) confirm(w0) - (1 to 11) foreach (x ⇒ expectMsg(Done(-1, x))) + (1 to 11) foreach (x => expectMsg(Done(-1, x))) val w1 = expectWrite(subject, msgs(0, 20): _*) journal.expectNoMsg(300.millis) confirm(w1) diff --git a/akka-persistence/src/test/scala/akka/persistence/PersistentActorRecoveryTimeoutSpec.scala b/akka-persistence/src/test/scala/akka/persistence/PersistentActorRecoveryTimeoutSpec.scala index 24101f0856..a1c9f96e6e 100644 --- a/akka-persistence/src/test/scala/akka/persistence/PersistentActorRecoveryTimeoutSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/PersistentActorRecoveryTimeoutSpec.scala @@ -26,7 +26,7 @@ object PersistentActorRecoveryTimeoutSpec { override def receiveRecover: Receive = Actor.emptyBehavior override def receiveCommand: Receive = { - case x ⇒ persist(x) { _ ⇒ + case x => persist(x) { _ => sender() ! x } } @@ -43,12 +43,12 @@ object PersistentActorRecoveryTimeoutSpec { } override def receiveRecover: Receive = { - case RecoveryCompleted ⇒ probe ! context.receiveTimeout - case _ ⇒ // we don't care + case RecoveryCompleted => probe ! context.receiveTimeout + case _ => // we don't care } override def receiveCommand: Receive = { - case x ⇒ persist(x) { _ ⇒ + case x => persist(x) { _ => sender() ! x } } diff --git a/akka-persistence/src/test/scala/akka/persistence/PersistentActorSpec.scala b/akka-persistence/src/test/scala/akka/persistence/PersistentActorSpec.scala index 5b47792d15..5b51bf473f 100644 --- a/akka-persistence/src/test/scala/akka/persistence/PersistentActorSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/PersistentActorSpec.scala @@ -32,15 +32,15 @@ object PersistentActorSpec { var askedForDelete: Option[ActorRef] = None val updateState: Receive = { - case Evt(data) ⇒ events = data :: events - case d @ Some(ref: ActorRef) ⇒ askedForDelete = d.asInstanceOf[Some[ActorRef]] + case Evt(data) => events = data :: events + case d @ Some(ref: ActorRef) => askedForDelete = d.asInstanceOf[Some[ActorRef]] } val commonBehavior: Receive = { - case "boom" ⇒ throw new TestException("boom") - case GetState ⇒ sender() ! events.reverse - case Delete(toSequenceNr) ⇒ - persist(Some(sender())) { s ⇒ askedForDelete = s } + case "boom" => throw new TestException("boom") + case GetState => sender() ! events.reverse + case Delete(toSequenceNr) => + persist(Some(sender())) { s => askedForDelete = s } deleteMessages(toSequenceNr) } @@ -73,26 +73,26 @@ object PersistentActorSpec { class Behavior1PersistentActor(name: String) extends ExamplePersistentActor(name) { val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => persistAll(Seq(Evt(s"${data}-1"), Evt(s"${data}-2")))(updateState) - case d: DeleteMessagesSuccess ⇒ + case d: DeleteMessagesSuccess => val replyTo = askedForDelete.getOrElse(throw new RuntimeException("Received DeleteMessagesSuccess without anyone asking for delete!")) replyTo ! d - case d: DeleteMessagesFailure ⇒ + case d: DeleteMessagesFailure => val replyTo = askedForDelete.getOrElse(throw new RuntimeException("Received DeleteMessagesFailure without anyone asking for delete!")) replyTo ! d } override protected def onPersistRejected(cause: Throwable, event: Any, seqNr: Long): Unit = event match { - case Evt(data) ⇒ sender() ! s"Rejected: $data" - case _ ⇒ super.onPersistRejected(cause, event, seqNr) + case Evt(data) => sender() ! s"Rejected: $data" + case _ => super.onPersistRejected(cause, event, seqNr) } override protected def onPersistFailure(cause: Throwable, event: Any, seqNr: Long): Unit = event match { - case Evt(data) ⇒ sender() ! s"Failure: $data" - case _ ⇒ super.onPersistFailure(cause, event, seqNr) + case Evt(data) => sender() ! s"Failure: $data" + case _ => super.onPersistFailure(cause, event, seqNr) } } class Behavior1PersistentActorWithLevelDbRuntimePluginConfig(name: String, val providedConfig: Config) @@ -102,7 +102,7 @@ object PersistentActorSpec { class Behavior2PersistentActor(name: String) extends ExamplePersistentActor(name) { val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => persistAll(Seq(Evt(s"${data}-1"), Evt(s"${data}-2")))(updateState) persistAll(Seq(Evt(s"${data}-3"), Evt(s"${data}-4")))(updateState) } @@ -114,7 +114,7 @@ object PersistentActorSpec { class Behavior3PersistentActor(name: String) extends ExamplePersistentActor(name) { val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => persistAll(Seq(Evt(s"${data}-11"), Evt(s"${data}-12")))(updateState) updateState(Evt(s"${data}-10")) } @@ -126,17 +126,17 @@ object PersistentActorSpec { class ChangeBehaviorInLastEventHandlerPersistentActor(name: String) extends ExamplePersistentActor(name) { val newBehavior: Receive = { - case Cmd(data) ⇒ + case Cmd(data) => persist(Evt(s"${data}-21"))(updateState) - persist(Evt(s"${data}-22")) { event ⇒ + persist(Evt(s"${data}-22")) { event => updateState(event) context.unbecome() } } val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ - persist(Evt(s"${data}-0")) { event ⇒ + case Cmd(data) => + persist(Evt(s"${data}-0")) { event => updateState(event) context.become(newBehavior) } @@ -149,8 +149,8 @@ object PersistentActorSpec { class ChangeBehaviorInFirstEventHandlerPersistentActor(name: String) extends ExamplePersistentActor(name) { val newBehavior: Receive = { - case Cmd(data) ⇒ - persist(Evt(s"${data}-21")) { event ⇒ + case Cmd(data) => + persist(Evt(s"${data}-21")) { event => updateState(event) context.unbecome() } @@ -158,8 +158,8 @@ object PersistentActorSpec { } val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ - persist(Evt(s"${data}-0")) { event ⇒ + case Cmd(data) => + persist(Evt(s"${data}-0")) { event => updateState(event) context.become(newBehavior) } @@ -172,14 +172,14 @@ object PersistentActorSpec { class ChangeBehaviorInCommandHandlerFirstPersistentActor(name: String) extends ExamplePersistentActor(name) { val newBehavior: Receive = { - case Cmd(data) ⇒ + case Cmd(data) => context.unbecome() persistAll(Seq(Evt(s"${data}-31"), Evt(s"${data}-32")))(updateState) updateState(Evt(s"${data}-30")) } val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => context.become(newBehavior) persist(Evt(s"${data}-0"))(updateState) } @@ -191,14 +191,14 @@ object PersistentActorSpec { class ChangeBehaviorInCommandHandlerLastPersistentActor(name: String) extends ExamplePersistentActor(name) { val newBehavior: Receive = { - case Cmd(data) ⇒ + case Cmd(data) => persistAll(Seq(Evt(s"${data}-31"), Evt(s"${data}-32")))(updateState) updateState(Evt(s"${data}-30")) context.unbecome() } val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => persist(Evt(s"${data}-0"))(updateState) context.become(newBehavior) } @@ -210,7 +210,7 @@ object PersistentActorSpec { class SnapshottingPersistentActor(name: String, probe: ActorRef) extends ExamplePersistentActor(name) { override def receiveRecover = super.receiveRecover orElse { - case SnapshotOffer(_, events: List[_]) ⇒ + case SnapshotOffer(_, events: List[_]) => probe ! "offered" this.events = events } @@ -220,9 +220,9 @@ object PersistentActorSpec { } def receiveCommand: Receive = commonBehavior orElse { - case c: Cmd ⇒ handleCmd(c) - case SaveSnapshotSuccess(_) ⇒ probe ! "saved" - case "snap" ⇒ saveSnapshot(events) + case c: Cmd => handleCmd(c) + case SaveSnapshotSuccess(_) => probe ! "saved" + case "snap" => saveSnapshot(events) } } class SnapshottingPersistentActorWithLevelDbRuntimePluginConfig(name: String, probe: ActorRef, val providedConfig: Config) @@ -232,7 +232,7 @@ object PersistentActorSpec { class SnapshottingBecomingPersistentActor(name: String, probe: ActorRef) extends SnapshottingPersistentActor(name, probe) { val becomingRecover: Receive = { - case msg: SnapshotOffer ⇒ + case msg: SnapshotOffer => context.become(becomingCommand) // sending ourself a normal message here also tests // that we stash them until recovery is complete @@ -243,7 +243,7 @@ object PersistentActorSpec { override def receiveRecover = becomingRecover.orElse(super.receiveRecover) val becomingCommand: Receive = receiveCommand orElse { - case "It's changing me" ⇒ probe ! "I am becoming" + case "It's changing me" => probe ! "I am becoming" } } class SnapshottingBecomingPersistentActorWithLevelDbRuntimePluginConfig(name: String, probe: ActorRef, val providedConfig: Config) @@ -253,7 +253,7 @@ object PersistentActorSpec { class ReplyInEventHandlerPersistentActor(name: String) extends ExamplePersistentActor(name) { val receiveCommand: Receive = { - case Cmd("a") ⇒ persist(Evt("a"))(evt ⇒ sender() ! evt.data) + case Cmd("a") => persist(Evt("a"))(evt => sender() ! evt.data) } } class ReplyInEventHandlerPersistentActorWithLevelDbRuntimePluginConfig(name: String, val providedConfig: Config) @@ -265,9 +265,9 @@ object PersistentActorSpec { var counter = 0 val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => sender() ! data - persistAsync(Evt(s"$data-${incCounter()}")) { evt ⇒ + persistAsync(Evt(s"$data-${incCounter()}")) { evt => sender() ! evt.data } } @@ -279,8 +279,8 @@ object PersistentActorSpec { override protected def onPersistFailure(cause: Throwable, event: Any, seqNr: Long): Unit = event match { - case Evt(data) ⇒ sender() ! s"Failure: $data" - case _ ⇒ super.onPersistFailure(cause, event, seqNr) + case Evt(data) => sender() ! s"Failure: $data" + case _ => super.onPersistFailure(cause, event, seqNr) } } @@ -293,11 +293,11 @@ object PersistentActorSpec { var counter = 0 val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => sender() ! data - 1 to 3 foreach { i ⇒ - persistAsync(Evt(s"$data-${incCounter()}")) { evt ⇒ + 1 to 3 foreach { i => + persistAsync(Evt(s"$data-${incCounter()}")) { evt => sender() ! ("a" + evt.data.toString.drop(1)) // c-1 => a-1, as in "ack" } } @@ -319,16 +319,16 @@ object PersistentActorSpec { val sendMsgCounter = new AtomicInteger() val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => sender() ! data val event = Evt(data) - persistAsync(event) { evt ⇒ + persistAsync(event) { evt => // be way slower, in order to be overtaken by the other callback Thread.sleep(300) sender() ! s"${evt.data}-a-${sendMsgCounter.incrementAndGet()}" } - persistAsync(event) { evt ⇒ sender() ! s"${evt.data}-b-${sendMsgCounter.incrementAndGet()}" } + persistAsync(event) { evt => sender() ! s"${evt.data}-b-${sendMsgCounter.incrementAndGet()}" } } } class AsyncPersistSameEventTwicePersistentActorWithLevelDbRuntimePluginConfig(name: String, val providedConfig: Config) @@ -339,15 +339,15 @@ object PersistentActorSpec { class PersistAllNilPersistentActor(name: String) extends ExamplePersistentActor(name) { val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data: String) if data contains "defer" ⇒ + case Cmd(data: String) if data contains "defer" => deferAsync("before-nil")(sender() ! _) - persistAll(Nil)(_ ⇒ sender() ! "Nil") + persistAll(Nil)(_ => sender() ! "Nil") deferAsync("after-nil")(sender() ! _) sender() ! data - case Cmd(data: String) if data contains "persist" ⇒ + case Cmd(data: String) if data contains "persist" => persist("before-nil")(sender() ! _) - persistAll(Nil)(_ ⇒ sender() ! "Nil") + persistAll(Nil)(_ => sender() ! "Nil") deferAsync("after-nil")(sender() ! _) sender() ! data } @@ -362,19 +362,19 @@ object PersistentActorSpec { var counter = 0 val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => sender() ! data - persist(Evt(data + "-e1")) { evt ⇒ + persist(Evt(data + "-e1")) { evt => sender() ! s"${evt.data}-${incCounter()}" } // this should be happily executed - persistAsync(Evt(data + "-ea2")) { evt ⇒ + persistAsync(Evt(data + "-ea2")) { evt => sender() ! s"${evt.data}-${incCounter()}" } - persist(Evt(data + "-e3")) { evt ⇒ + persist(Evt(data + "-e3")) { evt => sender() ! s"${evt.data}-${incCounter()}" } } @@ -394,14 +394,14 @@ object PersistentActorSpec { var sendMsgCounter = 0 val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => sender() ! data - persist(Evt(data + "-e1")) { evt ⇒ + persist(Evt(data + "-e1")) { evt => sender() ! s"${evt.data}-${incCounter()}" } - persistAsync(Evt(data + "-ea2")) { evt ⇒ + persistAsync(Evt(data + "-ea2")) { evt => sender() ! s"${evt.data}-${incCounter()}" } } @@ -420,8 +420,8 @@ object PersistentActorSpec { var counter = 0 val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ - persistAsync(Evt(data)) { evt ⇒ + case Cmd(data) => + persistAsync(Evt(data)) { evt => if (data != evt.data) sender() ! s"Expected [$data] bot got [${evt.data}]" if (evt.data == "done") @@ -441,7 +441,7 @@ object PersistentActorSpec { class AnyValEventPersistentActor(name: String) extends ExamplePersistentActor(name) { val receiveCommand: Receive = { - case Cmd("a") ⇒ persist(5)(evt ⇒ sender() ! evt) + case Cmd("a") => persist(5)(evt => sender() ! evt) } } class AnyValEventPersistentActorWithLevelDbRuntimePluginConfig(name: String, val providedConfig: Config) @@ -451,12 +451,12 @@ object PersistentActorSpec { class HandleRecoveryFinishedEventPersistentActor(name: String, probe: ActorRef) extends SnapshottingPersistentActor(name, probe) { val sendingRecover: Receive = { - case msg: SnapshotOffer ⇒ + case msg: SnapshotOffer => // sending ourself a normal message tests // that we stash them until recovery is complete self ! "I am the stashed" super.receiveRecover(msg) - case RecoveryCompleted ⇒ + case RecoveryCompleted => probe ! RecoveryCompleted self ! "I am the recovered" updateState(Evt(RecoveryCompleted)) @@ -465,7 +465,7 @@ object PersistentActorSpec { override def receiveRecover = sendingRecover.orElse(super.receiveRecover) override def receiveCommand: Receive = super.receiveCommand orElse { - case s: String ⇒ probe ! s + case s: String => probe ! s } } @@ -475,19 +475,19 @@ object PersistentActorSpec { extends HandleRecoveryFinishedEventPersistentActor(name, probe) with InmemRuntimePluginConfig trait DeferActor extends PersistentActor { - def doDefer[A](event: A)(handler: A ⇒ Unit): Unit + def doDefer[A](event: A)(handler: A => Unit): Unit } trait DeferSync { - this: PersistentActor ⇒ - def doDefer[A](event: A)(handler: A ⇒ Unit): Unit = defer(event)(handler) + this: PersistentActor => + def doDefer[A](event: A)(handler: A => Unit): Unit = defer(event)(handler) } trait DeferAsync { - this: PersistentActor ⇒ - def doDefer[A](event: A)(handler: A ⇒ Unit): Unit = deferAsync(event)(handler) + this: PersistentActor => + def doDefer[A](event: A)(handler: A => Unit): Unit = deferAsync(event)(handler) } abstract class DeferringWithPersistActor(name: String) extends ExamplePersistentActor(name) with DeferActor { val receiveCommand: Receive = { - case Cmd(data) ⇒ + case Cmd(data) => doDefer("d-1") { sender() ! _ } persist(s"$data-2") { sender() ! _ } doDefer("d-3") { sender() ! _ } @@ -507,7 +507,7 @@ object PersistentActorSpec { abstract class DeferringWithAsyncPersistActor(name: String) extends ExamplePersistentActor(name) with DeferActor { val receiveCommand: Receive = { - case Cmd(data) ⇒ + case Cmd(data) => doDefer(s"d-$data-1") { sender() ! _ } persistAsync(s"pa-$data-2") { sender() ! _ } doDefer(s"d-$data-3") { sender() ! _ } @@ -527,7 +527,7 @@ object PersistentActorSpec { abstract class DeferringMixedCallsPPADDPADPersistActor(name: String) extends ExamplePersistentActor(name) with DeferActor { val receiveCommand: Receive = { - case Cmd(data) ⇒ + case Cmd(data) => persist(s"p-$data-1") { sender() ! _ } persistAsync(s"pa-$data-2") { sender() ! _ } doDefer(s"d-$data-3") { sender() ! _ } @@ -549,7 +549,7 @@ object PersistentActorSpec { abstract class DeferringWithNoPersistCallsPersistActor(name: String) extends ExamplePersistentActor(name) with DeferActor { val receiveCommand: Receive = { - case Cmd(_) ⇒ + case Cmd(_) => doDefer("d-1") { sender() ! _ } doDefer("d-2") { sender() ! _ } doDefer("d-3") { sender() ! _ } @@ -568,10 +568,10 @@ object PersistentActorSpec { abstract class DeferringActor(name: String) extends ExamplePersistentActor(name) with DeferActor { val receiveCommand: Receive = { - case Cmd(data) ⇒ + case Cmd(data) => sender() ! data - persist(()) { _ ⇒ } // skip calling defer immediately because of empty pending invocations - doDefer(Evt(s"$data-defer")) { evt ⇒ + persist(()) { _ => } // skip calling defer immediately because of empty pending invocations + doDefer(Evt(s"$data-defer")) { evt => sender() ! evt.data } } @@ -589,14 +589,14 @@ object PersistentActorSpec { class StressOrdering(name: String) extends ExamplePersistentActor(name) { val receiveCommand: Receive = { - case LatchCmd(latch, data) ⇒ + case LatchCmd(latch, data) => sender() ! data Await.ready(latch, 5.seconds) - persistAsync(data)(_ ⇒ ()) - case Cmd(data) ⇒ + persistAsync(data)(_ => ()) + case Cmd(data) => sender() ! data - persist(data)(_ ⇒ ()) - case s: String ⇒ + persist(data)(_ => ()) + case s: String => sender() ! s } } @@ -609,7 +609,7 @@ object PersistentActorSpec { var master: ActorRef = _ val receiveCommand: Receive = { - case "Boom" ⇒ + case "Boom" => master = sender() throw new TestException("boom") } @@ -622,7 +622,7 @@ object PersistentActorSpec { } override def receiveRecover = { - case _ ⇒ () + case _ => () } } @@ -633,15 +633,15 @@ object PersistentActorSpec { class MultipleAndNestedPersists(name: String, probe: ActorRef) extends ExamplePersistentActor(name) { val receiveCommand: Receive = { - case s: String ⇒ + case s: String => probe ! s - persist(s + "-outer-1") { outer ⇒ + persist(s + "-outer-1") { outer => probe ! outer - persist(s + "-inner-1") { inner ⇒ probe ! inner } + persist(s + "-inner-1") { inner => probe ! inner } } - persist(s + "-outer-2") { outer ⇒ + persist(s + "-outer-2") { outer => probe ! outer - persist(s + "-inner-2") { inner ⇒ probe ! inner } + persist(s + "-inner-2") { inner => probe ! inner } } } } @@ -652,15 +652,15 @@ object PersistentActorSpec { class MultipleAndNestedPersistAsyncs(name: String, probe: ActorRef) extends ExamplePersistentActor(name) { val receiveCommand: Receive = { - case s: String ⇒ + case s: String => probe ! s - persistAsync(s + "-outer-1") { outer ⇒ + persistAsync(s + "-outer-1") { outer => probe ! outer - persistAsync(s + "-inner-1") { inner ⇒ probe ! inner } + persistAsync(s + "-inner-1") { inner => probe ! inner } } - persistAsync(s + "-outer-2") { outer ⇒ + persistAsync(s + "-outer-2") { outer => probe ! outer - persistAsync(s + "-inner-2") { inner ⇒ probe ! inner } + persistAsync(s + "-inner-2") { inner => probe ! inner } } } } @@ -672,7 +672,7 @@ object PersistentActorSpec { class DeeplyNestedPersistAsyncs(name: String, maxDepth: Int, probe: ActorRef) extends ExamplePersistentActor(name) { var currentDepths = Map.empty[String, Int].withDefaultValue(1) - def weMustGoDeeper: String ⇒ Unit = { dWithDepth ⇒ + def weMustGoDeeper: String => Unit = { dWithDepth => val d = dWithDepth.split("-").head probe ! dWithDepth if (currentDepths(d) < maxDepth) { @@ -685,7 +685,7 @@ object PersistentActorSpec { } val receiveCommand: Receive = { - case s: String ⇒ + case s: String => probe ! s persistAsync(s + "-" + 1)(weMustGoDeeper) } @@ -697,17 +697,17 @@ object PersistentActorSpec { class NestedPersistNormalAndAsyncs(name: String, probe: ActorRef) extends ExamplePersistentActor(name) { val receiveCommand: Receive = { - case s: String ⇒ + case s: String => probe ! s - persist(s + "-outer-1") { outer ⇒ + persist(s + "-outer-1") { outer => probe ! outer - persistAsync(s + "-inner-async-1") { inner ⇒ + persistAsync(s + "-inner-async-1") { inner => probe ! inner } } - persist(s + "-outer-2") { outer ⇒ + persist(s + "-outer-2") { outer => probe ! outer - persistAsync(s + "-inner-async-2") { inner ⇒ + persistAsync(s + "-inner-async-2") { inner => probe ! inner } } @@ -720,17 +720,17 @@ object PersistentActorSpec { class NestedPersistAsyncsAndNormal(name: String, probe: ActorRef) extends ExamplePersistentActor(name) { val receiveCommand: Receive = { - case s: String ⇒ + case s: String => probe ! s - persistAsync(s + "-outer-async-1") { outer ⇒ + persistAsync(s + "-outer-async-1") { outer => probe ! outer - persist(s + "-inner-1") { inner ⇒ + persist(s + "-inner-1") { inner => probe ! inner } } - persistAsync(s + "-outer-async-2") { outer ⇒ + persistAsync(s + "-outer-async-2") { outer => probe ! outer - persist(s + "-inner-2") { inner ⇒ + persist(s + "-inner-2") { inner => probe ! inner } } @@ -743,15 +743,15 @@ object PersistentActorSpec { class NestedPersistInAsyncEnforcesStashing(name: String, probe: ActorRef) extends ExamplePersistentActor(name) { val receiveCommand: Receive = { - case s: String ⇒ + case s: String => probe ! s - persistAsync(s + "-outer-async") { outer ⇒ + persistAsync(s + "-outer-async") { outer => probe ! outer - persist(s + "-inner") { inner ⇒ + persist(s + "-inner") { inner => probe ! inner Thread.sleep(1000) // really long wait here... // the next incoming command must be handled by the following function - context.become({ case _ ⇒ sender() ! "done" }) + context.become({ case _ => sender() ! "done" }) } } } @@ -764,7 +764,7 @@ object PersistentActorSpec { class DeeplyNestedPersists(name: String, maxDepth: Int, probe: ActorRef) extends ExamplePersistentActor(name) { var currentDepths = Map.empty[String, Int].withDefaultValue(1) - def weMustGoDeeper: String ⇒ Unit = { dWithDepth ⇒ + def weMustGoDeeper: String => Unit = { dWithDepth => val d = dWithDepth.split("-").head probe ! dWithDepth if (currentDepths(d) < maxDepth) { @@ -777,7 +777,7 @@ object PersistentActorSpec { } val receiveCommand: Receive = { - case s: String ⇒ + case s: String => probe ! s persist(s + "-" + 1)(weMustGoDeeper) } @@ -791,13 +791,13 @@ object PersistentActorSpec { override def persistenceId: String = "StackableTestPersistentActor" def receiveCommand = { - case "restart" ⇒ throw new Exception("triggering restart") with NoStackTrace { + case "restart" => throw new Exception("triggering restart") with NoStackTrace { override def toString = "Boom!" } } def receiveRecover = { - case _ ⇒ () + case _ => () } override def preStart(): Unit = { @@ -829,7 +829,7 @@ object PersistentActorSpec { object StackableTestPersistentActor { trait BaseActor extends Actor { - this: StackableTestPersistentActor ⇒ + this: StackableTestPersistentActor => override protected[akka] def aroundPreStart() = { probe ! "base aroundPreStart" super.aroundPreStart() @@ -859,7 +859,7 @@ object PersistentActorSpec { } trait MixinActor extends Actor { - this: StackableTestPersistentActor ⇒ + this: StackableTestPersistentActor => override protected[akka] def aroundPreStart() = { probe ! "mixin aroundPreStart" super.aroundPreStart() @@ -892,10 +892,10 @@ object PersistentActorSpec { class PersistInRecovery(name: String) extends ExamplePersistentActor(name) { override def receiveRecover = { - case Evt("invalid") ⇒ + case Evt("invalid") => persist(Evt("invalid-recovery"))(updateState) - case e: Evt ⇒ updateState(e) - case RecoveryCompleted ⇒ + case e: Evt => updateState(e) + case RecoveryCompleted => persistAsync(Evt("rc-1"))(updateState) persist(Evt("rc-2"))(updateState) persistAsync(Evt("rc-3"))(updateState) @@ -904,7 +904,7 @@ object PersistentActorSpec { override def onRecoveryFailure(cause: scala.Throwable, event: Option[Any]): Unit = () def receiveCommand = commonBehavior orElse { - case Cmd(d) ⇒ persist(Evt(d))(updateState) + case Cmd(d) => persist(Evt(d))(updateState) } } class PersistInRecoveryWithLevelDbRuntimePluginConfig(name: String, val providedConfig: Config) @@ -1167,20 +1167,20 @@ abstract class PersistentActorSpec(config: Config) extends PersistenceSpec(confi } "support multiple persistAsync calls for one command, and execute them 'when possible', not hindering command processing" in { val persistentActor = asyncPersistThreeTimesPersistentActor - val commands = 1 to 10 map { i ⇒ Cmd(s"c-$i") } + val commands = 1 to 10 map { i => Cmd(s"c-$i") } - commands foreach { i ⇒ + commands foreach { i => Thread.sleep(Random.nextInt(10)) persistentActor ! i } val all: Seq[String] = this.receiveN(40).asInstanceOf[Seq[String]] // each command = 1 reply + 3 event-replies - val replies = all.filter(r ⇒ r.count(_ == '-') == 1) + val replies = all.filter(r => r.count(_ == '-') == 1) replies should equal(commands.map(_.data)) - val expectedAcks = (3 to 32) map { i ⇒ s"a-${i / 3}-${i - 2}" } - val acks = all.filter(r ⇒ r.count(_ == '-') == 2) + val expectedAcks = (3 to 32) map { i => s"a-${i / 3}-${i - 2}" } + val acks = all.filter(r => r.count(_ == '-') == 2) acks should equal(expectedAcks) } "reply to the original sender() of a command, even when using persistAsync" in { @@ -1188,11 +1188,11 @@ abstract class PersistentActorSpec(config: Config) extends PersistenceSpec(confi // but as we want to remove it soon, keeping the explicit test here. val persistentActor = asyncPersistThreeTimesPersistentActor - val commands = 1 to 10 map { i ⇒ Cmd(s"c-$i") } + val commands = 1 to 10 map { i => Cmd(s"c-$i") } val probes = Vector.fill(10)(TestProbe()) (probes zip commands) foreach { - case (p, c) ⇒ + case (p, c) => persistentActor.tell(c, p.ref) } @@ -1268,9 +1268,9 @@ abstract class PersistentActorSpec(config: Config) extends PersistenceSpec(confi } "correlate persistAsync handlers after restart" in { val persistentActor = asyncPersistHandlerCorrelationCheck - for (n ← 1 to 100) persistentActor ! Cmd(n) + for (n <- 1 to 100) persistentActor ! Cmd(n) persistentActor ! "boom" - for (n ← 1 to 20) persistentActor ! Cmd(n) + for (n <- 1 to 20) persistentActor ! Cmd(n) persistentActor ! Cmd("done") expectMsg(5.seconds, "done") } diff --git a/akka-persistence/src/test/scala/akka/persistence/PersistentActorStashingSpec.scala b/akka-persistence/src/test/scala/akka/persistence/PersistentActorStashingSpec.scala index 258280f1f2..a620eeb9fc 100644 --- a/akka-persistence/src/test/scala/akka/persistence/PersistentActorStashingSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/PersistentActorStashingSpec.scala @@ -21,13 +21,13 @@ object PersistentActorStashingSpec { var askedForDelete: Option[ActorRef] = None val updateState: Receive = { - case Evt(data) ⇒ events = data :: events - case d @ Some(ref: ActorRef) ⇒ askedForDelete = d.asInstanceOf[Some[ActorRef]] + case Evt(data) => events = data :: events + case d @ Some(ref: ActorRef) => askedForDelete = d.asInstanceOf[Some[ActorRef]] } val commonBehavior: Receive = { - case "boom" ⇒ throw new TestException("boom") - case GetState ⇒ sender() ! events.reverse + case "boom" => throw new TestException("boom") + case GetState => sender() ! events.reverse } def unstashBehavior: Receive @@ -39,67 +39,67 @@ object PersistentActorStashingSpec { var stashed = false val receiveCommand: Receive = unstashBehavior orElse { - case Cmd("a") if !stashed ⇒ + case Cmd("a") if !stashed => stash(); stashed = true - case Cmd("a") ⇒ sender() ! "a" - case Cmd("b") ⇒ persist(Evt("b"))(evt ⇒ sender() ! evt.data) + case Cmd("a") => sender() ! "a" + case Cmd("b") => persist(Evt("b"))(evt => sender() ! evt.data) } def unstashBehavior: Receive = { - case Cmd("c") ⇒ unstashAll(); sender() ! "c" + case Cmd("c") => unstashAll(); sender() ! "c" } } class UserStashWithinHandlerPersistentActor(name: String) extends UserStashPersistentActor(name: String) { override def unstashBehavior: Receive = { - case Cmd("c") ⇒ persist(Evt("c")) { evt ⇒ sender() ! evt.data; unstashAll() } + case Cmd("c") => persist(Evt("c")) { evt => sender() ! evt.data; unstashAll() } } } class UserStashManyPersistentActor(name: String) extends StashExamplePersistentActor(name) { val receiveCommand: Receive = commonBehavior orElse { - case Cmd("a") ⇒ persist(Evt("a")) { evt ⇒ + case Cmd("a") => persist(Evt("a")) { evt => updateState(evt) context.become(processC) } - case Cmd("b-1") ⇒ persist(Evt("b-1"))(updateState) - case Cmd("b-2") ⇒ persist(Evt("b-2"))(updateState) + case Cmd("b-1") => persist(Evt("b-1"))(updateState) + case Cmd("b-2") => persist(Evt("b-2"))(updateState) } val processC: Receive = unstashBehavior orElse { - case other ⇒ stash() + case other => stash() } def unstashBehavior: Receive = { - case Cmd("c") ⇒ - persist(Evt("c")) { evt ⇒ updateState(evt); context.unbecome() } + case Cmd("c") => + persist(Evt("c")) { evt => updateState(evt); context.unbecome() } unstashAll() } } class UserStashWithinHandlerManyPersistentActor(name: String) extends UserStashManyPersistentActor(name) { override def unstashBehavior: Receive = { - case Cmd("c") ⇒ persist(Evt("c")) { evt ⇒ updateState(evt); context.unbecome(); unstashAll() } + case Cmd("c") => persist(Evt("c")) { evt => updateState(evt); context.unbecome(); unstashAll() } } } class UserStashFailurePersistentActor(name: String) extends StashExamplePersistentActor(name) { val receiveCommand: Receive = commonBehavior orElse { - case Cmd(data) ⇒ + case Cmd(data) => if (data == "b-2") throw new TestException("boom") - persist(Evt(data)) { evt ⇒ + persist(Evt(data)) { evt => updateState(evt) if (data == "a") context.become(otherCommandHandler) } } val otherCommandHandler: Receive = unstashBehavior orElse { - case other ⇒ stash() + case other => stash() } def unstashBehavior: Receive = { - case Cmd("c") ⇒ - persist(Evt("c")) { evt ⇒ + case Cmd("c") => + persist(Evt("c")) { evt => updateState(evt) context.unbecome() } @@ -109,8 +109,8 @@ object PersistentActorStashingSpec { class UserStashWithinHandlerFailureCallbackPersistentActor(name: String) extends UserStashFailurePersistentActor(name) { override def unstashBehavior: Receive = { - case Cmd("c") ⇒ - persist(Evt("c")) { evt ⇒ + case Cmd("c") => + persist(Evt("c")) { evt => updateState(evt) context.unbecome() unstashAll() @@ -122,20 +122,20 @@ object PersistentActorStashingSpec { var stashed = false val receiveCommand: Receive = commonBehavior orElse unstashBehavior orElse { - case Cmd("a") ⇒ persistAsync(Evt("a"))(updateState) - case Cmd("b") if !stashed ⇒ + case Cmd("a") => persistAsync(Evt("a"))(updateState) + case Cmd("b") if !stashed => stash(); stashed = true - case Cmd("b") ⇒ persistAsync(Evt("b"))(updateState) + case Cmd("b") => persistAsync(Evt("b"))(updateState) } override def unstashBehavior: Receive = { - case Cmd("c") ⇒ persistAsync(Evt("c"))(updateState); unstashAll() + case Cmd("c") => persistAsync(Evt("c"))(updateState); unstashAll() } } class AsyncStashingWithinHandlerPersistentActor(name: String) extends AsyncStashingPersistentActor(name) { override def unstashBehavior: Receive = { - case Cmd("c") ⇒ persistAsync(Evt("c")) { evt ⇒ updateState(evt); unstashAll() } + case Cmd("c") => persistAsync(Evt("c")) { evt => updateState(evt); unstashAll() } } } @@ -144,19 +144,19 @@ object PersistentActorStashingSpec { val child = context.actorOf(Props(classOf[StashWithinHandlerPersistentActor], name)) override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) { - case ex: Exception ⇒ + case ex: Exception => target ! ex Resume } def receive = { - case c: Cmd ⇒ child ! c + case c: Cmd => child ! c } } class StashWithinHandlerPersistentActor(name: String) extends NamedPersistentActor(name) { val receiveRecover: Receive = { - case _ ⇒ // ignore + case _ => // ignore } def stashWithinHandler(evt: Evt) = { @@ -164,10 +164,10 @@ object PersistentActorStashingSpec { } val receiveCommand: Receive = { - case Cmd("a") ⇒ persist(Evt("a"))(stashWithinHandler) - case Cmd("b") ⇒ persistAsync(Evt("b"))(stashWithinHandler) - case Cmd("c") ⇒ - persist(Evt("x")) { _ ⇒ } + case Cmd("a") => persist(Evt("a"))(stashWithinHandler) + case Cmd("b") => persistAsync(Evt("b"))(stashWithinHandler) + case Cmd("c") => + persist(Evt("x")) { _ => } deferAsync(Evt("c"))(stashWithinHandler) } @@ -194,8 +194,8 @@ abstract class PersistentActorStashingSpec(config: Config) extends PersistenceSp "support user stash operations with several stashed messages" in { val persistentActor = namedPersistentActor[T] val n = 10 - val cmds = 1 to n flatMap (_ ⇒ List(Cmd("a"), Cmd("b-1"), Cmd("b-2"), Cmd("c"))) - val evts = 1 to n flatMap (_ ⇒ List("a", "c", "b-1", "b-2")) + val cmds = 1 to n flatMap (_ => List(Cmd("a"), Cmd("b-1"), Cmd("b-2"), Cmd("c"))) + val evts = 1 to n flatMap (_ => List("a", "c", "b-1", "b-2")) cmds foreach (persistentActor ! _) persistentActor ! GetState @@ -235,7 +235,7 @@ abstract class PersistentActorStashingSpec(config: Config) extends PersistenceSp def stashInPersist(s: String): Unit = { actor ! Cmd(s) expectMsgPF() { - case ex: IllegalStateException if ex.getMessage.startsWith("Do not call stash") ⇒ () + case ex: IllegalStateException if ex.getMessage.startsWith("Do not call stash") => () } } diff --git a/akka-persistence/src/test/scala/akka/persistence/RecoveryPermitterSpec.scala b/akka-persistence/src/test/scala/akka/persistence/RecoveryPermitterSpec.scala index e1766dad17..eaedf6ca44 100644 --- a/akka-persistence/src/test/scala/akka/persistence/RecoveryPermitterSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/RecoveryPermitterSpec.scala @@ -30,13 +30,13 @@ object RecoveryPermitterSpec { } override def receiveRecover: Receive = { - case RecoveryCompleted ⇒ + case RecoveryCompleted => probe ! RecoveryCompleted if (throwFromRecoveryCompleted) throw new TestExc } override def receiveCommand: Receive = { - case "stop" ⇒ + case "stop" => context.stop(self) } } @@ -169,7 +169,7 @@ class RecoveryPermitterSpec extends PersistenceSpec(ConfigFactory.parseString( p3.expectMsg(RecoveryCompleted) p3.expectMsg("postStop") // it's restarting - (1 to 5).foreach { _ ⇒ + (1 to 5).foreach { _ => p3.expectMsg(RecoveryCompleted) p3.expectMsg("postStop") } diff --git a/akka-persistence/src/test/scala/akka/persistence/SnapshotDirectoryFailureSpec.scala b/akka-persistence/src/test/scala/akka/persistence/SnapshotDirectoryFailureSpec.scala index e92e88f983..51e6bae73e 100644 --- a/akka-persistence/src/test/scala/akka/persistence/SnapshotDirectoryFailureSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/SnapshotDirectoryFailureSpec.scala @@ -18,13 +18,13 @@ object SnapshotDirectoryFailureSpec { override def persistenceId: String = name override def receiveRecover: Receive = { - case SnapshotOffer(md, s) ⇒ probe ! ((md, s)) + case SnapshotOffer(md, s) => probe ! ((md, s)) } override def receiveCommand = { - case s: String ⇒ saveSnapshot(s) - case SaveSnapshotSuccess(md) ⇒ probe ! md.sequenceNr - case other ⇒ probe ! other + case s: String => saveSnapshot(s) + case SaveSnapshotSuccess(md) => probe ! md.sequenceNr + case other => probe ! other } } } diff --git a/akka-persistence/src/test/scala/akka/persistence/SnapshotFailureRobustnessSpec.scala b/akka-persistence/src/test/scala/akka/persistence/SnapshotFailureRobustnessSpec.scala index df4846b5b6..0af56a700a 100644 --- a/akka-persistence/src/test/scala/akka/persistence/SnapshotFailureRobustnessSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/SnapshotFailureRobustnessSpec.scala @@ -24,14 +24,14 @@ object SnapshotFailureRobustnessSpec { class SaveSnapshotTestPersistentActor(name: String, probe: ActorRef) extends NamedPersistentActor(name) { override def receiveRecover: Receive = { - case SnapshotOffer(md, s) ⇒ probe ! ((md, s)) - case other ⇒ probe ! other + case SnapshotOffer(md, s) => probe ! ((md, s)) + case other => probe ! other } override def receiveCommand = { - case Cmd(payload) ⇒ persist(payload)(_ ⇒ saveSnapshot(payload)) - case SaveSnapshotSuccess(md) ⇒ probe ! md.sequenceNr - case other ⇒ probe ! other + case Cmd(payload) => persist(payload)(_ => saveSnapshot(payload)) + case SaveSnapshotSuccess(md) => probe ! md.sequenceNr + case other => probe ! other } } @@ -42,33 +42,33 @@ object SnapshotFailureRobustnessSpec { "akka.persistence.snapshot-store.local-delete-fail" override def receiveRecover: Receive = { - case SnapshotOffer(md, s) ⇒ probe ! ((md, s)) - case other ⇒ probe ! other + case SnapshotOffer(md, s) => probe ! ((md, s)) + case other => probe ! other } override def receiveCommand = { - case Cmd(payload) ⇒ persist(payload)(_ ⇒ saveSnapshot(payload)) - case DeleteSnapshot(seqNr) ⇒ deleteSnapshot(seqNr) - case DeleteSnapshots(crit) ⇒ deleteSnapshots(crit) - case SaveSnapshotSuccess(md) ⇒ probe ! md.sequenceNr - case other ⇒ probe ! other + case Cmd(payload) => persist(payload)(_ => saveSnapshot(payload)) + case DeleteSnapshot(seqNr) => deleteSnapshot(seqNr) + case DeleteSnapshots(crit) => deleteSnapshots(crit) + case SaveSnapshotSuccess(md) => probe ! md.sequenceNr + case other => probe ! other } } class LoadSnapshotTestPersistentActor(name: String, probe: ActorRef) extends NamedPersistentActor(name) { override def receiveRecover: Receive = { - case SnapshotOffer(md, s) ⇒ probe ! ((md, s)) - case payload: String ⇒ probe ! s"${payload}-${lastSequenceNr}" - case other ⇒ probe ! other + case SnapshotOffer(md, s) => probe ! ((md, s)) + case payload: String => probe ! s"${payload}-${lastSequenceNr}" + case other => probe ! other } override def receiveCommand = { - case Cmd(payload) ⇒ - persist(payload) { _ ⇒ + case Cmd(payload) => + persist(payload) { _ => probe ! s"${payload}-${lastSequenceNr}" } - case SnapshotOffer(md, s) ⇒ probe ! ((md, s)) - case other ⇒ probe ! other + case SnapshotOffer(md, s) => probe ! ((md, s)) + case other => probe ! other } } @@ -121,7 +121,7 @@ class SnapshotFailureRobustnessSpec extends PersistenceSpec(PersistenceSpec.conf val lPersistentActor = system.actorOf(Props(classOf[LoadSnapshotTestPersistentActor], name, testActor)) expectMsgType[Logging.Error].message.toString should startWith("Error loading snapshot") expectMsgPF() { - case (SnapshotMetadata(`persistenceId`, 1, timestamp), state) ⇒ + case (SnapshotMetadata(`persistenceId`, 1, timestamp), state) => state should ===("blahonga") timestamp should be > (0L) } @@ -156,7 +156,7 @@ class SnapshotFailureRobustnessSpec extends PersistenceSpec(PersistenceSpec.conf system.eventStream.subscribe(testActor, classOf[Logging.Error]) try { val lPersistentActor = system.actorOf(Props(classOf[LoadSnapshotTestPersistentActor], name, testActor)) - (1 to 3).foreach { _ ⇒ + (1 to 3).foreach { _ => expectMsgType[Logging.Error].message.toString should startWith("Error loading snapshot") } expectMsgType[Logging.Error].message.toString should startWith("Persistence failure") @@ -178,7 +178,7 @@ class SnapshotFailureRobustnessSpec extends PersistenceSpec(PersistenceSpec.conf expectMsg(1) p ! DeleteSnapshot(1) expectMsgPF() { - case DeleteSnapshotFailure(SnapshotMetadata(`persistenceId`, 1, timestamp), cause) ⇒ + case DeleteSnapshotFailure(SnapshotMetadata(`persistenceId`, 1, timestamp), cause) => // ok, expected failure cause.getMessage should include("Failed to delete") } @@ -195,7 +195,7 @@ class SnapshotFailureRobustnessSpec extends PersistenceSpec(PersistenceSpec.conf val criteria = SnapshotSelectionCriteria(maxSequenceNr = 10) p ! DeleteSnapshots(criteria) expectMsgPF() { - case DeleteSnapshotsFailure(criteria, cause) ⇒ + case DeleteSnapshotsFailure(criteria, cause) => // ok, expected failure cause.getMessage should include("Failed to delete") } diff --git a/akka-persistence/src/test/scala/akka/persistence/SnapshotRecoveryLocalStoreSpec.scala b/akka-persistence/src/test/scala/akka/persistence/SnapshotRecoveryLocalStoreSpec.scala index e147aa5b15..bb0b9b6877 100644 --- a/akka-persistence/src/test/scala/akka/persistence/SnapshotRecoveryLocalStoreSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/SnapshotRecoveryLocalStoreSpec.scala @@ -16,12 +16,12 @@ object SnapshotRecoveryLocalStoreSpec { class SaveSnapshotTestPersistentActor(name: String, probe: ActorRef) extends NamedPersistentActor(name) { var state = s"State for actor ${name}" def receiveCommand = { - case TakeSnapshot ⇒ saveSnapshot(state) - case SaveSnapshotSuccess(md) ⇒ probe ! md.sequenceNr - case GetState ⇒ probe ! state + case TakeSnapshot => saveSnapshot(state) + case SaveSnapshotSuccess(md) => probe ! md.sequenceNr + case GetState => probe ! state } def receiveRecover = { - case _ ⇒ + case _ => } } @@ -31,10 +31,10 @@ object SnapshotRecoveryLocalStoreSpec { override def recovery = Recovery(toSequenceNr = 0) def receiveCommand = { - case _ ⇒ + case _ => } def receiveRecover = { - case other ⇒ probe ! other + case other => probe ! other } } } @@ -58,7 +58,7 @@ class SnapshotRecoveryLocalStoreSpec extends PersistenceSpec(PersistenceSpec.con val recoveringActor = system.actorOf(Props(classOf[LoadSnapshotTestPersistentActor], persistenceId, testActor)) - expectMsgPF() { case SnapshotOffer(SnapshotMetadata(`persistenceId`, seqNo, timestamp), state) ⇒ } + expectMsgPF() { case SnapshotOffer(SnapshotMetadata(`persistenceId`, seqNo, timestamp), state) => } expectMsg(RecoveryCompleted) } diff --git a/akka-persistence/src/test/scala/akka/persistence/SnapshotSerializationSpec.scala b/akka-persistence/src/test/scala/akka/persistence/SnapshotSerializationSpec.scala index c23df0cadd..b5b5194350 100644 --- a/akka-persistence/src/test/scala/akka/persistence/SnapshotSerializationSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/SnapshotSerializationSpec.scala @@ -17,8 +17,8 @@ object SnapshotSerializationSpec { object XXXXXXXXXXXXXXXXXXXX { class MySnapshot(val id: String) extends SerializationMarker { override def equals(obj: scala.Any) = obj match { - case s: MySnapshot ⇒ s.id.equals(id) - case _ ⇒ false + case s: MySnapshot => s.id.equals(id) + case _ => false } } } @@ -33,8 +33,8 @@ object SnapshotSerializationSpec { val bStream = new ByteArrayOutputStream() val pStream = new PrintStream(bStream) val msg: String = obj match { - case s: MySnapshot ⇒ s.id - case _ ⇒ "unknown" + case s: MySnapshot => s.id + case _ => "unknown" } pStream.println(msg) bStream.toByteArray @@ -50,15 +50,15 @@ object SnapshotSerializationSpec { class TestPersistentActor(name: String, probe: ActorRef) extends NamedPersistentActor(name) { override def receiveRecover: Receive = { - case SnapshotOffer(md, s) ⇒ probe ! ((md, s)) - case RecoveryCompleted ⇒ // ignore - case other ⇒ probe ! other + case SnapshotOffer(md, s) => probe ! ((md, s)) + case RecoveryCompleted => // ignore + case other => probe ! other } override def receiveCommand = { - case s: String ⇒ saveSnapshot(new MySnapshot(s)) - case SaveSnapshotSuccess(md) ⇒ probe ! md.sequenceNr - case other ⇒ probe ! other + case s: String => saveSnapshot(new MySnapshot(s)) + case SaveSnapshotSuccess(md) => probe ! md.sequenceNr + case other => probe ! other } } @@ -88,7 +88,7 @@ class SnapshotSerializationSpec extends PersistenceSpec(PersistenceSpec.config(" expectMsg(0) val lPersistentActor = system.actorOf(Props(classOf[TestPersistentActor], name, testActor)) expectMsgPF() { - case (SnapshotMetadata(`persistenceId`, 0, timestamp), state) ⇒ + case (SnapshotMetadata(`persistenceId`, 0, timestamp), state) => state should ===(new MySnapshot("blahonga")) timestamp should be > (0L) } diff --git a/akka-persistence/src/test/scala/akka/persistence/SnapshotSpec.scala b/akka-persistence/src/test/scala/akka/persistence/SnapshotSpec.scala index 7f16fa1836..027dd9b1db 100644 --- a/akka-persistence/src/test/scala/akka/persistence/SnapshotSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/SnapshotSpec.scala @@ -14,18 +14,18 @@ object SnapshotSpec { var state = List.empty[String] override def receiveRecover: Receive = { - case payload: String ⇒ state = s"${payload}-${lastSequenceNr}" :: state - case SnapshotOffer(_, snapshot: List[_]) ⇒ state = snapshot.asInstanceOf[List[String]] + case payload: String => state = s"${payload}-${lastSequenceNr}" :: state + case SnapshotOffer(_, snapshot: List[_]) => state = snapshot.asInstanceOf[List[String]] } override def receiveCommand = { - case payload: String ⇒ - persist(payload) { _ ⇒ + case payload: String => + persist(payload) { _ => state = s"${payload}-${lastSequenceNr}" :: state } - case TakeSnapshot ⇒ saveSnapshot(state) - case SaveSnapshotSuccess(md) ⇒ probe ! md.sequenceNr - case GetState ⇒ probe ! state.reverse + case TakeSnapshot => saveSnapshot(state) + case SaveSnapshotSuccess(md) => probe ! md.sequenceNr + case GetState => probe ! state.reverse } } @@ -33,19 +33,19 @@ object SnapshotSpec { override def recovery: Recovery = _recovery override def receiveRecover: Receive = { - case payload: String ⇒ probe ! s"${payload}-${lastSequenceNr}" - case offer @ SnapshotOffer(md, s) ⇒ probe ! offer - case other ⇒ probe ! other + case payload: String => probe ! s"${payload}-${lastSequenceNr}" + case offer @ SnapshotOffer(md, s) => probe ! offer + case other => probe ! other } override def receiveCommand = { - case "done" ⇒ probe ! "done" - case payload: String ⇒ - persist(payload) { _ ⇒ + case "done" => probe ! "done" + case payload: String => + persist(payload) { _ => probe ! s"${payload}-${lastSequenceNr}" } - case offer @ SnapshotOffer(md, s) ⇒ probe ! offer - case other ⇒ probe ! other + case offer @ SnapshotOffer(md, s) => probe ! offer + case other => probe ! other } } @@ -53,17 +53,17 @@ object SnapshotSpec { override def recovery: Recovery = _recovery override def receiveRecover: Receive = { - case payload: String ⇒ probe ! s"${payload}-${lastSequenceNr}" - case other if !other.isInstanceOf[SnapshotOffer] ⇒ probe ! other + case payload: String => probe ! s"${payload}-${lastSequenceNr}" + case other if !other.isInstanceOf[SnapshotOffer] => probe ! other } override def receiveCommand = { - case "done" ⇒ probe ! "done" - case payload: String ⇒ - persist(payload) { _ ⇒ + case "done" => probe ! "done" + case payload: String => + persist(payload) { _ => probe ! s"${payload}-${lastSequenceNr}" } - case other ⇒ probe ! other + case other => probe ! other } } @@ -75,8 +75,8 @@ object SnapshotSpec { override def receiveCommand = receiveDelete orElse super.receiveCommand def receiveDelete: Receive = { - case Delete1(metadata) ⇒ deleteSnapshot(metadata.sequenceNr) - case DeleteN(criteria) ⇒ deleteSnapshots(criteria) + case Delete1(metadata) => deleteSnapshot(metadata.sequenceNr) + case DeleteN(criteria) => deleteSnapshots(criteria) } } } @@ -107,7 +107,7 @@ class SnapshotSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", "Sn val persistenceId = name expectMsgPF() { - case SnapshotOffer(SnapshotMetadata(`persistenceId`, 4, timestamp), state) ⇒ + case SnapshotOffer(SnapshotMetadata(`persistenceId`, 4, timestamp), state) => state should ===(List("a-1", "b-2", "c-3", "d-4").reverse) timestamp should be > (0L) } @@ -132,7 +132,7 @@ class SnapshotSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", "Sn val persistenceId = name expectMsgPF() { - case SnapshotOffer(SnapshotMetadata(`persistenceId`, 2, timestamp), state) ⇒ + case SnapshotOffer(SnapshotMetadata(`persistenceId`, 2, timestamp), state) => state should ===(List("a-1", "b-2").reverse) timestamp should be > (0L) } @@ -146,7 +146,7 @@ class SnapshotSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", "Sn persistentActor ! "done" expectMsgPF() { - case SnapshotOffer(SnapshotMetadata(`persistenceId`, 4, timestamp), state) ⇒ + case SnapshotOffer(SnapshotMetadata(`persistenceId`, 4, timestamp), state) => state should ===(List("a-1", "b-2", "c-3", "d-4").reverse) timestamp should be > (0L) } @@ -159,7 +159,7 @@ class SnapshotSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", "Sn val persistenceId = name expectMsgPF() { - case SnapshotOffer(SnapshotMetadata(`persistenceId`, 2, timestamp), state) ⇒ + case SnapshotOffer(SnapshotMetadata(`persistenceId`, 2, timestamp), state) => state should ===(List("a-1", "b-2").reverse) timestamp should be > (0L) } @@ -175,7 +175,7 @@ class SnapshotSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", "Sn val persistenceId = name expectMsgPF() { - case SnapshotOffer(SnapshotMetadata(`persistenceId`, 2, timestamp), state) ⇒ + case SnapshotOffer(SnapshotMetadata(`persistenceId`, 2, timestamp), state) => state should ===(List("a-1", "b-2").reverse) timestamp should be > (0L) } @@ -204,7 +204,7 @@ class SnapshotSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", "Sn persistentActor1 ! "done" val metadata = expectMsgPF() { - case SnapshotOffer(md @ SnapshotMetadata(`persistenceId`, 4, _), state) ⇒ + case SnapshotOffer(md @ SnapshotMetadata(`persistenceId`, 4, _), state) => state should ===(List("a-1", "b-2", "c-3", "d-4").reverse) md } @@ -213,13 +213,13 @@ class SnapshotSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", "Sn persistentActor1 ! Delete1(metadata) deleteProbe.expectMsgType[DeleteSnapshot] - expectMsgPF() { case m @ DeleteSnapshotSuccess(SnapshotMetadata(`persistenceId`, 4, _)) ⇒ } + expectMsgPF() { case m @ DeleteSnapshotSuccess(SnapshotMetadata(`persistenceId`, 4, _)) => } // recover persistentActor from 2nd snapshot (3rd was deleted) plus replayed messages val persistentActor2 = system.actorOf(Props(classOf[DeleteSnapshotTestPersistentActor], name, recovery, testActor)) expectMsgPF(hint = "" + SnapshotOffer(SnapshotMetadata(`persistenceId`, 2, 0), null)) { - case SnapshotOffer(md @ SnapshotMetadata(`persistenceId`, 2, _), state) ⇒ + case SnapshotOffer(md @ SnapshotMetadata(`persistenceId`, 2, _), state) => state should ===(List("a-1", "b-2").reverse) md } @@ -240,12 +240,12 @@ class SnapshotSpec extends PersistenceSpec(PersistenceSpec.config("leveldb", "Sn val criteria = SnapshotSelectionCriteria(maxSequenceNr = 4) persistentActor1 ! DeleteN(criteria) expectMsgPF() { - case SnapshotOffer(md @ SnapshotMetadata(`persistenceId`, 4, _), state) ⇒ + case SnapshotOffer(md @ SnapshotMetadata(`persistenceId`, 4, _), state) => state should ===(List("a-1", "b-2", "c-3", "d-4").reverse) } expectMsg(RecoveryCompleted) deleteProbe.expectMsgType[DeleteSnapshots] - expectMsgPF() { case DeleteSnapshotsSuccess(`criteria`) ⇒ } + expectMsgPF() { case DeleteSnapshotsSuccess(`criteria`) => } // recover persistentActor from replayed messages (all snapshots deleted) val persistentActor2 = system.actorOf(Props(classOf[DeleteSnapshotTestPersistentActor], name, recovery, testActor)) diff --git a/akka-persistence/src/test/scala/akka/persistence/TimerPersistentActorSpec.scala b/akka-persistence/src/test/scala/akka/persistence/TimerPersistentActorSpec.scala index 5df3858854..83d3ac8210 100644 --- a/akka-persistence/src/test/scala/akka/persistence/TimerPersistentActorSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/TimerPersistentActorSpec.scala @@ -28,17 +28,17 @@ object TimerPersistentActorSpec { override def persistenceId = name override def receiveRecover: Receive = { - case _ ⇒ + case _ => } override def receiveCommand: Receive = { - case Scheduled(msg, replyTo) ⇒ + case Scheduled(msg, replyTo) => replyTo ! msg - case AutoReceivedMessageWrapper(msg) ⇒ + case AutoReceivedMessageWrapper(msg) => timers.startSingleTimer("PoisonPill", PoisonPill, Duration.Zero) - case msg ⇒ + case msg => timers.startSingleTimer("key", Scheduled(msg, sender()), Duration.Zero) - persist(msg)(_ ⇒ ()) + persist(msg)(_ => ()) } } @@ -46,10 +46,10 @@ object TimerPersistentActorSpec { class WrongOrder extends PersistentActor with Timers { override def persistenceId = "notused" override def receiveRecover: Receive = { - case _ ⇒ + case _ => } override def receiveCommand: Receive = { - case _ ⇒ () + case _ => () } } @@ -65,10 +65,10 @@ object TimerPersistentActorSpec { override def createReceive(): AbstractActor.Receive = new AbstractActor.Receive({ - case Scheduled(msg, replyTo) ⇒ + case Scheduled(msg, replyTo) => replyTo ! msg BoxedUnit.UNIT - case msg ⇒ + case msg => timers.startSingleTimer("key", Scheduled(msg, sender()), Duration.Zero) persist(msg, new Procedure[Any] { override def apply(evt: Any): Unit = () diff --git a/akka-persistence/src/test/scala/akka/persistence/fsm/PersistentFSMSpec.scala b/akka-persistence/src/test/scala/akka/persistence/fsm/PersistentFSMSpec.scala index c8c7dffd4b..f1324a9341 100644 --- a/akka-persistence/src/test/scala/akka/persistence/fsm/PersistentFSMSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/fsm/PersistentFSMSpec.scala @@ -286,8 +286,8 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config) "can extract state name" in { StateChangeEvent("xxx", None) match { - case StateChangeEvent(name, _) ⇒ name should equal("xxx") - case _ ⇒ fail("unable to extract state name") + case StateChangeEvent(name, _) => name should equal("xxx") + case _ => fail("unable to extract state name") } } @@ -336,7 +336,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config) val persistentEventsStreamer = system.actorOf(PersistentEventsStreamer.props(persistenceId, testActor)) expectMsgPF() { - case SnapshotOffer(SnapshotMetadata(name, _, timestamp), PersistentFSMSnapshot(stateIdentifier, cart, None)) ⇒ + case SnapshotOffer(SnapshotMetadata(name, _, timestamp), PersistentFSMSnapshot(stateIdentifier, cart, None)) => stateIdentifier should ===(Paid.identifier) cart should ===(NonEmptyShoppingCart(List(shirt, shoes, coat))) timestamp should be > 0L @@ -390,7 +390,7 @@ abstract class PersistentFSMSpec(config: Config) extends PersistenceSpec(config) val storageLocations = List( "akka.persistence.journal.leveldb.dir", "akka.persistence.journal.leveldb-shared.store.dir", - "akka.persistence.snapshot-store.local.dir").map(s ⇒ new File(sys2.settings.config.getString(s))) + "akka.persistence.snapshot-store.local.dir").map(s => new File(sys2.settings.config.getString(s))) shutdown(sys2) storageLocations.foreach(FileUtils.deleteDirectory) } @@ -458,12 +458,12 @@ object PersistentFSMSpec { startWith(LookingAround, EmptyShoppingCart) when(LookingAround) { - case Event("stay", _) ⇒ stay - case Event(e, _) ⇒ goto(LookingAround) + case Event("stay", _) => stay + case Event(e, _) => goto(LookingAround) } onTransition { - case (from, to) ⇒ reportActor ! s"$from -> $to" + case (from, to) => reportActor ! s"$from -> $to" } override def applyEvent(domainEvent: DomainEvent, currentData: ShoppingCart): ShoppingCart = @@ -483,52 +483,52 @@ object PersistentFSMSpec { startWith(LookingAround, EmptyShoppingCart) when(LookingAround) { - case Event(AddItem(item), _) ⇒ + case Event(AddItem(item), _) => goto(Shopping) applying ItemAdded(item) forMax (1 seconds) - case Event(GetCurrentCart, data) ⇒ + case Event(GetCurrentCart, data) => stay replying data } when(Shopping) { - case Event(AddItem(item), _) ⇒ + case Event(AddItem(item), _) => stay applying ItemAdded(item) forMax (1 seconds) - case Event(Buy, _) ⇒ + case Event(Buy, _) => //#customer-andthen-example goto(Paid) applying OrderExecuted andThen { - case NonEmptyShoppingCart(items) ⇒ + case NonEmptyShoppingCart(items) => reportActor ! PurchaseWasMade(items) //#customer-andthen-example saveStateSnapshot() - case EmptyShoppingCart ⇒ saveStateSnapshot() + case EmptyShoppingCart => saveStateSnapshot() //#customer-andthen-example } //#customer-andthen-example - case Event(Leave, _) ⇒ + case Event(Leave, _) => //#customer-snapshot-example stop applying OrderDiscarded andThen { - case _ ⇒ + case _ => reportActor ! ShoppingCardDiscarded saveStateSnapshot() } //#customer-snapshot-example - case Event(GetCurrentCart, data) ⇒ + case Event(GetCurrentCart, data) => stay replying data - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => goto(Inactive) forMax (2 seconds) } when(Inactive) { - case Event(AddItem(item), _) ⇒ + case Event(AddItem(item), _) => goto(Shopping) applying ItemAdded(item) forMax (1 seconds) - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => stop applying OrderDiscarded andThen { - case _ ⇒ reportActor ! ShoppingCardDiscarded + case _ => reportActor ! ShoppingCardDiscarded } } when(Paid) { - case Event(Leave, _) ⇒ stop() - case Event(GetCurrentCart, data) ⇒ + case Event(Leave, _) => stop() + case Event(GetCurrentCart, data) => stay replying data } //#customer-fsm-body @@ -542,9 +542,9 @@ object PersistentFSMSpec { //#customer-apply-event override def applyEvent(event: DomainEvent, cartBeforeEvent: ShoppingCart): ShoppingCart = { event match { - case ItemAdded(item) ⇒ cartBeforeEvent.addItem(item) - case OrderExecuted ⇒ cartBeforeEvent - case OrderDiscarded ⇒ cartBeforeEvent.empty() + case ItemAdded(item) => cartBeforeEvent.addItem(item) + case OrderExecuted => cartBeforeEvent + case OrderDiscarded => cartBeforeEvent.empty() } } //#customer-apply-event @@ -559,12 +559,12 @@ object PersistentFSMSpec { override val persistenceId: String = id def receiveRecover = { - case RecoveryCompleted ⇒ // do nothing - case persistentEvent ⇒ client ! persistentEvent + case RecoveryCompleted => // do nothing + case persistentEvent => client ! persistentEvent } def receiveCommand = { - case _ ⇒ // do nothing + case _ => // do nothing } } @@ -589,11 +589,11 @@ object PersistentFSMSpec { startWith(State("init"), "") when(State("init"), stateTimeout = 300.millis) { - case Event(StateTimeout, _) ⇒ + case Event(StateTimeout, _) => probe ! StateTimeout stay() - case Event(OverrideTimeoutToInf, _) ⇒ + case Event(OverrideTimeoutToInf, _) => probe ! OverrideTimeoutToInf stay() forMax Duration.Inf } @@ -616,25 +616,25 @@ object PersistentFSMSpec { override def persistenceId: String = "snapshot-fsm-test" override def applyEvent(event: SnapshotFSMEvent, currentData: List[Int]): List[Int] = event match { - case IntAdded(i) ⇒ i :: currentData + case IntAdded(i) => i :: currentData } startWith(PersistSingleAtOnce, Nil) when(PersistSingleAtOnce) { - case Event(i: Int, _) ⇒ + case Event(i: Int, _) => stay applying IntAdded(i) - case Event("4x", _) ⇒ + case Event("4x", _) => goto(Persist4xAtOnce) - case Event(SaveSnapshotSuccess(metadata), _) ⇒ + case Event(SaveSnapshotSuccess(metadata), _) => probe ! s"SeqNo=${metadata.sequenceNr}, StateData=${stateData}" stay() } when(Persist4xAtOnce) { - case Event(i: Int, _) ⇒ + case Event(i: Int, _) => stay applying (IntAdded(i), IntAdded(i), IntAdded(i), IntAdded(i)) - case Event(SaveSnapshotSuccess(metadata), _) ⇒ + case Event(SaveSnapshotSuccess(metadata), _) => probe ! s"SeqNo=${metadata.sequenceNr}, StateData=${stateData}" stay() } diff --git a/akka-persistence/src/test/scala/akka/persistence/journal/SteppingInmemJournal.scala b/akka-persistence/src/test/scala/akka/persistence/journal/SteppingInmemJournal.scala index cd1827e88e..468ff79e7e 100644 --- a/akka-persistence/src/test/scala/akka/persistence/journal/SteppingInmemJournal.scala +++ b/akka-persistence/src/test/scala/akka/persistence/journal/SteppingInmemJournal.scala @@ -47,7 +47,7 @@ object SteppingInmemJournal { def getRef(instanceId: String): ActorRef = synchronized(_current(instanceId)) private def putRef(instanceId: String, instance: ActorRef): Unit = synchronized { - _current = _current + (instanceId → instance) + _current = _current + (instanceId -> instance) } private def remove(instanceId: String): Unit = synchronized( _current -= instanceId) @@ -69,16 +69,16 @@ final class SteppingInmemJournal extends InmemJournal { val instanceId = context.system.settings.config.getString("akka.persistence.journal.stepping-inmem.instance-id") - var queuedOps: Seq[() ⇒ Future[Unit]] = Seq.empty + var queuedOps: Seq[() => Future[Unit]] = Seq.empty var queuedTokenRecipients = List.empty[ActorRef] override def receivePluginInternal = super.receivePluginInternal orElse { - case Token if queuedOps.isEmpty ⇒ queuedTokenRecipients = queuedTokenRecipients :+ sender() - case Token ⇒ + case Token if queuedOps.isEmpty => queuedTokenRecipients = queuedTokenRecipients :+ sender() + case Token => val op +: rest = queuedOps queuedOps = rest val tokenConsumer = sender() - op().onComplete(_ ⇒ tokenConsumer ! TokenConsumed) + op().onComplete(_ => tokenConsumer ! TokenConsumed) } override def preStart(): Unit = { @@ -92,15 +92,15 @@ final class SteppingInmemJournal extends InmemJournal { } override def asyncWriteMessages(messages: Seq[AtomicWrite]): Future[Seq[Try[Unit]]] = { - val futures = messages.map { message ⇒ + val futures = messages.map { message => val promise = Promise[Try[Unit]]() val future = promise.future - doOrEnqueue { () ⇒ + doOrEnqueue { () => promise.completeWith(super.asyncWriteMessages(Seq(message)).map { - case Nil ⇒ AsyncWriteJournal.successUnit - case head :: _ ⇒ head + case Nil => AsyncWriteJournal.successUnit + case head :: _ => head }) - future.map(_ ⇒ ()) + future.map(_ => ()) } future } @@ -111,7 +111,7 @@ final class SteppingInmemJournal extends InmemJournal { override def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = { val promise = Promise[Unit]() val future = promise.future - doOrEnqueue { () ⇒ + doOrEnqueue { () => promise.completeWith(super.asyncDeleteMessagesTo(persistenceId, toSequenceNr)) future } @@ -121,17 +121,17 @@ final class SteppingInmemJournal extends InmemJournal { override def asyncReadHighestSequenceNr(persistenceId: String, fromSequenceNr: Long): Future[Long] = { val promise = Promise[Long]() val future = promise.future - doOrEnqueue { () ⇒ + doOrEnqueue { () => promise.completeWith(super.asyncReadHighestSequenceNr(persistenceId, fromSequenceNr)) - future.map(_ ⇒ ()) + future.map(_ => ()) } future } - override def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(recoveryCallback: (PersistentRepr) ⇒ Unit): Future[Unit] = { + override def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(recoveryCallback: (PersistentRepr) => Unit): Future[Unit] = { val promise = Promise[Unit]() val future = promise.future - doOrEnqueue { () ⇒ + doOrEnqueue { () => promise.completeWith(super.asyncReplayMessages(persistenceId, fromSequenceNr, toSequenceNr, max)(recoveryCallback)) future } @@ -139,12 +139,12 @@ final class SteppingInmemJournal extends InmemJournal { future } - private def doOrEnqueue(op: () ⇒ Future[Unit]): Unit = { + private def doOrEnqueue(op: () => Future[Unit]): Unit = { if (queuedTokenRecipients.nonEmpty) { val completed = op() val tokenRecipient +: rest = queuedTokenRecipients queuedTokenRecipients = rest - completed.onComplete(_ ⇒ tokenRecipient ! TokenConsumed) + completed.onComplete(_ => tokenRecipient ! TokenConsumed) } else { queuedOps = queuedOps :+ op } diff --git a/akka-persistence/src/test/scala/akka/persistence/journal/chaos/ChaosJournal.scala b/akka-persistence/src/test/scala/akka/persistence/journal/chaos/ChaosJournal.scala index e27edfe19b..28dabe6436 100644 --- a/akka-persistence/src/test/scala/akka/persistence/journal/chaos/ChaosJournal.scala +++ b/akka-persistence/src/test/scala/akka/persistence/journal/chaos/ChaosJournal.scala @@ -29,7 +29,7 @@ class ReadHighestFailedException private object ChaosJournalMessages extends InmemMessages class ChaosJournal extends AsyncWriteJournal { - import ChaosJournalMessages.{ delete ⇒ del, _ } + import ChaosJournalMessages.{ delete => del, _ } val config = context.system.settings.config.getConfig("akka.persistence.journal.chaos") val writeFailureRate = config.getDouble("write-failure-rate") @@ -43,25 +43,25 @@ class ChaosJournal extends AsyncWriteJournal { try Future.successful { if (shouldFail(writeFailureRate)) throw new WriteFailedException(messages.flatMap(_.payload)) else - for (a ← messages) yield { + for (a <- messages) yield { a.payload.foreach(add) AsyncWriteJournal.successUnit } } catch { - case NonFatal(e) ⇒ Future.failed(e) + case NonFatal(e) => Future.failed(e) } override def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = { try Future.successful { - (1L to toSequenceNr).foreach { snr ⇒ + (1L to toSequenceNr).foreach { snr => del(persistenceId, snr) } } catch { - case NonFatal(e) ⇒ Future.failed(e) + case NonFatal(e) => Future.failed(e) } } - def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: (PersistentRepr) ⇒ Unit): Future[Unit] = + def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)(replayCallback: (PersistentRepr) => Unit): Future[Unit] = if (shouldFail(replayFailureRate)) { val rm = read(persistenceId, fromSequenceNr, toSequenceNr, max) val sm = rm.take(random.nextInt(rm.length + 1)) diff --git a/akka-persistence/src/test/scala/akka/persistence/journal/leveldb/CompactionSegmentManagementSpec.scala b/akka-persistence/src/test/scala/akka/persistence/journal/leveldb/CompactionSegmentManagementSpec.scala index 6c6e78fd19..a905786787 100644 --- a/akka-persistence/src/test/scala/akka/persistence/journal/leveldb/CompactionSegmentManagementSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/journal/leveldb/CompactionSegmentManagementSpec.scala @@ -11,9 +11,9 @@ class CompactionSegmentManagementSpec extends WordSpec { "A CompactionSegmentManagement compatible object" must { "ignore persistence ids without declared compaction intervals" in { val intervals = Map( - "persistence_id-1" → 1L, - "persistence_id-2" → 1L, - "persistence_id-3" → 1L + "persistence_id-1" -> 1L, + "persistence_id-2" -> 1L, + "persistence_id-3" -> 1L ) val compactionStub = new CompactionSegmentManagement { override def compactionIntervals: Map[String, Long] = intervals @@ -26,9 +26,9 @@ class CompactionSegmentManagementSpec extends WordSpec { "ignore persistence ids whose compaction intervals are less or equal to zero" in { val intervals = Map( - "persistence_id-1" → 1L, - "persistence_id-2" → 0L, - "persistence_id-3" → -1L + "persistence_id-1" -> 1L, + "persistence_id-2" -> 0L, + "persistence_id-3" -> -1L ) val compactionStub = new CompactionSegmentManagement { override def compactionIntervals: Map[String, Long] = intervals @@ -40,9 +40,9 @@ class CompactionSegmentManagementSpec extends WordSpec { "allow for wildcard configuration" in { val intervals = Map( - "persistence_id-1" → 1L, - "persistence_id-2" → 1L, - "*" → 1L + "persistence_id-1" -> 1L, + "persistence_id-2" -> 1L, + "*" -> 1L ) val compactionStub = new CompactionSegmentManagement { override def compactionIntervals: Map[String, Long] = intervals @@ -53,17 +53,17 @@ class CompactionSegmentManagementSpec extends WordSpec { } "not permit compaction before thresholds are exceeded" in { - val namedIntervals = Map("persistence_id-1" → 5L, "persistence_id-2" → 4L) - val intervals = namedIntervals + ("*" → 3L) + val namedIntervals = Map("persistence_id-1" -> 5L, "persistence_id-2" -> 4L) + val intervals = namedIntervals + ("*" -> 3L) val compactionStub = new CompactionSegmentManagement { override def compactionIntervals: Map[String, Long] = intervals } - val expectedIntervals = namedIntervals + "persistence_id-3" → 3L + "persistence_id-4" → 3L + val expectedIntervals = namedIntervals + ("persistence_id-3" -> 3L) + ("persistence_id-4" -> 3L) - for ((id, interval) ← expectedIntervals) { + for ((id, interval) <- expectedIntervals) { var segment = 0 - for (i ← 0L.until(4 * interval)) { + for (i <- 0L.until(4 * interval)) { if ((i + 1) % interval == 0) { assert(compactionStub.mustCompact(id, i), s"must compact for [$id] when toSeqNr is [$i]") segment += 1 @@ -81,7 +81,7 @@ class CompactionSegmentManagementSpec extends WordSpec { val id = "persistence_id-1" val interval = 5L val compactionStub = new CompactionSegmentManagement { - override def compactionIntervals: Map[String, Long] = Map(id → interval) + override def compactionIntervals: Map[String, Long] = Map(id -> interval) } val smallJump = interval / 2 val midJump = interval diff --git a/akka-persistence/src/test/scala/akka/persistence/journal/leveldb/JournalCompactionSpec.scala b/akka-persistence/src/test/scala/akka/persistence/journal/leveldb/JournalCompactionSpec.scala index 741d2a0474..3ee60c4bde 100644 --- a/akka-persistence/src/test/scala/akka/persistence/journal/leveldb/JournalCompactionSpec.scala +++ b/akka-persistence/src/test/scala/akka/persistence/journal/leveldb/JournalCompactionSpec.scala @@ -26,7 +26,7 @@ class JournalNoCompactionSpec extends JournalCompactionSpecBase(SpecComponentBui val deletionBatchSize = 500 var oldJournalSize = 0L - for (i ← 0L.until(totalMessages)) { + for (i <- 0L.until(totalMessages)) { logger ! Generate watcher.expectMsg(Generated(i)) } @@ -60,7 +60,7 @@ class JournalCompactionSpec extends JournalCompactionSpecBase(SpecComponentBuild val deletionBatchSize = builder.compactionInterval // 500 var oldJournalSize = 0L - for (i ← 0L.until(totalMessages)) { + for (i <- 0L.until(totalMessages)) { logger ! Generate watcher.expectMsg(Generated(i)) } @@ -94,7 +94,7 @@ class JournalCompactionThresholdSpec extends JournalCompactionSpecBase(SpecCompo val deletionBatchSize = builder.compactionInterval // 500 var oldJournalSize = 0L - for (i ← 0L.until(totalMessages)) { + for (i <- 0L.until(totalMessages)) { logger ! Generate watcher.expectMsg(Generated(i)) } @@ -181,16 +181,16 @@ object JournalCompactionSpec { import EventLogger._ override def receiveRecover: Receive = { - case Event(seqNr, _) ⇒ log.info("Recovered event {}", seqNr) + case Event(seqNr, _) => log.info("Recovered event {}", seqNr) } override def receiveCommand: Receive = { - case Generate ⇒ + case Generate => persist(Event(lastSequenceNr, randomText()))(onEventPersisted) - case Delete(toSeqNr) ⇒ + case Delete(toSeqNr) => log.info("Deleting messages up to {}", toSeqNr) deleteMessages(toSeqNr) - case evt: DeleteMessagesSuccess ⇒ + case evt: DeleteMessagesSuccess => watcher ! evt } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/io/DnsSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/io/DnsSpec.scala index 576dd1fc80..937a0614d0 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/io/DnsSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/io/DnsSpec.scala @@ -22,10 +22,10 @@ class DnsSpec extends RemotingMultiNodeSpec(DnsSpec) { def initialParticipants = roles.size val ip4Address = InetAddress.getByAddress("localhost", Array[Byte](127, 0, 0, 1)) match { - case address: Inet4Address ⇒ address + case address: Inet4Address => address } val ipv6Address = InetAddress.getByAddress("localhost", Array[Byte](0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)) match { - case address: Inet6Address ⇒ address + case address: Inet6Address => address } var temporaryValue: Option[String] = None @@ -36,8 +36,8 @@ class DnsSpec extends RemotingMultiNodeSpec(DnsSpec) { override def afterTermination(): Unit = { temporaryValue match { - case Some(value) ⇒ sys.props.put("java.net.preferIPv6Addresses", value) - case _ ⇒ sys.props.remove("java.net.preferIPv6Addresses") + case Some(value) => sys.props.put("java.net.preferIPv6Addresses", value) + case _ => sys.props.remove("java.net.preferIPv6Addresses") } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/AttemptSysMsgRedeliverySpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/AttemptSysMsgRedeliverySpec.scala index 52ee53e280..ec8953cf7f 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/AttemptSysMsgRedeliverySpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/AttemptSysMsgRedeliverySpec.scala @@ -48,7 +48,7 @@ class ArteryAttemptSysMsgRedeliveryMultiJvmNode3 extends AttemptSysMsgRedelivery object AttemptSysMsgRedeliverySpec { class Echo extends Actor { def receive = { - case m ⇒ sender ! m + case m => sender ! m } } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/LookupRemoteActorSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/LookupRemoteActorSpec.scala index 1777087771..a07ef67445 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/LookupRemoteActorSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/LookupRemoteActorSpec.scala @@ -35,7 +35,7 @@ class ArteryLookupRemoteActorMultiJvmNode2 extends LookupRemoteActorSpec(new Loo object LookupRemoteActorSpec { class SomeActor extends Actor { def receive = { - case "identify" ⇒ sender() ! self + case "identify" => sender() ! self } } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/NewRemoteActorSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/NewRemoteActorSpec.scala index 3a3507c6bf..a5098a6159 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/NewRemoteActorSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/NewRemoteActorSpec.scala @@ -43,13 +43,13 @@ class ArteryNewRemoteActorMultiJvmNode2 extends NewRemoteActorSpec(new NewRemote object NewRemoteActorSpec { class SomeActor extends Actor { def receive = { - case "identify" ⇒ sender() ! self + case "identify" => sender() ! self } } class SomeActorWithParam(ignored: String) extends Actor { def receive = { - case "identify" ⇒ sender() ! self + case "identify" => sender() ! self } } } @@ -126,7 +126,7 @@ abstract class NewRemoteActorSpec(multiNodeConfig: NewRemoteActorMultiJvmSpec) // master system is supposed to be shutdown after slave // this should be triggered by slave system.terminate - expectMsgPF() { case Terminated(`actor`) ⇒ true } + expectMsgPF() { case Terminated(`actor`) => true } } runOn(slave) { diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/PiercingShouldKeepQuarantineSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/PiercingShouldKeepQuarantineSpec.scala index 5a83e3ed32..aa09781bb0 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/PiercingShouldKeepQuarantineSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/PiercingShouldKeepQuarantineSpec.scala @@ -35,7 +35,7 @@ class ArteryPiercingShouldKeepQuarantineSpecMultiJvmNode2 extends PiercingShould object PiercingShouldKeepQuarantineSpec { class Subject extends Actor { def receive = { - case "getuid" ⇒ sender() ! AddressUidExtension(context.system).longAddressUid + case "getuid" => sender() ! AddressUidExtension(context.system).longAddressUid } } } @@ -65,7 +65,7 @@ abstract class PiercingShouldKeepQuarantineSpec(multiNodeConfig: PiercingShouldK Thread.sleep(1000) // Quarantine is up -- Should not be able to communicate with remote system any more - for (_ ← 1 to 4) { + for (_ <- 1 to 4) { system.actorSelection(node(second) / "user" / "subject") ! "getuid" expectNoMsg(2.seconds) } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteDeliverySpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteDeliverySpec.scala index 13c18e6405..518adbf8e1 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteDeliverySpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteDeliverySpec.scala @@ -40,7 +40,7 @@ object RemoteDeliverySpec { class Postman extends Actor { def receive = { - case Letter(n, route) ⇒ route.head ! Letter(n, route.tail) + case Letter(n, route) => route.head ! Letter(n, route.tail) } } } @@ -69,7 +69,7 @@ abstract class RemoteDeliverySpec(multiNodeConfig: RemoteDeliveryConfig) val p3 = identify(third, "postman-third") val route = p2 :: p3 :: p2 :: p3 :: testActor :: Nil - for (n ← 1 to 500) { + for (n <- 1 to 500) { p1 ! Letter(n, route) expectMsg(5.seconds, Letter(n, Nil)) // in case the loop count is increased it is good with some progress feedback diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteDeploymentDeathWatchSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteDeploymentDeathWatchSpec.scala index e976907da5..70010bba43 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteDeploymentDeathWatchSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteDeploymentDeathWatchSpec.scala @@ -93,7 +93,7 @@ abstract class RemoteDeploymentDeathWatchSpec(multiNodeConfig: RemoteDeploymentD val timeout = remainingOrDefault try Await.ready(system.whenTerminated, timeout) catch { - case _: TimeoutException ⇒ + case _: TimeoutException => fail("Failed to stop [%s] within [%s] \n%s".format(system.name, timeout, system.asInstanceOf[ActorSystemImpl].printTree)) } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteGatePiercingSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteGatePiercingSpec.scala index ec16313467..6dce6d8956 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteGatePiercingSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteGatePiercingSpec.scala @@ -39,7 +39,7 @@ object RemoteGatePiercingSpec extends MultiNodeConfig { class Subject extends Actor { def receive = { - case "shutdown" ⇒ context.system.terminate() + case "shutdown" => context.system.terminate() } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeDeathWatchSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeDeathWatchSpec.scala index 9a2c6653e2..ad82dc0f99 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeDeathWatchSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeDeathWatchSpec.scala @@ -76,15 +76,15 @@ object RemoteNodeDeathWatchSpec { class ProbeActor(testActor: ActorRef) extends Actor { def receive = { - case WatchIt(watchee) ⇒ + case WatchIt(watchee) => context watch watchee sender() ! Ack - case UnwatchIt(watchee) ⇒ + case UnwatchIt(watchee) => context unwatch watchee sender() ! Ack - case t: Terminated ⇒ + case t: Terminated => testActor forward WrappedTerminated(t) - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } } @@ -350,7 +350,7 @@ abstract class RemoteNodeDeathWatchSpec(multiNodeConfig: RemoteNodeDeathWatchCon enterBarrier("watch-established-5") enterBarrier("stopped-5") - p1.receiveN(2, 5 seconds).collect { case WrappedTerminated(t) ⇒ t.actor }.toSet should ===(Set(a1, a2)) + p1.receiveN(2, 5 seconds).collect { case WrappedTerminated(t) => t.actor }.toSet should ===(Set(a1, a2)) p3.expectMsgType[WrappedTerminated](5 seconds).t.actor should ===(a3) p2.expectNoMessage(2 seconds) enterBarrier("terminated-verified-5") diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeRestartDeathWatchSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeRestartDeathWatchSpec.scala index 257b4b76a0..12e41e03b6 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeRestartDeathWatchSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeRestartDeathWatchSpec.scala @@ -51,10 +51,10 @@ class RemoteNodeRestartDeathWatchMultiJvmNode2 extends RemoteNodeRestartDeathWat object RemoteNodeRestartDeathWatchSpec { class Subject extends Actor { def receive = { - case "shutdown" ⇒ + case "shutdown" => sender() ! "shutdown-ack" context.system.terminate() - case msg ⇒ sender() ! msg + case msg => sender() ! msg } } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeRestartGateSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeRestartGateSpec.scala index 3589627a21..d16363313f 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeRestartGateSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeRestartGateSpec.scala @@ -33,8 +33,8 @@ object RemoteNodeRestartGateSpec extends MultiNodeConfig { class Subject extends Actor { def receive = { - case "shutdown" ⇒ context.system.terminate() - case msg ⇒ sender() ! msg + case "shutdown" => context.system.terminate() + case msg => sender() ! msg } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeShutdownAndComesBackSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeShutdownAndComesBackSpec.scala index 619ca0aa64..70bc19a897 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeShutdownAndComesBackSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteNodeShutdownAndComesBackSpec.scala @@ -35,8 +35,8 @@ object RemoteNodeShutdownAndComesBackSpec extends MultiNodeConfig { class Subject extends Actor { def receive = { - case "shutdown" ⇒ context.system.terminate() - case msg ⇒ sender() ! msg + case "shutdown" => context.system.terminate() + case msg => sender() ! msg } } @@ -100,7 +100,7 @@ abstract class RemoteNodeShutdownAndComesBackSpec val p = TestProbe() system.actorSelection(RootActorPath(secondAddress) / "user" / "subject").tell(Identify("subject"), p.ref) p.expectMsgPF(1 second) { - case ActorIdentity("subject", Some(ref)) ⇒ true + case ActorIdentity("subject", Some(ref)) => true } } } @@ -117,7 +117,7 @@ abstract class RemoteNodeShutdownAndComesBackSpec subjectNew ! "shutdown" // we are waiting for a Terminated here, but it is ok if it does not arrive receiveWhile(5.seconds) { - case _: ActorIdentity ⇒ true + case _: ActorIdentity => true } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteQuarantinePiercingSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteQuarantinePiercingSpec.scala index 0735b5db90..0218d40ac9 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteQuarantinePiercingSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteQuarantinePiercingSpec.scala @@ -39,8 +39,8 @@ class ArteryRemoteQuarantinePiercingMultiJvmNode2 extends RemoteQuarantinePierci object RemoteQuarantinePiercingSpec { class Subject extends Actor { def receive = { - case "shutdown" ⇒ context.system.terminate() - case "identify" ⇒ sender() ! (AddressUidExtension(context.system).longAddressUid → self) + case "shutdown" => context.system.terminate() + case "identify" => sender() ! (AddressUidExtension(context.system).longAddressUid -> self) } } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteReDeploymentSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteReDeploymentSpec.scala index 4cc6215722..43bc8d3ff3 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteReDeploymentSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteReDeploymentSpec.scala @@ -84,8 +84,8 @@ object RemoteReDeploymentMultiJvmSpec { val monitor = context.actorSelection("/user/echo") log.info(s"Started Parent on path ${self.path}") def receive = { - case (p: Props, n: String) ⇒ context.actorOf(p, n) - case msg ⇒ monitor ! msg + case (p: Props, n: String) => context.actorOf(p, n) + case msg => monitor ! msg } } @@ -100,7 +100,7 @@ object RemoteReDeploymentMultiJvmSpec { class Echo(target: ActorRef) extends Actor with ActorLogging { def receive = { - case msg ⇒ + case msg => log.info(s"received $msg from ${sender()}") target ! msg } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteRestartedQuarantinedSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteRestartedQuarantinedSpec.scala index dd5023949d..16a3af905b 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteRestartedQuarantinedSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemoteRestartedQuarantinedSpec.scala @@ -38,8 +38,8 @@ object RemoteRestartedQuarantinedSpec extends MultiNodeConfig { class Subject extends Actor { def receive = { - case "shutdown" ⇒ context.system.terminate() - case "identify" ⇒ sender() ! (AddressUidExtension(context.system).addressUid → self) + case "shutdown" => context.system.terminate() + case "identify" => sender() ! (AddressUidExtension(context.system).addressUid -> self) } } @@ -108,7 +108,7 @@ abstract class RemoteRestartedQuarantinedSpec } expectMsgPF(10 seconds) { - case ThisActorSystemQuarantinedEvent(local, remote) ⇒ + case ThisActorSystemQuarantinedEvent(local, remote) => } enterBarrier("still-quarantined") diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemotingMultiNodeSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemotingMultiNodeSpec.scala index 2b58f4cb07..909d8274de 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemotingMultiNodeSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/RemotingMultiNodeSpec.scala @@ -32,7 +32,7 @@ abstract class RemotingMultiNodeSpec(config: MultiNodeConfig) extends MultiNodeS with STMultiNodeSpec with FlightRecordingSupport with ImplicitSender - with DefaultTimeout { self: MultiNodeSpec ⇒ + with DefaultTimeout { self: MultiNodeSpec => // Keep track of failure so we can print artery flight recording on failure private var failed = false diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/Ticket15109Spec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/Ticket15109Spec.scala index ec5a13657b..2e3dfa29bb 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/Ticket15109Spec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/Ticket15109Spec.scala @@ -35,7 +35,7 @@ object Ticket15109Spec extends MultiNodeConfig { class Subject extends Actor { def receive = { - case "ping" ⇒ sender() ! "pong" + case "ping" => sender() ! "pong" } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/TransportFailSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/TransportFailSpec.scala index bc404420f2..cc9a7d5f37 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/TransportFailSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/TransportFailSpec.scala @@ -51,7 +51,7 @@ class TransportFailMultiJvmNode2 extends TransportFailSpec object TransportFailSpec { class Subject extends Actor { def receive = { - case msg ⇒ sender() ! msg + case msg => sender() ! msg } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/DirectMemorySpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/DirectMemorySpec.scala index 389725d748..7c5926f78f 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/DirectMemorySpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/DirectMemorySpec.scala @@ -34,13 +34,13 @@ object DirectMemorySpec extends MultiNodeConfig { case class Done(actor: ActorRef) class CountingEcho(reportTo: ActorRef, private var count: Int) extends Actor { override def receive: Receive = { - case Start(rootPath) ⇒ + case Start(rootPath) => count -= 1 context.system.actorSelection(rootPath / "user" / self.path.name) ! Message - case Message if count > 0 ⇒ + case Message if count > 0 => count -= 1 sender() ! Message - case Message ⇒ + case Message => reportTo ! Done(self) } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/FanInThrougputSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/FanInThrougputSpec.scala index 699e4b234f..92b172c5c7 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/FanInThrougputSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/FanInThrougputSpec.scala @@ -19,12 +19,12 @@ import akka.remote.artery.MaxThroughputSpec._ object FanInThroughputSpec extends MultiNodeConfig { val totalNumberOfNodes = System.getProperty("akka.test.FanInThroughputSpec.nrOfNodes") match { - case null ⇒ 4 - case value ⇒ value.toInt + case null => 4 + case value => value.toInt } val senderReceiverPairs = totalNumberOfNodes - 1 - for (n ← 1 to totalNumberOfNodes) role("node-" + n) + for (n <- 1 to totalNumberOfNodes) role("node-" + n) val barrierTimeout = 5.minutes @@ -130,7 +130,7 @@ abstract class FanInThroughputSpec extends RemotingMultiNodeSpec(FanInThroughput runOn(roles.head) { val rep = reporter(testName) - val receivers = (1 to sendingNodes.size).map { n ⇒ + val receivers = (1 to sendingNodes.size).map { n => system.actorOf( receiverProps(rep, payloadSize, printTaskRunnerMetrics = n == 1, senderReceiverPairs), receiverName + "-" + n) @@ -144,7 +144,7 @@ abstract class FanInThroughputSpec extends RemotingMultiNodeSpec(FanInThroughput runOn(sendingNodes: _*) { enterBarrier(receiverName + "-started") val ignore = TestProbe() - val receivers = (1 to sendingNodes.size).map { n ⇒ + val receivers = (1 to sendingNodes.size).map { n => identifyReceiver(receiverName + "-" + n, roles.head) }.toArray[Target] @@ -172,7 +172,7 @@ abstract class FanInThroughputSpec extends RemotingMultiNodeSpec(FanInThroughput "Max throughput of fan-in" must { val reporter = BenchmarkFileReporter("FanInThroughputSpec", system) - for (s ← scenarios) { + for (s <- scenarios) { s"be great for ${s.testName}, burstSize = ${s.burstSize}, payloadSize = ${s.payloadSize}" in test(s, reporter) } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/FanOutThrougputSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/FanOutThrougputSpec.scala index 6e4a08ce6c..3ac7ee395c 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/FanOutThrougputSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/FanOutThrougputSpec.scala @@ -19,12 +19,12 @@ import akka.remote.artery.MaxThroughputSpec._ object FanOutThroughputSpec extends MultiNodeConfig { val totalNumberOfNodes = System.getProperty("akka.test.FanOutThroughputSpec.nrOfNodes") match { - case null ⇒ 4 - case value ⇒ value.toInt + case null => 4 + case value => value.toInt } val senderReceiverPairs = totalNumberOfNodes - 1 - for (n ← 1 to totalNumberOfNodes) role("node-" + n) + for (n <- 1 to totalNumberOfNodes) role("node-" + n) val barrierTimeout = 5.minutes @@ -141,8 +141,8 @@ abstract class FanOutThroughputSpec extends RemotingMultiNodeSpec(FanOutThroughp runOn(roles.head) { enterBarrier(receiverName + "-started") val ignore = TestProbe() - val receivers = targetNodes.map(target ⇒ identifyReceiver(receiverName, target)).toArray[Target] - val senders = for ((target, i) ← targetNodes.zipWithIndex) yield { + val receivers = targetNodes.map(target => identifyReceiver(receiverName, target)).toArray[Target] + val senders = for ((target, i) <- targetNodes.zipWithIndex) yield { val receiver = receivers(i) val plotProbe = TestProbe() val snd = system.actorOf( @@ -154,7 +154,7 @@ abstract class FanOutThroughputSpec extends RemotingMultiNodeSpec(FanOutThroughp (snd, terminationProbe, plotProbe) } senders.foreach { - case (snd, terminationProbe, plotProbe) ⇒ + case (snd, terminationProbe, plotProbe) => terminationProbe.expectTerminated(snd, barrierTimeout) if (snd == senders.head._1) { val plotResult = plotProbe.expectMsgType[PlotResult] @@ -169,7 +169,7 @@ abstract class FanOutThroughputSpec extends RemotingMultiNodeSpec(FanOutThroughp "Max throughput of fan-out" must { val reporter = BenchmarkFileReporter("FanOutThroughputSpec", system) - for (s ← scenarios) { + for (s <- scenarios) { s"be great for ${s.testName}, burstSize = ${s.burstSize}, payloadSize = ${s.payloadSize}" in test(s, reporter) } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/HandshakeRestartReceiverSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/HandshakeRestartReceiverSpec.scala index 1fbe363d54..7a2a523f94 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/HandshakeRestartReceiverSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/HandshakeRestartReceiverSpec.scala @@ -33,8 +33,8 @@ object HandshakeRestartReceiverSpec extends MultiNodeConfig { class Subject extends Actor { def receive = { - case "shutdown" ⇒ context.system.terminate() - case "identify" ⇒ sender() ! (AddressUidExtension(context.system).longAddressUid → self) + case "shutdown" => context.system.terminate() + case "identify" => sender() ! (AddressUidExtension(context.system).longAddressUid -> self) } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/LatencySpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/LatencySpec.scala index 739e873f06..fc9b541f73 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/LatencySpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/LatencySpec.scala @@ -74,10 +74,10 @@ object LatencySpec extends MultiNodeConfig { var cachedSender: ActorRef = null def receive = { - case Reset ⇒ + case Reset => cachedSender = null sender() ! Reset - case msg ⇒ + case msg => if (cachedSender == null) cachedSender = sender() cachedSender ! msg } @@ -97,12 +97,12 @@ object LatencySpec extends MultiNodeConfig { var reportedArrayOOB = false def receive = { - case bytes: Array[Byte] ⇒ + case bytes: Array[Byte] => if (bytes.length != 0) { if (bytes.length != payloadSize) throw new IllegalArgumentException("Invalid message") receiveMessage(bytes.length) } - case _: TestMessage ⇒ + case _: TestMessage => receiveMessage(payloadSize) } @@ -115,7 +115,7 @@ object LatencySpec extends MultiNodeConfig { try { histogram.recordValue(d) } catch { - case e: ArrayIndexOutOfBoundsException ⇒ + case e: ArrayIndexOutOfBoundsException => // Report it only once instead of flooding the console if (!reportedArrayOOB) { e.printStackTrace() @@ -261,7 +261,7 @@ abstract class LatencySpec else if (messageRate <= 20000) 1.3 else 1.4 - for (n ← 1 to repeat) { + for (n <- 1 to repeat) { echo ! Reset expectMsg(Reset) histogram.reset() @@ -270,11 +270,11 @@ abstract class LatencySpec // warmup for 3 seconds to init compression val warmup = Source(1 to 30) .throttle(10, 1.second, 10, ThrottleMode.Shaping) - .runForeach { n ⇒ + .runForeach { n => echo.tell(Array.emptyByteArray, receiver) } - warmup.foreach { _ ⇒ + warmup.foreach { _ => var i = 0 var adjust = 0L val targetDelay = (SECONDS.toNanos(1) / (messageRate * adjustRateFactor)).toLong @@ -339,7 +339,7 @@ abstract class LatencySpec enterBarrier("echo-started") } - for (s ← scenarios) { + for (s <- scenarios) { s"be low for ${s.testName}, at ${s.messageRate} msg/s, payloadSize = ${s.payloadSize}" in test(s, reporter) } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/MaxThroughputSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/MaxThroughputSpec.scala index f5f81b138f..572f1757c8 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/MaxThroughputSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/MaxThroughputSpec.scala @@ -118,27 +118,27 @@ object MaxThroughputSpec extends MultiNodeConfig { private var correspondingSender: ActorRef = null // the Actor which send the Start message will also receive the report def receive = { - case msg: Array[Byte] ⇒ + case msg: Array[Byte] => if (msg.length != payloadSize) throw new IllegalArgumentException("Invalid message") report() - case msg: TestMessage ⇒ + case msg: TestMessage => report() - case Start(corresponding) ⇒ + case Start(corresponding) => if (corresponding == self) correspondingSender = sender() sender() ! Start - case End if endMessagesMissing > 1 ⇒ + case End if endMessagesMissing > 1 => endMessagesMissing -= 1 // wait for End message from all senders - case End ⇒ + case End => if (printTaskRunnerMetrics) taskRunnerMetrics.printHistograms() correspondingSender ! EndResult(c) context.stop(self) - case m: Echo ⇒ + case m: Echo => sender() ! m } @@ -173,7 +173,7 @@ object MaxThroughputSpec extends MultiNodeConfig { RARP(context.system).provider.remoteSettings.Artery.Enabled def receive = { - case Run ⇒ + case Run => if (compressionEnabled) { target.tell(Warmup(payload), self) context.setReceiveTimeout(1.second) @@ -182,17 +182,17 @@ object MaxThroughputSpec extends MultiNodeConfig { } def waitingForCompression: Receive = { - case ReceivedActorRefCompressionTable(_, table) ⇒ + case ReceivedActorRefCompressionTable(_, table) => val ref = target match { - case ActorRefTarget(ref) ⇒ ref - case ActorSelectionTarget(sel, _) ⇒ sel.anchor + case ActorRefTarget(ref) => ref + case ActorSelectionTarget(sel, _) => sel.anchor } if (table.dictionary.contains(ref)) { context.setReceiveTimeout(Duration.Undefined) runWarmup() } else target.tell(Warmup(payload), self) - case ReceiveTimeout ⇒ + case ReceiveTimeout => target.tell(Warmup(payload), self) } @@ -203,14 +203,14 @@ object MaxThroughputSpec extends MultiNodeConfig { } def warmup: Receive = { - case Start ⇒ + case Start => println(s"${self.path.name}: Starting benchmark of $totalMessages messages with burst size " + s"$burstSize and payload size $payloadSize") startTime = System.nanoTime remaining = totalMessages - (0 until sent.size).foreach(i ⇒ sent(i) = 0) + (0 until sent.size).foreach(i => sent(i) = 0) // have a few batches in flight to make sure there are always messages to send - (1 to 3).foreach { _ ⇒ + (1 to 3).foreach { _ => val t0 = System.nanoTime() sendBatch(warmup = false) sendFlowControl(t0) @@ -218,11 +218,11 @@ object MaxThroughputSpec extends MultiNodeConfig { context.become(active) - case _: Warmup ⇒ + case _: Warmup => } def active: Receive = { - case c @ FlowControl(id, t0) ⇒ + case c @ FlowControl(id, t0) => val targetCount = pendingFlowControl(id) if (targetCount - 1 == 0) { pendingFlowControl -= id @@ -239,7 +239,7 @@ object MaxThroughputSpec extends MultiNodeConfig { } val waitingForEndResult: Receive = { - case EndResult(totalReceived) ⇒ + case EndResult(totalReceived) => val took = NANOSECONDS.toMillis(System.nanoTime - startTime) val throughput = (totalReceived * 1000.0 / took) @@ -262,7 +262,7 @@ object MaxThroughputSpec extends MultiNodeConfig { plotRef ! PlotResult().add(testName, throughput * payloadSize * testSettings.senderReceiverPairs / 1024 / 1024) context.stop(self) - case c: ReceivedActorRefCompressionTable ⇒ + case c: ReceivedActorRefCompressionTable => } val sent = new Array[Long](targets.size) @@ -322,23 +322,23 @@ object MaxThroughputSpec extends MultiNodeConfig { override def manifest(o: AnyRef): String = o match { - case _: FlowControl ⇒ FlowControlManifest + case _: FlowControl => FlowControlManifest } override def toBinary(o: AnyRef, buf: ByteBuffer): Unit = o match { - case FlowControl(id, burstStartTime) ⇒ + case FlowControl(id, burstStartTime) => buf.putInt(id) buf.putLong(burstStartTime) } override def fromBinary(buf: ByteBuffer, manifest: String): AnyRef = manifest match { - case FlowControlManifest ⇒ FlowControl(buf.getInt, buf.getLong) + case FlowControlManifest => FlowControl(buf.getInt, buf.getLong) } override def toBinary(o: AnyRef): Array[Byte] = o match { - case FlowControl(id, burstStartTime) ⇒ + case FlowControl(id, burstStartTime) => val buf = ByteBuffer.allocate(12) toBinary(o, buf) buf.flip() @@ -440,7 +440,7 @@ abstract class MaxThroughputSpec extends RemotingMultiNodeSpec(MaxThroughputSpec runOn(second) { val rep = reporter(testName) - val receivers = (1 to senderReceiverPairs).map { n ⇒ + val receivers = (1 to senderReceiverPairs).map { n => system.actorOf( receiverProps(rep, payloadSize, printTaskRunnerMetrics = n == 1, senderReceiverPairs), receiverName + n) @@ -454,8 +454,8 @@ abstract class MaxThroughputSpec extends RemotingMultiNodeSpec(MaxThroughputSpec runOn(first) { enterBarrier(receiverName + "-started") val ignore = TestProbe() - val receivers = (for (n ← 1 to senderReceiverPairs) yield identifyReceiver(receiverName + n)).toArray - val senders = for (n ← 1 to senderReceiverPairs) yield { + val receivers = (for (n <- 1 to senderReceiverPairs) yield identifyReceiver(receiverName + n)).toArray + val senders = for (n <- 1 to senderReceiverPairs) yield { val receiver = receivers(n - 1) val plotProbe = TestProbe() val snd = system.actorOf( @@ -467,7 +467,7 @@ abstract class MaxThroughputSpec extends RemotingMultiNodeSpec(MaxThroughputSpec (snd, terminationProbe, plotProbe) } senders.foreach { - case (snd, terminationProbe, plotProbe) ⇒ + case (snd, terminationProbe, plotProbe) => terminationProbe.expectTerminated(snd, barrierTimeout) if (snd == senders.head._1) { val plotResult = plotProbe.expectMsgType[PlotResult] @@ -482,7 +482,7 @@ abstract class MaxThroughputSpec extends RemotingMultiNodeSpec(MaxThroughputSpec "Max throughput of Artery" must { val reporter = BenchmarkFileReporter("MaxThroughputSpec", system) - for (s ← scenarios) { + for (s <- scenarios) { s"be great for ${s.testName}, burstSize = ${s.burstSize}, payloadSize = ${s.payloadSize}" in test(s, reporter) } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/PlotResult.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/PlotResult.scala index ea258eed1f..ef6f27dbe7 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/PlotResult.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/PlotResult.scala @@ -7,7 +7,7 @@ package akka.remote.artery final case class PlotResult(values: Vector[(String, Number)] = Vector.empty) { def add(key: String, value: Number): PlotResult = - copy(values = values :+ (key → value)) + copy(values = values :+ (key -> value)) def addAll(p: PlotResult): PlotResult = copy(values ++ p.values) diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/RemoteRestartedQuarantinedSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/RemoteRestartedQuarantinedSpec.scala index c4c263ec36..a3866b53a9 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/RemoteRestartedQuarantinedSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/RemoteRestartedQuarantinedSpec.scala @@ -28,8 +28,8 @@ object RemoteRestartedQuarantinedSpec extends MultiNodeConfig { class Subject extends Actor { def receive = { - case "shutdown" ⇒ context.system.terminate() - case "identify" ⇒ sender() ! (AddressUidExtension(context.system).longAddressUid → self) + case "shutdown" => context.system.terminate() + case "identify" => sender() ! (AddressUidExtension(context.system).longAddressUid -> self) } } @@ -92,7 +92,7 @@ abstract class RemoteRestartedQuarantinedSpec extends RemotingMultiNodeSpec(Remo enterBarrier("quarantined") expectMsgPF(10 seconds) { - case ThisActorSystemQuarantinedEvent(local, remote) ⇒ + case ThisActorSystemQuarantinedEvent(local, remote) => } // check that we quarantine back diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/SurviveInboundStreamRestartWithCompressionInFlightSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/SurviveInboundStreamRestartWithCompressionInFlightSpec.scala index fc7f3e8c56..437640d886 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/SurviveInboundStreamRestartWithCompressionInFlightSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/SurviveInboundStreamRestartWithCompressionInFlightSpec.scala @@ -44,7 +44,7 @@ object SurviveInboundStreamRestartWithCompressionInFlightSpec extends MultiNodeC */ case class TellAndEcho(ref: ActorRef) extends Actor { override def receive = { - case msg ⇒ + case msg => ref ! msg val reply = s"${self.path.name}-$msg" sender() ! reply @@ -93,10 +93,10 @@ abstract class SurviveInboundStreamRestartWithCompressionInFlightSpec extends Re val sendToB = expectMsgType[ActorIdentity].ref.get runOn(second) { - 1 to 100 foreach { i ⇒ pingPong(sendToA, s"a$i") } + 1 to 100 foreach { i => pingPong(sendToA, s"a$i") } info("done sending to A, first round") - 1 to 100 foreach { i ⇒ pingPong(sendToB, s"a$i") } + 1 to 100 foreach { i => pingPong(sendToB, s"a$i") } info("done sending to B, first round") } enterBarrier("sender-started") @@ -129,8 +129,8 @@ abstract class SurviveInboundStreamRestartWithCompressionInFlightSpec extends Re // we continue sending messages using the "old table". // if a new table was being built, it would cause the b to be compressed as 1 causing a wrong reply to come back - 1 to 100 foreach { i ⇒ pingPong(sendToB, s"b$i") } - 1 to 100 foreach { i ⇒ pingPong(sendToA, s"a$i") } + 1 to 100 foreach { i => pingPong(sendToB, s"b$i") } + 1 to 100 foreach { i => pingPong(sendToA, s"a$i") } info("received correct replies from restarted system!") } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/TaskRunnerMetrics.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/TaskRunnerMetrics.scala index 5088a5544b..d60137d64d 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/TaskRunnerMetrics.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/TaskRunnerMetrics.scala @@ -18,25 +18,25 @@ class TaskRunnerMetrics(system: ActorSystem) { val aeronSourceHistogram = new Histogram(SECONDS.toNanos(10), 3) val aeronSinkHistogram = new Histogram(SECONDS.toNanos(10), 3) system.asInstanceOf[ExtendedActorSystem].provider.asInstanceOf[RemoteActorRefProvider].transport match { - case a: ArteryTransport ⇒ - a.afrFileChannel.foreach { afrFileChannel ⇒ + case a: ArteryTransport => + a.afrFileChannel.foreach { afrFileChannel => var c = 0 var aeronSourceMaxBeforeDelegate = 0L var aeronSinkMaxBeforeDelegate = 0L val reader = new FlightRecorderReader(afrFileChannel) - reader.structure.hiFreqLog.logs.foreach(_.compactEntries.foreach { entry ⇒ + reader.structure.hiFreqLog.logs.foreach(_.compactEntries.foreach { entry => c += 1 if (c > entryOffset) { entry.code match { - case FlightRecorderEvents.AeronSource_ReturnFromTaskRunner ⇒ + case FlightRecorderEvents.AeronSource_ReturnFromTaskRunner => aeronSourceHistogram.recordValue(entry.param) - case FlightRecorderEvents.AeronSink_ReturnFromTaskRunner ⇒ + case FlightRecorderEvents.AeronSink_ReturnFromTaskRunner => aeronSinkHistogram.recordValue(entry.param) - case FlightRecorderEvents.AeronSource_DelegateToTaskRunner ⇒ + case FlightRecorderEvents.AeronSource_DelegateToTaskRunner => aeronSourceMaxBeforeDelegate = math.max(aeronSourceMaxBeforeDelegate, entry.param) - case FlightRecorderEvents.AeronSink_DelegateToTaskRunner ⇒ + case FlightRecorderEvents.AeronSink_DelegateToTaskRunner => aeronSinkMaxBeforeDelegate = math.max(aeronSinkMaxBeforeDelegate, entry.param) - case _ ⇒ + case _ => } } }) @@ -54,7 +54,7 @@ class TaskRunnerMetrics(system: ActorSystem) { aeronSinkHistogram.outputPercentileDistribution(System.out, 1000.0) } } - case _ ⇒ + case _ => } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/TestMessage.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/TestMessage.scala index 464c71427f..2b9c5c9e9d 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/TestMessage.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/TestMessage.scala @@ -6,7 +6,7 @@ package akka.remote.artery import akka.actor.ExtendedActorSystem import akka.serialization.SerializerWithStringManifest -import akka.remote.artery.protobuf.{ TestMessages ⇒ proto } +import akka.remote.artery.protobuf.{ TestMessages => proto } import akka.protobuf.ByteString object TestMessage { @@ -29,18 +29,18 @@ class TestMessageSerializer(val system: ExtendedActorSystem) extends SerializerW override def manifest(o: AnyRef): String = o match { - case _: TestMessage ⇒ TestMessageManifest + case _: TestMessage => TestMessageManifest } override def toBinary(o: AnyRef): Array[Byte] = o match { - case msg: TestMessage ⇒ + case msg: TestMessage => val builder = proto.TestMessage.newBuilder() .setId(msg.id) .setName(msg.name) .setDescription(msg.description) .setStatus(msg.status) .setPayload(ByteString.copyFrom(msg.payload)) - msg.items.foreach { item ⇒ + msg.items.foreach { item => builder.addItems(proto.Item.newBuilder().setId(item.id).setName(item.name)) } builder.build().toByteArray() @@ -49,7 +49,7 @@ class TestMessageSerializer(val system: ExtendedActorSystem) extends SerializerW override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { val protoMsg = proto.TestMessage.parseFrom(bytes) import scala.collection.JavaConverters._ - val items = protoMsg.getItemsList.asScala.map { item ⇒ + val items = protoMsg.getItemsList.asScala.map { item => TestMessage.Item(item.getId, item.getName) }.toVector diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/UdpPortActor.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/UdpPortActor.scala index 9497488f65..d3ed23f875 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/UdpPortActor.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/UdpPortActor.scala @@ -22,6 +22,6 @@ class UdpPortActor extends Actor { .getDefaultAddress.host.get, udp = true).getPort def receive = { - case GetUdpPort ⇒ sender() ! port + case GetUdpPort => sender() ! port } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamConcistencySpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamConcistencySpec.scala index ad51184c48..26e587a7a7 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamConcistencySpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamConcistencySpec.scala @@ -123,7 +123,7 @@ abstract class AeronStreamConsistencySpec val startMsg = "0".getBytes("utf-8") Source.fromGraph(new AeronSource(channel(first), streamId, aeron, taskRunner, pool, IgnoreEventSink, 0)) .via(killSwitch.flow) - .runForeach { envelope ⇒ + .runForeach { envelope => val bytes = ByteString.fromByteBuffer(envelope.byteBuffer) if (bytes.length == 1 && bytes(0) == startMsg(0)) started.ref ! Done @@ -140,7 +140,7 @@ abstract class AeronStreamConsistencySpec }.failed.foreach { _.printStackTrace } within(10.seconds) { - Source(1 to 100).map { _ ⇒ + Source(1 to 100).map { _ => val envelope = pool.acquire() envelope.byteBuffer.put(startMsg) envelope.byteBuffer.flip() @@ -153,7 +153,7 @@ abstract class AeronStreamConsistencySpec Source(1 to totalMessages) .throttle(10000, 1.second, 1000, ThrottleMode.Shaping) - .map { n ⇒ + .map { n => val envelope = pool.acquire() envelope.byteBuffer.put(n.toString.getBytes("utf-8")) envelope.byteBuffer.flip() diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamLatencySpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamLatencySpec.scala index 81e06082e0..8a30a7b8ad 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamLatencySpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamLatencySpec.scala @@ -218,7 +218,7 @@ abstract class AeronStreamLatencySpec val startMsg = "0".getBytes("utf-8") Source.fromGraph(new AeronSource(channel(first), streamId, aeron, taskRunner, pool, IgnoreEventSink, 0)) .via(killSwitch.flow) - .runForeach { envelope ⇒ + .runForeach { envelope => val bytes = ByteString.fromByteBuffer(envelope.byteBuffer) if (bytes.length == 1 && bytes(0) == startMsg(0)) started.ref ! Done @@ -238,7 +238,7 @@ abstract class AeronStreamLatencySpec } within(10.seconds) { - Source(1 to 50).map { _ ⇒ + Source(1 to 50).map { _ => val envelope = pool.acquire() envelope.byteBuffer.put(startMsg) envelope.byteBuffer.flip() @@ -249,13 +249,13 @@ abstract class AeronStreamLatencySpec started.expectMsg(Done) } - for (rep ← 1 to repeat) { + for (rep <- 1 to repeat) { histogram.reset() count.set(0) lastRepeat.set(rep == repeat) val sendFlow = Flow[Unit] - .map { _ ⇒ + .map { _ => val envelope = pool.acquire() envelope.byteBuffer.put(payload) envelope.byteBuffer.flip() @@ -324,7 +324,7 @@ abstract class AeronStreamLatencySpec enterBarrier("echo-started") } - for (s ← scenarios) { + for (s <- scenarios) { s"be low for ${s.testName}, at ${s.messageRate} msg/s, payloadSize = ${s.payloadSize}" in test(s) } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala index 47ebbc9537..e620a41903 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala @@ -184,7 +184,7 @@ abstract class AeronStreamMaxThroughputSpec val killSwitch = KillSwitches.shared(testName) Source.fromGraph(new AeronSource(channel(second), streamId, aeron, taskRunner, pool, IgnoreEventSink, 0)) .via(killSwitch.flow) - .runForeach { envelope ⇒ + .runForeach { envelope => val bytes = ByteString.fromByteBuffer(envelope.byteBuffer) rep.onMessage(1, bytes.length) count += 1 @@ -210,8 +210,8 @@ abstract class AeronStreamMaxThroughputSpec val payload = ("0" * payloadSize).getBytes("utf-8") val t0 = System.nanoTime() - Source.fromIterator(() ⇒ iterate(1, totalMessages)) - .map { n ⇒ + Source.fromIterator(() => iterate(1, totalMessages)) + .map { n => val envelope = pool.acquire() envelope.byteBuffer.put(payload) envelope.byteBuffer.flip() @@ -234,7 +234,7 @@ abstract class AeronStreamMaxThroughputSpec enterBarrier("udp-port-started") } - for (s ← scenarios) { + for (s <- scenarios) { s"be great for ${s.testName}, payloadSize = ${s.payloadSize}" in test(s) } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteRandomSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteRandomSpec.scala index 20f66243d7..1136b0c9eb 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteRandomSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteRandomSpec.scala @@ -52,7 +52,7 @@ class ArteryRemoteRandomMultiJvmNode4 extends RemoteRandomSpec(new RemoteRandomC object RemoteRandomSpec { class SomeActor extends Actor { def receive = { - case "hit" ⇒ sender() ! self + case "hit" => sender() ! self } } } @@ -79,14 +79,14 @@ class RemoteRandomSpec(multiNodeConfig: RemoteRandomConfig) extends RemotingMult val connectionCount = 3 val iterationCount = 100 - for (i ← 0 until iterationCount; k ← 0 until connectionCount) { + for (i <- 0 until iterationCount; k <- 0 until connectionCount) { actor ! "hit" } val replies: Map[Address, Int] = (receiveWhile(5.seconds, messages = connectionCount * iterationCount) { - case ref: ActorRef ⇒ ref.path.address - }).foldLeft(Map(node(first).address → 0, node(second).address → 0, node(third).address → 0)) { - case (replyMap, address) ⇒ replyMap + (address → (replyMap(address) + 1)) + case ref: ActorRef => ref.path.address + }).foldLeft(Map(node(first).address -> 0, node(second).address -> 0, node(third).address -> 0)) { + case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) } enterBarrier("broadcast-end") diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteRoundRobinSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteRoundRobinSpec.scala index 701d14e8db..ef02567e6c 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteRoundRobinSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteRoundRobinSpec.scala @@ -64,7 +64,7 @@ class ArteryRemoteRoundRobinMultiJvmNode4 extends RemoteRoundRobinSpec(new Remot object RemoteRoundRobinSpec { class SomeActor extends Actor { def receive = { - case "hit" ⇒ sender() ! self + case "hit" => sender() ! self } } @@ -96,16 +96,16 @@ class RemoteRoundRobinSpec(multiNodeConfig: RemoteRoundRobinConfig) extends Remo val connectionCount = 3 val iterationCount = 10 - for (i ← 0 until iterationCount; k ← 0 until connectionCount) { + for (i <- 0 until iterationCount; k <- 0 until connectionCount) { actor ! "hit" } val replies: Map[Address, Int] = (receiveWhile(5 seconds, messages = connectionCount * iterationCount) { - case ref: ActorRef ⇒ + case ref: ActorRef => info(s"reply from $ref") ref.path.address - }).foldLeft(Map(node(first).address → 0, node(second).address → 0, node(third).address → 0)) { - case (replyMap, address) ⇒ replyMap + (address → (replyMap(address) + 1)) + }).foldLeft(Map(node(first).address -> 0, node(second).address -> 0, node(third).address -> 0)) { + case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) } enterBarrier("broadcast-end") @@ -143,7 +143,7 @@ class RemoteRoundRobinSpec(multiNodeConfig: RemoteRoundRobinConfig) extends Remo expectMsgType[Routees].routees.size should ===(2) val repliesFrom: Set[ActorRef] = - (for (n ← 3 to 9) yield { + (for (n <- 3 to 9) yield { // each message trigger a resize, incrementing number of routees with 1 actor ! "hit" Await.result(actor ? GetRoutees, timeout.duration).asInstanceOf[Routees].routees.size should ===(n) @@ -183,14 +183,14 @@ class RemoteRoundRobinSpec(multiNodeConfig: RemoteRoundRobinConfig) extends Remo val connectionCount = 3 val iterationCount = 10 - for (i ← 0 until iterationCount; k ← 0 until connectionCount) { + for (i <- 0 until iterationCount; k <- 0 until connectionCount) { actor ! "hit" } val replies: Map[Address, Int] = (receiveWhile(5 seconds, messages = connectionCount * iterationCount) { - case ref: ActorRef ⇒ ref.path.address - }).foldLeft(Map(node(first).address → 0, node(second).address → 0, node(third).address → 0)) { - case (replyMap, address) ⇒ replyMap + (address → (replyMap(address) + 1)) + case ref: ActorRef => ref.path.address + }).foldLeft(Map(node(first).address -> 0, node(second).address -> 0, node(third).address -> 0)) { + case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) } enterBarrier("end") diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteScatterGatherSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteScatterGatherSpec.scala index 346483795a..1af84f64a6 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteScatterGatherSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/routing/RemoteScatterGatherSpec.scala @@ -53,7 +53,7 @@ class ArteryRemoteScatterGatherMultiJvmNode4 extends RemoteScatterGatherSpec(new object RemoteScatterGatherSpec { class SomeActor extends Actor { def receive = { - case "hit" ⇒ sender() ! self + case "hit" => sender() ! self } } } @@ -85,14 +85,14 @@ class RemoteScatterGatherSpec(multiNodeConfig: RemoteScatterGatherConfig) extend // let them start Thread.sleep(2000) - for (i ← 0 until iterationCount; k ← 0 until connectionCount) { + for (i <- 0 until iterationCount; k <- 0 until connectionCount) { actor ! "hit" } val replies: Map[Address, Int] = (receiveWhile(5.seconds, messages = connectionCount * iterationCount) { - case ref: ActorRef ⇒ ref.path.address - }).foldLeft(Map(node(first).address → 0, node(second).address → 0, node(third).address → 0)) { - case (replyMap, address) ⇒ replyMap + (address → (replyMap(address) + 1)) + case ref: ActorRef => ref.path.address + }).foldLeft(Map(node(first).address -> 0, node(second).address -> 0, node(third).address -> 0)) { + case (replyMap, address) => replyMap + (address -> (replyMap(address) + 1)) } enterBarrier("broadcast-end") diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/sample/MultiNodeSample.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/sample/MultiNodeSample.scala index d2c0896abd..f9b0e4b935 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/sample/MultiNodeSample.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/sample/MultiNodeSample.scala @@ -27,7 +27,7 @@ class MultiNodeSampleSpecMultiJvmNode2 extends MultiNodeSample object MultiNodeSample { class Ponger extends Actor { def receive = { - case "ping" ⇒ sender() ! "pong" + case "ping" => sender() ! "pong" } } } diff --git a/akka-remote-tests/src/multi-jvm/scala/akka/remote/testconductor/TestConductorSpec.scala b/akka-remote-tests/src/multi-jvm/scala/akka/remote/testconductor/TestConductorSpec.scala index 1a163fecbf..e65e8807ef 100644 --- a/akka-remote-tests/src/multi-jvm/scala/akka/remote/testconductor/TestConductorSpec.scala +++ b/akka-remote-tests/src/multi-jvm/scala/akka/remote/testconductor/TestConductorSpec.scala @@ -43,7 +43,7 @@ class TestConductorSpec extends RemotingMultiNodeSpec(TestConductorMultiJvmSpec) runOn(master) { system.actorOf(Props(new Actor { def receive = { - case x ⇒ testActor ! x; sender() ! x + case x => testActor ! x; sender() ! x } }).withDeploy(Deploy.local), "echo") } @@ -67,7 +67,7 @@ class TestConductorSpec extends RemotingMultiNodeSpec(TestConductorMultiJvmSpec) enterBarrier("throttled_send") runOn(slave) { - for (i ← 0 to 9) echo ! i + for (i <- 0 to 9) echo ! i } within(0.5 seconds, 2 seconds) { @@ -85,7 +85,7 @@ class TestConductorSpec extends RemotingMultiNodeSpec(TestConductorMultiJvmSpec) enterBarrier("throttled_recv") runOn(slave) { - for (i ← 10 to 19) echo ! i + for (i <- 10 to 19) echo ! i } val (min, max) = diff --git a/akka-remote-tests/src/test/scala/akka/remote/artery/ArteryFailedToBindSpec.scala b/akka-remote-tests/src/test/scala/akka/remote/artery/ArteryFailedToBindSpec.scala index c2a53e4e23..fde236a18a 100644 --- a/akka-remote-tests/src/test/scala/akka/remote/artery/ArteryFailedToBindSpec.scala +++ b/akka-remote-tests/src/test/scala/akka/remote/artery/ArteryFailedToBindSpec.scala @@ -39,9 +39,9 @@ class ArteryFailedToBindSpec extends WordSpec with Matchers { ActorSystem("BindTest2", config) } RARP(as).provider.transport.asInstanceOf[ArteryTransport].settings.Transport match { - case ArterySettings.AeronUpd ⇒ + case ArterySettings.AeronUpd => ex.getMessage should ===("Inbound Aeron channel is in errored state. See Aeron logs for details.") - case ArterySettings.Tcp | ArterySettings.TlsTcp ⇒ + case ArterySettings.Tcp | ArterySettings.TlsTcp => ex.getMessage should startWith("Failed to bind TCP") } diff --git a/akka-remote-tests/src/test/scala/akka/remote/testconductor/BarrierSpec.scala b/akka-remote-tests/src/test/scala/akka/remote/testconductor/BarrierSpec.scala index de81b305ec..90acc7a121 100644 --- a/akka-remote-tests/src/test/scala/akka/remote/testconductor/BarrierSpec.scala +++ b/akka-remote-tests/src/test/scala/akka/remote/testconductor/BarrierSpec.scala @@ -132,8 +132,8 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } val msg = expectMsgType[Failed] msg match { - case Failed(barrier, thr: ClientLost) if (thr == ClientLost(Data(Set(nodeA), "bar6", a.ref :: Nil, thr.data.deadline), B)) ⇒ - case x ⇒ fail("Expected " + Failed(barrier, ClientLost(Data(Set(nodeA), "bar6", a.ref :: Nil, null), B)) + " but got " + x) + case Failed(barrier, thr: ClientLost) if (thr == ClientLost(Data(Set(nodeA), "bar6", a.ref :: Nil, thr.data.deadline), B)) => + case x => fail("Expected " + Failed(barrier, ClientLost(Data(Set(nodeA), "bar6", a.ref :: Nil, null), B)) + " but got " + x) } } @@ -152,8 +152,8 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } val msg = expectMsgType[Failed] msg match { - case Failed(barrier, thr: ClientLost) if (thr == ClientLost(Data(Set(nodeA, nodeC), "bar7", a.ref :: Nil, thr.data.deadline), B)) ⇒ - case x ⇒ fail("Expected " + Failed(barrier, ClientLost(Data(Set(nodeA, nodeC), "bar7", a.ref :: Nil, null), B)) + " but got " + x) + case Failed(barrier, thr: ClientLost) if (thr == ClientLost(Data(Set(nodeA, nodeC), "bar7", a.ref :: Nil, thr.data.deadline), B)) => + case x => fail("Expected " + Failed(barrier, ClientLost(Data(Set(nodeA, nodeC), "bar7", a.ref :: Nil, null), B)) + " but got " + x) } } @@ -170,8 +170,8 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } val msg = expectMsgType[Failed] msg match { - case Failed(barrier, thr: WrongBarrier) if (thr == WrongBarrier("foo", b.ref, Data(Set(nodeA, nodeB), "bar8", a.ref :: Nil, thr.data.deadline))) ⇒ - case x ⇒ fail("Expected " + Failed(barrier, WrongBarrier("foo", b.ref, Data(Set(nodeA, nodeB), "bar8", a.ref :: Nil, null))) + " but got " + x) + case Failed(barrier, thr: WrongBarrier) if (thr == WrongBarrier("foo", b.ref, Data(Set(nodeA, nodeB), "bar8", a.ref :: Nil, thr.data.deadline))) => + case x => fail("Expected " + Failed(barrier, WrongBarrier("foo", b.ref, Data(Set(nodeA, nodeB), "bar8", a.ref :: Nil, null))) + " but got " + x) } } @@ -183,8 +183,8 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } val msg = expectMsgType[Failed] msg match { - case Failed(barrier, thr: BarrierEmpty) if (thr == BarrierEmpty(Data(Set(), "", Nil, thr.data.deadline), "cannot remove RoleName(a): no client to remove")) ⇒ - case x ⇒ fail("Expected " + Failed(barrier, BarrierEmpty(Data(Set(), "", Nil, null), "cannot remove RoleName(a): no client to remove")) + " but got " + x) + case Failed(barrier, thr: BarrierEmpty) if (thr == BarrierEmpty(Data(Set(), "", Nil, thr.data.deadline), "cannot remove RoleName(a): no client to remove")) => + case x => fail("Expected " + Failed(barrier, BarrierEmpty(Data(Set(), "", Nil, null), "cannot remove RoleName(a): no client to remove")) + " but got " + x) } barrier ! NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) a.send(barrier, EnterBarrier("bar9", None)) @@ -202,8 +202,8 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { EventFilter[BarrierTimeout](occurrences = 1) intercept { val msg = expectMsgType[Failed](7 seconds) msg match { - case Failed(barrier, thr: BarrierTimeout) if (thr == BarrierTimeout(Data(Set(nodeA, nodeB), "bar10", a.ref :: Nil, thr.data.deadline))) ⇒ - case x ⇒ fail("Expected " + Failed(barrier, BarrierTimeout(Data(Set(nodeA, nodeB), "bar10", a.ref :: Nil, null))) + " but got " + x) + case Failed(barrier, thr: BarrierTimeout) if (thr == BarrierTimeout(Data(Set(nodeA, nodeB), "bar10", a.ref :: Nil, thr.data.deadline))) => + case x => fail("Expected " + Failed(barrier, BarrierTimeout(Data(Set(nodeA, nodeB), "bar10", a.ref :: Nil, null))) + " but got " + x) } } } @@ -219,8 +219,8 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } val msg = expectMsgType[Failed] msg match { - case Failed(barrier, thr: DuplicateNode) if (thr == DuplicateNode(Data(Set(nodeA), "", Nil, thr.data.deadline), nodeB)) ⇒ - case x ⇒ fail("Expected " + Failed(barrier, DuplicateNode(Data(Set(nodeA), "", Nil, null), nodeB)) + " but got " + x) + case Failed(barrier, thr: DuplicateNode) if (thr == DuplicateNode(Data(Set(nodeA), "", Nil, thr.data.deadline), nodeB)) => + case x => fail("Expected " + Failed(barrier, DuplicateNode(Data(Set(nodeA), "", Nil, null), nodeB)) + " but got " + x) } } @@ -233,7 +233,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { "A Controller with BarrierCoordinator" must { "register clients and remove them" taggedAs TimingTest in { - withController(1) { b ⇒ + withController(1) { b => b ! NodeInfo(A, AddressFromURIString("akka://sys"), testActor) expectMsg(ToClient(Done)) b ! Remove(B) @@ -246,7 +246,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "register clients and disconnect them" taggedAs TimingTest in { - withController(1) { b ⇒ + withController(1) { b => b ! NodeInfo(A, AddressFromURIString("akka://sys"), testActor) expectMsg(ToClient(Done)) b ! ClientDisconnected(B) @@ -257,14 +257,14 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "fail entering barrier when nobody registered" taggedAs TimingTest in { - withController(0) { b ⇒ + withController(0) { b => b ! EnterBarrier("b", None) expectMsg(ToClient(BarrierResult("b", false))) } } "enter barrier" taggedAs TimingTest in { - withController(2) { barrier ⇒ + withController(2) { barrier => val a, b = TestProbe() barrier ! NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) barrier ! NodeInfo(B, AddressFromURIString("akka://sys"), b.ref) @@ -281,7 +281,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "enter barrier with joining node" taggedAs TimingTest in { - withController(2) { barrier ⇒ + withController(2) { barrier => val a, b, c = TestProbe() barrier ! NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) barrier ! NodeInfo(B, AddressFromURIString("akka://sys"), b.ref) @@ -302,7 +302,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "enter barrier with leaving node" taggedAs TimingTest in { - withController(3) { barrier ⇒ + withController(3) { barrier => val a, b, c = TestProbe() barrier ! NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) barrier ! NodeInfo(B, AddressFromURIString("akka://sys"), b.ref) @@ -325,7 +325,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "leave barrier when last “arrived” is removed" taggedAs TimingTest in { - withController(2) { barrier ⇒ + withController(2) { barrier => val a, b = TestProbe() barrier ! NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) barrier ! NodeInfo(B, AddressFromURIString("akka://sys"), b.ref) @@ -339,7 +339,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "fail barrier with disconnecing node" taggedAs TimingTest in { - withController(2) { barrier ⇒ + withController(2) { barrier => val a, b = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) barrier ! nodeA @@ -357,7 +357,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "fail barrier with disconnecing node who already arrived" taggedAs TimingTest in { - withController(3) { barrier ⇒ + withController(3) { barrier => val a, b, c = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) val nodeC = NodeInfo(C, AddressFromURIString("akka://sys"), c.ref) @@ -377,7 +377,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "fail when entering wrong barrier" taggedAs TimingTest in { - withController(2) { barrier ⇒ + withController(2) { barrier => val a, b = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) barrier ! nodeA @@ -395,7 +395,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "fail after barrier timeout" taggedAs TimingTest in { - withController(2) { barrier ⇒ + withController(2) { barrier => val a, b = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) val nodeB = NodeInfo(B, AddressFromURIString("akka://sys"), b.ref) @@ -414,7 +414,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "fail if a node registers twice" taggedAs TimingTest in { - withController(2) { controller ⇒ + withController(2) { controller => val a, b = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) val nodeB = NodeInfo(A, AddressFromURIString("akka://sys"), b.ref) @@ -428,7 +428,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "fail subsequent barriers if a node registers twice" taggedAs TimingTest in { - withController(1) { controller ⇒ + withController(1) { controller => val a, b = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) val nodeB = NodeInfo(A, AddressFromURIString("akka://sys"), b.ref) @@ -444,7 +444,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "fail subsequent barriers after foreced failure" taggedAs TimingTest in { - withController(2) { barrier ⇒ + withController(2) { barrier => val a, b = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) val nodeB = NodeInfo(B, AddressFromURIString("akka://sys"), b.ref) @@ -466,7 +466,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "timeout within the shortest timeout if the new timeout is shorter" taggedAs TimingTest in { - withController(3) { barrier ⇒ + withController(3) { barrier => val a, b, c = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) val nodeB = NodeInfo(B, AddressFromURIString("akka://sys"), b.ref) @@ -490,7 +490,7 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } "timeout within the shortest timeout if the new timeout is longer" taggedAs TimingTest in { - withController(3) { barrier ⇒ + withController(3) { barrier => val a, b, c = TestProbe() val nodeA = NodeInfo(A, AddressFromURIString("akka://sys"), a.ref) val nodeB = NodeInfo(B, AddressFromURIString("akka://sys"), b.ref) @@ -519,15 +519,15 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { } - private def withController(participants: Int)(f: (ActorRef) ⇒ Unit): Unit = { + private def withController(participants: Int)(f: (ActorRef) => Unit): Unit = { system.actorOf(Props(new Actor { val controller = context.actorOf(Props(classOf[Controller], participants, new InetSocketAddress(InetAddress.getLocalHost, 0))) controller ! GetSockAddr override def supervisorStrategy = OneForOneStrategy() { - case x ⇒ testActor ! Failed(controller, x); SupervisorStrategy.Restart + case x => testActor ! Failed(controller, x); SupervisorStrategy.Restart } def receive = { - case x: InetSocketAddress ⇒ testActor ! controller + case x: InetSocketAddress => testActor ! controller } }).withDeploy(Deploy.local)) val actor = expectMsgType[ActorRef] @@ -543,10 +543,10 @@ class BarrierSpec extends AkkaSpec(BarrierSpec.config) with ImplicitSender { system.actorOf(Props(new Actor { val barrier = context.actorOf(Props[BarrierCoordinator]) override def supervisorStrategy = OneForOneStrategy() { - case x ⇒ testActor ! Failed(barrier, x); SupervisorStrategy.Restart + case x => testActor ! Failed(barrier, x); SupervisorStrategy.Restart } def receive = { - case _ ⇒ sender() ! barrier + case _ => sender() ! barrier } }).withDeploy(Deploy.local)) ! "" expectMsgType[ActorRef] diff --git a/akka-remote-tests/src/test/scala/akka/remote/testkit/LogRoleReplace.scala b/akka-remote-tests/src/test/scala/akka/remote/testkit/LogRoleReplace.scala index 9a5172cc8c..51d8177071 100644 --- a/akka-remote-tests/src/test/scala/akka/remote/testkit/LogRoleReplace.scala +++ b/akka-remote-tests/src/test/scala/akka/remote/testkit/LogRoleReplace.scala @@ -127,17 +127,17 @@ class LogRoleReplace { } line match { - case RoleStarted(jvm, role, host, port) ⇒ - replacements += (jvm → role) - replacements += ((host + ":" + port) → role) + case RoleStarted(jvm, role, host, port) => + replacements += (jvm -> role) + replacements += ((host + ":" + port) -> role) false - case _ ⇒ true + case _ => true } } private def replaceLine(line: String): String = { var result = line - for ((from, to) ← replacements) { + for ((from, to) <- replacements) { result = result.replaceAll(from, to) } result diff --git a/akka-remote-tests/src/test/scala/akka/remote/testkit/STMultiNodeSpec.scala b/akka-remote-tests/src/test/scala/akka/remote/testkit/STMultiNodeSpec.scala index 588d7f40de..844de9349c 100644 --- a/akka-remote-tests/src/test/scala/akka/remote/testkit/STMultiNodeSpec.scala +++ b/akka-remote-tests/src/test/scala/akka/remote/testkit/STMultiNodeSpec.scala @@ -14,7 +14,7 @@ import org.scalatest.Matchers * Hooks up MultiNodeSpec with ScalaTest */ trait STMultiNodeSpec extends MultiNodeSpecCallbacks - with WordSpecLike with Matchers with BeforeAndAfterAll { self: MultiNodeSpec ⇒ + with WordSpecLike with Matchers with BeforeAndAfterAll { self: MultiNodeSpec => override def beforeAll() = multiNodeSpecBeforeAll() diff --git a/akka-remote-tests/src/test/scala/org/scalatest/extra/QuietReporter.scala b/akka-remote-tests/src/test/scala/org/scalatest/extra/QuietReporter.scala index 80db884d5a..436b4ec1f6 100644 --- a/akka-remote-tests/src/test/scala/org/scalatest/extra/QuietReporter.scala +++ b/akka-remote-tests/src/test/scala/org/scalatest/extra/QuietReporter.scala @@ -14,7 +14,7 @@ class QuietReporter(inColor: Boolean, withDurations: Boolean = false) def this() = this(!getBoolean("akka.test.nocolor"), !getBoolean("akka.test.nodurations")) override def apply(event: Event): Unit = event match { - case _: RunStarting ⇒ () - case _ ⇒ super.apply(event) + case _: RunStarting => () + case _ => super.apply(event) } } diff --git a/akka-remote/src/main/scala/akka/remote/AckedDelivery.scala b/akka-remote/src/main/scala/akka/remote/AckedDelivery.scala index f52b20d6df..a780dae6f3 100644 --- a/akka-remote/src/main/scala/akka/remote/AckedDelivery.scala +++ b/akka-remote/src/main/scala/akka/remote/AckedDelivery.scala @@ -104,10 +104,10 @@ final case class AckedSendBuffer[T <: HasSequenceNumber]( throw new IllegalArgumentException(s"Highest SEQ so far was $maxSeq but cumulative ACK is ${ack.cumulativeAck}") val newNacked = if (ack.nacks.isEmpty) Vector.empty - else (nacked ++ nonAcked) filter { m ⇒ ack.nacks(m.seq) } + else (nacked ++ nonAcked) filter { m => ack.nacks(m.seq) } if (newNacked.size < ack.nacks.size) throw new ResendUnfulfillableException else this.copy( - nonAcked = nonAcked.filter { m ⇒ m.seq > ack.cumulativeAck }, + nonAcked = nonAcked.filter { m => m.seq > ack.cumulativeAck }, nacked = newNacked) } @@ -166,7 +166,7 @@ final case class AckedReceiveBuffer[T <: HasSequenceNumber]( var updatedLastDelivered = lastDelivered var prev = lastDelivered - for (bufferedMsg ← buf) { + for (bufferedMsg <- buf) { if (bufferedMsg.seq.isSuccessor(updatedLastDelivered)) { deliver :+= bufferedMsg updatedLastDelivered = updatedLastDelivered.inc diff --git a/akka-remote/src/main/scala/akka/remote/BoundAddressesExtension.scala b/akka-remote/src/main/scala/akka/remote/BoundAddressesExtension.scala index abf16805c6..7212eae09e 100644 --- a/akka-remote/src/main/scala/akka/remote/BoundAddressesExtension.scala +++ b/akka-remote/src/main/scala/akka/remote/BoundAddressesExtension.scala @@ -30,7 +30,7 @@ class BoundAddressesExtension(val system: ExtendedActorSystem) extends Extension */ def boundAddresses: Map[String, Set[Address]] = system.provider .asInstanceOf[RemoteActorRefProvider].transport match { - case artery: ArteryTransport ⇒ Map(ArteryTransport.ProtocolName → Set(artery.bindAddress.address)) - case remoting: Remoting ⇒ remoting.boundAddresses + case artery: ArteryTransport => Map(ArteryTransport.ProtocolName -> Set(artery.bindAddress.address)) + case remoting: Remoting => remoting.boundAddresses } } diff --git a/akka-remote/src/main/scala/akka/remote/DefaultFailureDetectorRegistry.scala b/akka-remote/src/main/scala/akka/remote/DefaultFailureDetectorRegistry.scala index 055905f360..aaa434838d 100644 --- a/akka-remote/src/main/scala/akka/remote/DefaultFailureDetectorRegistry.scala +++ b/akka-remote/src/main/scala/akka/remote/DefaultFailureDetectorRegistry.scala @@ -16,26 +16,26 @@ import java.util.concurrent.locks.{ ReentrantLock, Lock } * By-name parameter that returns the failure detector instance to be used by a newly registered resource * */ -class DefaultFailureDetectorRegistry[A](detectorFactory: () ⇒ FailureDetector) extends FailureDetectorRegistry[A] { +class DefaultFailureDetectorRegistry[A](detectorFactory: () => FailureDetector) extends FailureDetectorRegistry[A] { private val resourceToFailureDetector = new AtomicReference[Map[A, FailureDetector]](Map()) private final val failureDetectorCreationLock: Lock = new ReentrantLock final override def isAvailable(resource: A): Boolean = resourceToFailureDetector.get.get(resource) match { - case Some(r) ⇒ r.isAvailable - case _ ⇒ true + case Some(r) => r.isAvailable + case _ => true } final override def isMonitoring(resource: A): Boolean = resourceToFailureDetector.get.get(resource) match { - case Some(r) ⇒ r.isMonitoring - case _ ⇒ false + case Some(r) => r.isMonitoring + case _ => false } final override def heartbeat(resource: A): Unit = { resourceToFailureDetector.get.get(resource) match { - case Some(failureDetector) ⇒ failureDetector.heartbeat() - case None ⇒ + case Some(failureDetector) => failureDetector.heartbeat() + case None => // First one wins and creates the new FailureDetector failureDetectorCreationLock.lock() try { @@ -43,19 +43,19 @@ class DefaultFailureDetectorRegistry[A](detectorFactory: () ⇒ FailureDetector) // when this one acquired it, so the second check is needed. val oldTable = resourceToFailureDetector.get oldTable.get(resource) match { - case Some(failureDetector) ⇒ + case Some(failureDetector) => failureDetector.heartbeat() - case None ⇒ + case None => val newDetector: FailureDetector = detectorFactory() // address below was introduced as a var because of binary compatibility constraints newDetector match { - case phi: PhiAccrualFailureDetector ⇒ phi.address = resource.toString - case _ ⇒ + case phi: PhiAccrualFailureDetector => phi.address = resource.toString + case _ => } newDetector.heartbeat() - resourceToFailureDetector.set(oldTable + (resource → newDetector)) + resourceToFailureDetector.set(oldTable + (resource -> newDetector)) } } finally failureDetectorCreationLock.unlock() } diff --git a/akka-remote/src/main/scala/akka/remote/Endpoint.scala b/akka-remote/src/main/scala/akka/remote/Endpoint.scala index 5eca0c4e77..3bff8fd91b 100644 --- a/akka-remote/src/main/scala/akka/remote/Endpoint.scala +++ b/akka-remote/src/main/scala/akka/remote/Endpoint.scala @@ -74,17 +74,17 @@ private[remote] class DefaultMessageDispatcher( recipient match { - case `remoteDaemon` ⇒ + case `remoteDaemon` => if (UntrustedMode) log.debug(LogMarker.Security, "dropping daemon message in untrusted mode") else { logMessageReceived("daemon message") remoteDaemon ! payload } - case l @ (_: LocalRef | _: RepointableRef) if l.isLocal ⇒ + case l @ (_: LocalRef | _: RepointableRef) if l.isLocal => logMessageReceived("local message") payload match { - case sel: ActorSelectionMessage ⇒ + case sel: ActorSelectionMessage => if (UntrustedMode && (!TrustedSelectionPaths.contains(sel.elements.mkString("/", "/", "")) || sel.msg.isInstanceOf[PossiblyHarmful] || l != provider.rootGuardian)) log.debug( @@ -95,13 +95,13 @@ private[remote] class DefaultMessageDispatcher( else // run the receive logic for ActorSelectionMessage here to make sure it is not stuck on busy user actor ActorSelection.deliverSelection(l, sender, sel) - case msg: PossiblyHarmful if UntrustedMode ⇒ + case msg: PossiblyHarmful if UntrustedMode => log.debug(LogMarker.Security, "operating in UntrustedMode, dropping inbound PossiblyHarmful message of type [{}]", msg.getClass.getName) - case msg: SystemMessage ⇒ l.sendSystemMessage(msg) - case msg ⇒ l.!(msg)(sender) + case msg: SystemMessage => l.sendSystemMessage(msg) + case msg => l.!(msg)(sender) } - case r @ (_: RemoteRef | _: RepointableRef) if !r.isLocal && !UntrustedMode ⇒ + case r @ (_: RemoteRef | _: RepointableRef) if !r.isLocal && !UntrustedMode => logMessageReceived("remote-destined message") if (provider.transport.addresses(recipientAddress)) // if it was originally addressed to us but is in fact remote from our point of view (i.e. remote-deployed) @@ -111,7 +111,7 @@ private[remote] class DefaultMessageDispatcher( "dropping message [{}] for non-local recipient [{}] arriving at [{}] inbound addresses are [{}]", payloadClass, r, recipientAddress, provider.transport.addresses.mkString(", ")) - case r ⇒ log.error( + case r => log.error( "dropping message [{}] for unknown recipient [{}] arriving at [{}] inbound addresses are [{}]", payloadClass, r, recipientAddress, provider.transport.addresses.mkString(", ")) @@ -220,8 +220,8 @@ private[remote] class ReliableDeliverySupervisor( settings.SysResendTimeout, settings.SysResendTimeout, self, AttemptSysMsgRedelivery) override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) { - case _: AssociationProblem ⇒ Escalate - case NonFatal(e) ⇒ + case _: AssociationProblem => Escalate + case NonFatal(e) => val causedBy = if (e.getCause == null) "" else s"Caused by: [${e.getCause.getMessage}]" log.warning( "Association with remote system [{}] has failed, address is now gated for [{}] ms. Reason: [{}] {}", @@ -278,7 +278,7 @@ private[remote] class ReliableDeliverySupervisor( // Such a situation may arise when the EndpointWriter is shut down, and all of its mailbox contents are delivered // to dead letters. These messages should be ignored, as they still live in resendBuffer and might be delivered to // the remote system later. - (resendBuffer.nacked ++ resendBuffer.nonAcked) foreach { s ⇒ context.system.deadLetters ! s.copy(seqOpt = None) } + (resendBuffer.nacked ++ resendBuffer.nonAcked) foreach { s => context.system.deadLetters ! s.copy(seqOpt = None) } receiveBuffers.remove(Link(localAddress, remoteAddress)) autoResendTimer.cancel() maxSilenceTimer.foreach(_.cancel()) @@ -290,20 +290,20 @@ private[remote] class ReliableDeliverySupervisor( } override def receive: Receive = { - case FlushAndStop ⇒ + case FlushAndStop => // Trying to serve until our last breath resendAll() writer ! FlushAndStop context.become(flushWait) - case IsIdle ⇒ // Do not reply, we will Terminate soon, or send a GotUid - case s: Send ⇒ + case IsIdle => // Do not reply, we will Terminate soon, or send a GotUid + case s: Send => handleSend(s) - case ack: Ack ⇒ + case ack: Ack => // If we are not sure about the UID just ignore the ack. Ignoring is fine. if (uidConfirmed) { try resendBuffer = resendBuffer.acknowledge(ack) catch { - case NonFatal(e) ⇒ + case NonFatal(e) => throw new HopelessAssociation(localAddress, remoteAddress, uid, new IllegalStateException(s"Error encountered while processing system message " + s"acknowledgement buffer: $resendBuffer ack: $ack", e)) @@ -311,15 +311,15 @@ private[remote] class ReliableDeliverySupervisor( resendNacked() } - case AttemptSysMsgRedelivery ⇒ + case AttemptSysMsgRedelivery => if (uidConfirmed) resendAll() - case Terminated(_) ⇒ + case Terminated(_) => currentHandle = None context.parent ! StoppedReading(self) if (resendBuffer.nonAcked.nonEmpty || resendBuffer.nacked.nonEmpty) context.system.scheduler.scheduleOnce(settings.SysResendTimeout, self, AttemptSysMsgRedelivery) goToIdle() - case g @ GotUid(receivedUid, _) ⇒ + case g @ GotUid(receivedUid, _) => bailoutAt = None context.parent ! g // New system that has the same address as the old - need to start from fresh state @@ -328,21 +328,21 @@ private[remote] class ReliableDeliverySupervisor( uid = Some(receivedUid) resendAll() - case s: EndpointWriter.StopReading ⇒ + case s: EndpointWriter.StopReading => writer forward s - case Ungate ⇒ // ok, not gated + case Ungate => // ok, not gated } def gated(writerTerminated: Boolean, earlyUngateRequested: Boolean): Receive = { - case Terminated(_) if !writerTerminated ⇒ + case Terminated(_) if !writerTerminated => if (earlyUngateRequested) self ! Ungate else context.system.scheduler.scheduleOnce(settings.RetryGateClosedFor, self, Ungate) context.become(gated(writerTerminated = true, earlyUngateRequested)) - case IsIdle ⇒ sender() ! Idle - case Ungate ⇒ + case IsIdle => sender() ! Idle + case Ungate => if (!writerTerminated) { // Ungate was sent from EndpointManager, but we must wait for Terminated first. context.become(gated(writerTerminated = false, earlyUngateRequested = true)) @@ -359,36 +359,36 @@ private[remote] class ReliableDeliverySupervisor( // Resending will be triggered by the incoming GotUid message after the connection finished goToActive() } else goToIdle() - case AttemptSysMsgRedelivery ⇒ // Ignore - case s @ Send(_: SystemMessage, _, _, _) ⇒ tryBuffer(s.copy(seqOpt = Some(nextSeq()))) - case s: Send ⇒ context.system.deadLetters ! s - case EndpointWriter.FlushAndStop ⇒ context.stop(self) - case EndpointWriter.StopReading(w, replyTo) ⇒ + case AttemptSysMsgRedelivery => // Ignore + case s @ Send(_: SystemMessage, _, _, _) => tryBuffer(s.copy(seqOpt = Some(nextSeq()))) + case s: Send => context.system.deadLetters ! s + case EndpointWriter.FlushAndStop => context.stop(self) + case EndpointWriter.StopReading(w, replyTo) => replyTo ! EndpointWriter.StoppedReading(w) sender() ! EndpointWriter.StoppedReading(w) } def idle: Receive = { - case IsIdle ⇒ sender() ! Idle - case s: Send ⇒ + case IsIdle => sender() ! Idle + case s: Send => writer = createWriter() // Resending will be triggered by the incoming GotUid message after the connection finished handleSend(s) goToActive() - case AttemptSysMsgRedelivery ⇒ + case AttemptSysMsgRedelivery => if (resendBuffer.nacked.nonEmpty || resendBuffer.nonAcked.nonEmpty) { writer = createWriter() // Resending will be triggered by the incoming GotUid message after the connection finished goToActive() } - case TooLongIdle ⇒ + case TooLongIdle => throw new HopelessAssociation(localAddress, remoteAddress, uid, new TimeoutException("Remote system has been silent for too long. " + s"(more than ${settings.QuarantineSilentSystemTimeout.toUnit(TimeUnit.HOURS)} hours)")) - case EndpointWriter.FlushAndStop ⇒ context.stop(self) - case EndpointWriter.StopReading(w, replyTo) ⇒ + case EndpointWriter.FlushAndStop => context.stop(self) + case EndpointWriter.StopReading(w, replyTo) => replyTo ! EndpointWriter.StoppedReading(w) - case Ungate ⇒ // ok, not gated + case Ungate => // ok, not gated } private def goToIdle(): Unit = { @@ -404,13 +404,13 @@ private[remote] class ReliableDeliverySupervisor( } def flushWait: Receive = { - case IsIdle ⇒ // Do not reply, we will Terminate soon, which will do the inbound connection unstashing - case Terminated(_) ⇒ + case IsIdle => // Do not reply, we will Terminate soon, which will do the inbound connection unstashing + case Terminated(_) => // Clear buffer to prevent sending system messages to dead letters -- at this point we are shutting down // and don't really know if they were properly delivered or not. resendBuffer = new AckedSendBuffer[Send](0) context.stop(self) - case _ ⇒ // Ignore + case _ => // Ignore } private def handleSend(send: Send): Unit = @@ -435,7 +435,7 @@ private[remote] class ReliableDeliverySupervisor( try { resendBuffer = resendBuffer buffer s } catch { - case NonFatal(e) ⇒ throw new HopelessAssociation(localAddress, remoteAddress, uid, e) + case NonFatal(e) => throw new HopelessAssociation(localAddress, remoteAddress, uid, e) } private def createWriter(): ActorRef = { @@ -473,7 +473,7 @@ private[remote] abstract class EndpointActor( private def tryPublish(ev: AssociationEvent): Unit = try eventPublisher.notifyListeners(ev) - catch { case NonFatal(e) ⇒ log.error(e, "Unable to publish error event to EventStream.") } + catch { case NonFatal(e) => log.error(e, "Unable to publish error event to EventStream.") } } /** @@ -556,8 +556,8 @@ private[remote] class EndpointWriter( var lastAck: Option[Ack] = None override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) { - case e: ShutDownAssociation ⇒ publishAndThrow(e, Logging.InfoLevel) - case NonFatal(e) ⇒ publishAndThrow(e, Logging.ErrorLevel) + case e: ShutDownAssociation => publishAndThrow(e, Logging.InfoLevel) + case NonFatal(e) => publishAndThrow(e, Logging.ErrorLevel) } val provider = RARP(extendedSystem).provider @@ -575,8 +575,8 @@ private[remote] class EndpointWriter( private def publishAndThrow(reason: Throwable, logLevel: Logging.LogLevel): Nothing = { reason match { - case _: EndpointDisassociatedException ⇒ publishDisassociated() - case _ ⇒ publishError(reason, logLevel) + case _: EndpointDisassociatedException => publishDisassociated() + case _ => publishError(reason, logLevel) } throw reason } @@ -588,9 +588,9 @@ private[remote] class EndpointWriter( override def preStart(): Unit = { handle match { - case Some(h) ⇒ + case Some(h) => reader = startReadEndpoint(h) - case None ⇒ + case None => transport.associate(remoteAddress, refuseUid).map(Handle(_)) pipeTo self } } @@ -611,13 +611,13 @@ private[remote] class EndpointWriter( def receive = if (handle.isEmpty) initializing else writing def initializing: Receive = { - case s: Send ⇒ + case s: Send => enqueueInBuffer(s) - case Status.Failure(e: InvalidAssociationException) ⇒ + case Status.Failure(e: InvalidAssociationException) => publishAndThrow(new InvalidAssociation(localAddress, remoteAddress, e), Logging.WarningLevel) - case Status.Failure(e) ⇒ + case Status.Failure(e) => publishAndThrow(new EndpointAssociationException(s"Association failed with [$remoteAddress]", e), Logging.DebugLevel) - case Handle(inboundHandle) ⇒ + case Handle(inboundHandle) => // Assert handle == None? context.parent ! ReliableDeliverySupervisor.GotUid(inboundHandle.handshakeInfo.uid, remoteAddress) handle = Some(inboundHandle) @@ -627,19 +627,19 @@ private[remote] class EndpointWriter( } def enqueueInBuffer(msg: AnyRef): Unit = msg match { - case s @ Send(_: PriorityMessage, _, _, _) ⇒ prioBuffer offer s - case s @ Send(ActorSelectionMessage(_: PriorityMessage, _, _), _, _, _) ⇒ prioBuffer offer s - case _ ⇒ buffer offer msg + case s @ Send(_: PriorityMessage, _, _, _) => prioBuffer offer s + case s @ Send(ActorSelectionMessage(_: PriorityMessage, _, _), _, _, _) => prioBuffer offer s + case _ => buffer offer msg } val buffering: Receive = { - case s: Send ⇒ enqueueInBuffer(s) - case BackoffTimer ⇒ sendBufferedMessages() - case FlushAndStop ⇒ + case s: Send => enqueueInBuffer(s) + case BackoffTimer => sendBufferedMessages() + case FlushAndStop => // Flushing is postponed after the pending writes buffer offer FlushAndStop context.system.scheduler.scheduleOnce(settings.FlushWait, self, FlushAndStopTimeout) - case FlushAndStopTimeout ⇒ + case FlushAndStopTimeout => // enough flushAndStop() } @@ -678,12 +678,12 @@ private[remote] class EndpointWriter( def sendBufferedMessages(): Unit = { def delegate(msg: Any): Boolean = msg match { - case s: Send ⇒ + case s: Send => writeSend(s) - case FlushAndStop ⇒ + case FlushAndStop => flushAndStop() false - case s @ StopReading(_, replyTo) ⇒ + case s @ StopReading(_, replyTo) => reader.foreach(_.tell(s, replyTo)) true } @@ -764,7 +764,7 @@ private[remote] class EndpointWriter( } val writing: Receive = { - case s: Send ⇒ + case s: Send => if (!writeSend(s)) { enqueueInBuffer(s) scheduleBackoffTimer() @@ -772,16 +772,16 @@ private[remote] class EndpointWriter( } // We are in Writing state, so buffer is empty, safe to stop here - case FlushAndStop ⇒ + case FlushAndStop => flushAndStop() - case AckIdleCheckTimer if ackDeadline.isOverdue() ⇒ + case AckIdleCheckTimer if ackDeadline.isOverdue() => trySendPureAck() } def writeSend(s: Send): Boolean = try { handle match { - case Some(h) ⇒ + case Some(h) => if (provider.remoteSettings.LogSend && log.isDebugEnabled) { def msgLog = s"RemoteMessage: [${s.message}] to [${s.recipient}]<+[${s.recipient.path}] from [${s.senderOption.getOrElse(extendedSystem.deadLetters)}]" log.debug("sending message {}", msgLog) @@ -811,34 +811,34 @@ private[remote] class EndpointWriter( ok } - case None ⇒ + case None => throw new EndpointException("Internal error: Endpoint is in state Writing, but no association handle is present.") } } catch { - case e: NotSerializableException ⇒ + case e: NotSerializableException => log.error(e, "Serializer not defined for message type [{}]. Transient association error (association remains live)", s.message.getClass) true - case e: IllegalArgumentException ⇒ + case e: IllegalArgumentException => log.error(e, "Serializer not defined for message type [{}]. Transient association error (association remains live)", s.message.getClass) true - case e: MessageSerializer.SerializationException ⇒ + case e: MessageSerializer.SerializationException => log.error(e, "{} Transient association error (association remains live)", e.getMessage) true - case e: EndpointException ⇒ + case e: EndpointException => publishAndThrow(e, Logging.ErrorLevel) - case NonFatal(e) ⇒ + case NonFatal(e) => publishAndThrow(new EndpointException("Failed to write message to the transport", e), Logging.ErrorLevel) } def handoff: Receive = { - case Terminated(_) ⇒ + case Terminated(_) => reader = startReadEndpoint(handle.get) becomeWritingOrSendBufferedMessages() - case s: Send ⇒ + case s: Send => enqueueInBuffer(s) - case OutboundAck(_) ⇒ + case OutboundAck(_) => // Ignore outgoing acks during take over, since we might have // replaced the handle with a connection to a new, restarted, system // and the ack might be targeted to the old incarnation. @@ -846,33 +846,33 @@ private[remote] class EndpointWriter( } override def unhandled(message: Any): Unit = message match { - case Terminated(r) if r == reader.orNull ⇒ + case Terminated(r) if r == reader.orNull => publishAndThrow(new EndpointDisassociatedException("Disassociated"), Logging.DebugLevel) - case s @ StopReading(_, replyTo) ⇒ + case s @ StopReading(_, replyTo) => reader match { - case Some(r) ⇒ + case Some(r) => r.tell(s, replyTo) - case None ⇒ + case None => // initializing, buffer and take care of it later when buffer is sent enqueueInBuffer(s) } - case TakeOver(newHandle, replyTo) ⇒ + case TakeOver(newHandle, replyTo) => // Shutdown old reader handle foreach { _.disassociate("the association was replaced by a new one", log) } handle = Some(newHandle) replyTo ! TookOver(self, newHandle) context.become(handoff) - case FlushAndStop ⇒ + case FlushAndStop => stopReason = AssociationHandle.Shutdown context.stop(self) - case OutboundAck(ack) ⇒ + case OutboundAck(ack) => lastAck = Some(ack) if (ackDeadline.isOverdue()) trySendPureAck() - case AckIdleCheckTimer ⇒ // Ignore - case FlushAndStopTimeout ⇒ // ignore - case BackoffTimer ⇒ // ignore - case other ⇒ super.unhandled(other) + case AckIdleCheckTimer => // Ignore + case FlushAndStopTimeout => // ignore + case BackoffTimer => // ignore + case other => super.unhandled(other) } def flushAndStop(): Unit = { @@ -883,7 +883,7 @@ private[remote] class EndpointWriter( } private def trySendPureAck(): Unit = - for (h ← handle; ack ← lastAck) { + for (h <- handle; ack <- lastAck) { if (h.write(codec.constructPureAck(ack))) { ackDeadline = newAckDeadline lastAck = None @@ -901,11 +901,11 @@ private[remote] class EndpointWriter( } private def serializeMessage(msg: Any): SerializedMessage = handle match { - case Some(h) ⇒ + case Some(h) => Serialization.currentTransportInformation.withValue(Serialization.Information(h.localAddress, extendedSystem)) { MessageSerializer.serialize(extendedSystem, msg.asInstanceOf[AnyRef]) } - case None ⇒ + case None => throw new EndpointException("Internal error: No handle was present during serialization of outbound message.") } @@ -954,11 +954,11 @@ private[remote] class EndpointReader( override def preStart(): Unit = { receiveBuffers.get(Link(localAddress, remoteAddress)) match { - case null ⇒ - case ResendState(`uid`, buffer) ⇒ + case null => + case ResendState(`uid`, buffer) => ackedReceiveBuffer = buffer deliverAndAck() - case _ ⇒ + case _ => } } @@ -983,35 +983,35 @@ private[remote] class EndpointReader( } override def receive: Receive = { - case Disassociated(info) ⇒ handleDisassociated(info) + case Disassociated(info) => handleDisassociated(info) - case InboundPayload(p) if p.size <= transport.maximumPayloadBytes ⇒ + case InboundPayload(p) if p.size <= transport.maximumPayloadBytes => val (ackOption, msgOption) = tryDecodeMessageAndAck(p) - for (ack ← ackOption; reliableDelivery ← reliableDeliverySupervisor) reliableDelivery ! ack + for (ack <- ackOption; reliableDelivery <- reliableDeliverySupervisor) reliableDelivery ! ack msgOption match { - case Some(msg) ⇒ + case Some(msg) => if (msg.reliableDeliveryEnabled) { ackedReceiveBuffer = ackedReceiveBuffer.receive(msg) deliverAndAck() } else try msgDispatch.dispatch(msg.recipient, msg.recipientAddress, msg.serializedMessage, msg.senderOption) catch { - case e: NotSerializableException ⇒ logTransientSerializationError(msg, e) - case e: IllegalArgumentException ⇒ logTransientSerializationError(msg, e) + case e: NotSerializableException => logTransientSerializationError(msg, e) + case e: IllegalArgumentException => logTransientSerializationError(msg, e) } - case None ⇒ + case None => } - case InboundPayload(oversized) ⇒ + case InboundPayload(oversized) => log.error( new OversizedPayloadException(s"Discarding oversized payload received: " + s"max allowed size [${transport.maximumPayloadBytes}] bytes, actual size [${oversized.size}] bytes."), "Transient error while reading from association (association remains live)") - case StopReading(writer, replyTo) ⇒ + case StopReading(writer, replyTo) => saveState() context.become(notReading) replyTo ! StoppedReading(writer) @@ -1029,38 +1029,38 @@ private[remote] class EndpointReader( } def notReading: Receive = { - case Disassociated(info) ⇒ handleDisassociated(info) + case Disassociated(info) => handleDisassociated(info) - case StopReading(writer, replyTo) ⇒ + case StopReading(writer, replyTo) => replyTo ! StoppedReading(writer) - case InboundPayload(p) if p.size <= transport.maximumPayloadBytes ⇒ + case InboundPayload(p) if p.size <= transport.maximumPayloadBytes => val (ackOption, msgOption) = tryDecodeMessageAndAck(p) - for (ack ← ackOption; reliableDelivery ← reliableDeliverySupervisor) reliableDelivery ! ack + for (ack <- ackOption; reliableDelivery <- reliableDeliverySupervisor) reliableDelivery ! ack if (log.isWarningEnabled) log.warning("Discarding inbound message to [{}] in read-only association to [{}]. " + "If this happens often you may consider using akka.remote.use-passive-connections=off " + "or use Artery TCP.", msgOption.map(_.recipient).getOrElse("unknown"), remoteAddress) - case InboundPayload(oversized) ⇒ + case InboundPayload(oversized) => log.error( new OversizedPayloadException(s"Discarding oversized payload received in read-only association: " + s"max allowed size [${transport.maximumPayloadBytes}] bytes, actual size [${oversized.size}] bytes."), "Transient error while reading from association (association remains live)") - case _ ⇒ + case _ => } private def handleDisassociated(info: DisassociateInfo): Unit = info match { - case AssociationHandle.Unknown ⇒ + case AssociationHandle.Unknown => context.stop(self) - case AssociationHandle.Shutdown ⇒ + case AssociationHandle.Shutdown => throw ShutDownAssociation( localAddress, remoteAddress, InvalidAssociationException("The remote system terminated the association because it is shutting down.")) - case AssociationHandle.Quarantined ⇒ + case AssociationHandle.Quarantined => throw InvalidAssociation( localAddress, remoteAddress, @@ -1075,7 +1075,7 @@ private[remote] class EndpointReader( // Notify writer that some messages can be acked context.parent ! OutboundAck(ack) - deliver foreach { m ⇒ + deliver foreach { m => msgDispatch.dispatch(m.recipient, m.recipientAddress, m.serializedMessage, m.senderOption) } } @@ -1083,6 +1083,6 @@ private[remote] class EndpointReader( private def tryDecodeMessageAndAck(pdu: ByteString): (Option[Ack], Option[Message]) = try { codec.decodeMessage(pdu, provider, localAddress) } catch { - case NonFatal(e) ⇒ throw new EndpointException("Error while decoding incoming Akka PDU", e) + case NonFatal(e) => throw new EndpointException("Error while decoding incoming Akka PDU", e) } } diff --git a/akka-remote/src/main/scala/akka/remote/FailureDetector.scala b/akka-remote/src/main/scala/akka/remote/FailureDetector.scala index fb2ae141c3..d50109e333 100644 --- a/akka-remote/src/main/scala/akka/remote/FailureDetector.scala +++ b/akka-remote/src/main/scala/akka/remote/FailureDetector.scala @@ -38,7 +38,7 @@ object FailureDetector { * time and is not related to any other notion of system or wall-clock time. */ // Abstract class to be able to extend it from Java - abstract class Clock extends (() ⇒ Long) + abstract class Clock extends (() => Long) implicit val defaultClock = new Clock { def apply() = NANOSECONDS.toMillis(System.nanoTime) diff --git a/akka-remote/src/main/scala/akka/remote/FailureDetectorRegistry.scala b/akka-remote/src/main/scala/akka/remote/FailureDetectorRegistry.scala index 84af6e369a..f8ecca7969 100644 --- a/akka-remote/src/main/scala/akka/remote/FailureDetectorRegistry.scala +++ b/akka-remote/src/main/scala/akka/remote/FailureDetectorRegistry.scala @@ -67,9 +67,9 @@ private[akka] object FailureDetectorLoader { def load(fqcn: String, config: Config, system: ActorSystem): FailureDetector = { system.asInstanceOf[ExtendedActorSystem].dynamicAccess.createInstanceFor[FailureDetector]( fqcn, List( - classOf[Config] → config, - classOf[EventStream] → system.eventStream)).recover({ - case e ⇒ throw new ConfigurationException( + classOf[Config] -> config, + classOf[EventStream] -> system.eventStream)).recover({ + case e => throw new ConfigurationException( s"Could not create custom failure detector [$fqcn] due to: ${e.toString}", e) }).get } diff --git a/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala b/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala index 2873021d05..a9b81d9a62 100644 --- a/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala +++ b/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala @@ -58,7 +58,7 @@ private[akka] object MessageSerializer { builder.build } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => throw new SerializationException(s"Failed to serialize remote message [${message.getClass}] " + s"using serializer [${serializer.getClass}].", e) } finally Serialization.currentTransportInformation.value = oldInfo @@ -77,8 +77,8 @@ private[akka] object MessageSerializer { envelope.writeHeader(headerBuilder, outboundEnvelope) serializer match { - case ser: ByteBufferSerializer ⇒ ser.toBinary(message, envelope.byteBuffer) - case _ ⇒ envelope.byteBuffer.put(serializer.toBinary(message)) + case ser: ByteBufferSerializer => ser.toBinary(message, envelope.byteBuffer) + case _ => envelope.byteBuffer.put(serializer.toBinary(message)) } } finally Serialization.currentTransportInformation.value = oldInfo diff --git a/akka-remote/src/main/scala/akka/remote/PhiAccrualFailureDetector.scala b/akka-remote/src/main/scala/akka/remote/PhiAccrualFailureDetector.scala index df31321e31..ad8efcf1c2 100644 --- a/akka-remote/src/main/scala/akka/remote/PhiAccrualFailureDetector.scala +++ b/akka-remote/src/main/scala/akka/remote/PhiAccrualFailureDetector.scala @@ -128,11 +128,11 @@ class PhiAccrualFailureDetector( val oldState = state.get val newHistory = oldState.timestamp match { - case None ⇒ + case None => // this is heartbeat from a new resource // add starter records for this new resource firstHeartbeat - case Some(latestTimestamp) ⇒ + case Some(latestTimestamp) => // this is a known connection val interval = timestamp - latestTimestamp // don't use the first heartbeat after failure for the history, since a long pause will skew the stats diff --git a/akka-remote/src/main/scala/akka/remote/RemoteActorRefProvider.scala b/akka-remote/src/main/scala/akka/remote/RemoteActorRefProvider.scala index 99d5471310..247035560e 100644 --- a/akka-remote/src/main/scala/akka/remote/RemoteActorRefProvider.scala +++ b/akka-remote/src/main/scala/akka/remote/RemoteActorRefProvider.scala @@ -51,13 +51,13 @@ private[akka] object RemoteActorRefProvider { startWith(Uninitialized, None) when(Uninitialized) { - case Event(i: Internals, _) ⇒ + case Event(i: Internals, _) => systemGuardian ! RegisterTerminationHook goto(Idle) using Some(i) } when(Idle) { - case Event(TerminationHook, Some(internals)) ⇒ + case Event(TerminationHook, Some(internals)) => log.info("Shutting down remote daemon.") internals.remoteDaemon ! TerminationHook goto(WaitDaemonShutdown) @@ -65,19 +65,19 @@ private[akka] object RemoteActorRefProvider { // TODO: state timeout when(WaitDaemonShutdown) { - case Event(TerminationHookDone, Some(internals)) ⇒ + case Event(TerminationHookDone, Some(internals)) => log.info("Remote daemon shut down; proceeding with flushing remote transports.") internals.transport.shutdown() pipeTo self goto(WaitTransportShutdown) } when(WaitTransportShutdown) { - case Event(Done, _) ⇒ + case Event(Done, _) => log.info("Remoting shut down.") systemGuardian ! TerminationHookDone stop() - case Event(Status.Failure(ex), _) ⇒ + case Event(Status.Failure(ex), _) => log.error(ex, "Remoting shut down with error") systemGuardian ! TerminationHookDone stop() @@ -98,26 +98,26 @@ private[akka] object RemoteActorRefProvider { import EndpointManager.Send override def !(message: Any)(implicit sender: ActorRef): Unit = message match { - case Send(m, senderOption, recipient, seqOpt) ⇒ + case Send(m, senderOption, recipient, seqOpt) => // else ignore: it is a reliably delivered message that might be retried later, and it has not yet deserved // the dead letter status if (seqOpt.isEmpty) super.!(DeadLetter(m, senderOption.getOrElse(_provider.deadLetters), recipient)) - case DeadLetter(Send(m, senderOption, recipient, seqOpt), _, _) ⇒ + case DeadLetter(Send(m, senderOption, recipient, seqOpt), _, _) => // else ignore: it is a reliably delivered message that might be retried later, and it has not yet deserved // the dead letter status if (seqOpt.isEmpty) super.!(DeadLetter(m, senderOption.getOrElse(_provider.deadLetters), recipient)) - case env: OutboundEnvelope ⇒ + case env: OutboundEnvelope => super.!(DeadLetter(unwrapSystemMessageEnvelope(env.message), env.sender.getOrElse(_provider.deadLetters), env.recipient.getOrElse(_provider.deadLetters))) - case DeadLetter(env: OutboundEnvelope, _, _) ⇒ + case DeadLetter(env: OutboundEnvelope, _, _) => super.!(DeadLetter(unwrapSystemMessageEnvelope(env.message), env.sender.getOrElse(_provider.deadLetters), env.recipient.getOrElse(_provider.deadLetters))) - case _ ⇒ super.!(message)(sender) + case _ => super.!(message)(sender) } private def unwrapSystemMessageEnvelope(msg: AnyRef): AnyRef = msg match { - case SystemMessageEnvelope(m, _, _) ⇒ m - case _ ⇒ msg + case SystemMessageEnvelope(m, _, _) => m + case _ => msg } @throws(classOf[java.io.ObjectStreamException]) @@ -150,7 +150,7 @@ private[akka] class RemoteActorRefProvider( protected def createDeployer: RemoteDeployer = new RemoteDeployer(settings, dynamicAccess) private val local = new LocalActorRefProvider(systemName, settings, eventStream, dynamicAccess, deployer, - Some(deadLettersPath ⇒ new RemoteDeadLetterActorRef(this, deadLettersPath, eventStream))) + Some(deadLettersPath => new RemoteDeadLetterActorRef(this, deadLettersPath, eventStream))) @volatile private var _log = local.log @@ -207,9 +207,9 @@ private[akka] class RemoteActorRefProvider( }, transport = if (remoteSettings.Artery.Enabled) remoteSettings.Artery.Transport match { - case ArterySettings.AeronUpd ⇒ new ArteryAeronUdpTransport(system, this) - case ArterySettings.Tcp ⇒ new ArteryTcpTransport(system, this, tlsEnabled = false) - case ArterySettings.TlsTcp ⇒ new ArteryTcpTransport(system, this, tlsEnabled = true) + case ArterySettings.AeronUpd => new ArteryAeronUdpTransport(system, this) + case ArterySettings.Tcp => new ArteryTcpTransport(system, this, tlsEnabled = false) + case ArterySettings.TlsTcp => new ArteryTcpTransport(system, this, tlsEnabled = true) } else new Remoting(system, this)) @@ -242,7 +242,7 @@ private[akka] class RemoteActorRefProvider( def createFailureDetector(): FailureDetector = FailureDetectorLoader.load(remoteSettings.WatchFailureDetectorImplementationClass, remoteSettings.WatchFailureDetectorConfig, system) - new DefaultFailureDetectorRegistry(() ⇒ createFailureDetector()) + new DefaultFailureDetectorRegistry(() => createFailureDetector()) } protected def createRemoteDeploymentWatcher(system: ActorSystemImpl): ActorRef = @@ -284,10 +284,10 @@ private[akka] class RemoteActorRefProvider( @scala.annotation.tailrec def lookupRemotes(p: Iterable[String]): Option[Deploy] = { p.headOption match { - case None ⇒ None - case Some("remote") ⇒ lookupRemotes(p.drop(3)) - case Some("user") ⇒ deployer.lookup(p.drop(1)) - case Some(_) ⇒ None + case None => None + case Some("remote") => lookupRemotes(p.drop(3)) + case Some("user") => deployer.lookup(p.drop(1)) + case Some(_) => None } } @@ -295,21 +295,21 @@ private[akka] class RemoteActorRefProvider( val lookup = if (lookupDeploy) elems.head match { - case "user" | "system" ⇒ deployer.lookup(elems.drop(1)) - case "remote" ⇒ lookupRemotes(elems) - case _ ⇒ None + case "user" | "system" => deployer.lookup(elems.drop(1)) + case "remote" => lookupRemotes(elems) + case _ => None } else None val deployment = { deploy.toList ::: lookup.toList match { - case Nil ⇒ Nil - case l ⇒ List(l reduce ((a, b) ⇒ b withFallback a)) + case Nil => Nil + case l => List(l reduce ((a, b) => b withFallback a)) } } - Iterator(props.deploy) ++ deployment.iterator reduce ((a, b) ⇒ b withFallback a) match { - case d @ Deploy(_, _, _, RemoteScope(address), _, _) ⇒ + Iterator(props.deploy) ++ deployment.iterator reduce ((a, b) => b withFallback a) match { + case d @ Deploy(_, _, _, RemoteScope(address), _, _) => if (hasAddress(address)) { local.actorOf(system, props, supervisor, path, false, deployment.headOption, false, async) } else if (props.deploy.scope == LocalScope) { @@ -320,7 +320,7 @@ private[akka] class RemoteActorRefProvider( val dispatcher = system.dispatchers.lookup(props.dispatcher) system.mailboxes.getMailboxType(props, dispatcher.configurator.config) } catch { - case NonFatal(e) ⇒ throw new ConfigurationException( + case NonFatal(e) => throw new ConfigurationException( s"configuration problem while creating [$path] with dispatcher [${props.dispatcher}] and mailbox [${props.mailbox}]", e) } val localAddress = transport.localAddressForRemote(address) @@ -328,10 +328,10 @@ private[akka] class RemoteActorRefProvider( withUid(path.uid) new RemoteActorRef(transport, localAddress, rpath, supervisor, Some(props), Some(d)) } catch { - case NonFatal(e) ⇒ throw new IllegalArgumentException(s"remote deployment failed for [$path]", e) + case NonFatal(e) => throw new IllegalArgumentException(s"remote deployment failed for [$path]", e) } - case _ ⇒ + case _ => local.actorOf(system, props, supervisor, path, systemService, deployment.headOption, false, async) } } @@ -343,7 +343,7 @@ private[akka] class RemoteActorRefProvider( new RemoteActorRef(transport, transport.localAddressForRemote(path.address), path, Nobody, props = None, deploy = None) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "Error while looking up address [{}]", path.address) new EmptyLocalActorRef(this, path, eventStream) } @@ -351,7 +351,7 @@ private[akka] class RemoteActorRefProvider( @deprecated("use actorSelection instead of actorFor", "2.2") override private[akka] def actorFor(ref: InternalActorRef, path: String): InternalActorRef = path match { - case ActorPathExtractor(address, elems) ⇒ + case ActorPathExtractor(address, elems) => if (hasAddress(address)) actorFor(rootGuardian, elems) else { val rootPath = RootActorPath(address) / elems @@ -359,12 +359,12 @@ private[akka] class RemoteActorRefProvider( new RemoteActorRef(transport, transport.localAddressForRemote(address), rootPath, Nobody, props = None, deploy = None) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "Error while looking up address [{}]", rootPath.address) new EmptyLocalActorRef(this, rootPath, eventStream) } } - case _ ⇒ local.actorFor(ref, path) + case _ => local.actorFor(ref, path) } @deprecated("use actorSelection instead of actorFor", "2.2") @@ -377,7 +377,7 @@ private[akka] class RemoteActorRefProvider( new RemoteActorRef(transport, transport.localAddressForRemote(address), RootActorPath(address), Nobody, props = None, deploy = None) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "No root guardian at [{}]", address) new EmptyLocalActorRef(this, RootActorPath(address), eventStream) } @@ -389,17 +389,17 @@ private[akka] class RemoteActorRefProvider( */ private[akka] def resolveActorRefWithLocalAddress(path: String, localAddress: Address): InternalActorRef = { path match { - case ActorPathExtractor(address, elems) ⇒ + case ActorPathExtractor(address, elems) => if (hasAddress(address)) local.resolveActorRef(rootGuardian, elems) else try { new RemoteActorRef(transport, localAddress, RootActorPath(address) / elems, Nobody, props = None, deploy = None) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning("Error while resolving ActorRef [{}] due to [{}]", path, e.getMessage) new EmptyLocalActorRef(this, RootActorPath(address) / elems, eventStream) } - case _ ⇒ + case _ => log.debug("Resolve (deserialization) of unknown (invalid) path [{}], using deadLetters.", path) deadLetters } @@ -409,8 +409,8 @@ private[akka] class RemoteActorRefProvider( // using thread local LRU cache, which will call internalRresolveActorRef // if the value is not cached actorRefResolveThreadLocalCache match { - case null ⇒ internalResolveActorRef(path) // not initialized yet - case c ⇒ c.threadLocalCache(this).getOrCompute(path) + case null => internalResolveActorRef(path) // not initialized yet + case c => c.threadLocalCache(this).getOrCompute(path) } } @@ -419,7 +419,7 @@ private[akka] class RemoteActorRefProvider( * public `resolveActorRef(path: String)`. */ private[akka] def internalResolveActorRef(path: String): ActorRef = path match { - case ActorPathExtractor(address, elems) ⇒ + case ActorPathExtractor(address, elems) => if (hasAddress(address)) local.resolveActorRef(rootGuardian, elems) else { val rootPath = RootActorPath(address) / elems @@ -427,12 +427,12 @@ private[akka] class RemoteActorRefProvider( new RemoteActorRef(transport, transport.localAddressForRemote(address), rootPath, Nobody, props = None, deploy = None) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning("Error while resolving ActorRef [{}] due to [{}]", path, e.getMessage) new EmptyLocalActorRef(this, rootPath, eventStream) } } - case _ ⇒ + case _ => log.debug("Resolve (deserialization) of unknown (invalid) path [{}], using deadLetters.", path) deadLetters } @@ -443,7 +443,7 @@ private[akka] class RemoteActorRefProvider( new RemoteActorRef(transport, transport.localAddressForRemote(path.address), path, Nobody, props = None, deploy = None) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning("Error while resolving ActorRef [{}] due to [{}]", path, e.getMessage) new EmptyLocalActorRef(this, path, eventStream) } @@ -466,9 +466,9 @@ private[akka] class RemoteActorRefProvider( def getExternalAddressFor(addr: Address): Option[Address] = { addr match { - case _ if hasAddress(addr) ⇒ Some(local.rootPath.address) - case Address(_, _, Some(_), Some(_)) ⇒ try Some(transport.localAddressForRemote(addr)) catch { case NonFatal(_) ⇒ None } - case _ ⇒ None + case _ if hasAddress(addr) => Some(local.rootPath.address) + case Address(_, _, Some(_), Some(_)) => try Some(transport.localAddressForRemote(addr)) catch { case NonFatal(_) => None } + case _ => None } } @@ -478,8 +478,8 @@ private[akka] class RemoteActorRefProvider( private var serializationInformationCache: OptionVal[Serialization.Information] = OptionVal.None @InternalApi override private[akka] def serializationInformation: Serialization.Information = serializationInformationCache match { - case OptionVal.Some(info) ⇒ info - case OptionVal.None ⇒ + case OptionVal.Some(info) => info + case OptionVal.None => if ((transport eq null) || (transport.defaultAddress eq null)) local.serializationInformation // address not know yet, access before complete init and binding else { @@ -526,12 +526,12 @@ private[akka] class RemoteActorRef private[akka] ( throw new IllegalArgumentException(s"Unexpected local address in RemoteActorRef [$this]") remote match { - case t: ArteryTransport ⇒ + case t: ArteryTransport => // detect mistakes such as using "akka.tcp" with Artery if (path.address.protocol != t.localAddress.address.protocol) throw new IllegalArgumentException( s"Wrong protocol of [${path}], expected [${t.localAddress.address.protocol}]") - case _ ⇒ + case _ => } @volatile private[remote] var cachedAssociation: artery.Association = null @@ -541,9 +541,9 @@ private[akka] class RemoteActorRef private[akka] ( def getChild(name: Iterator[String]): InternalActorRef = { val s = name.toStream s.headOption match { - case None ⇒ this - case Some("..") ⇒ getParent getChild name - case _ ⇒ new RemoteActorRef(remote, localAddressToUse, path / s, Nobody, props = None, deploy = None) + case None => this + case Some("..") => getParent getChild name + case _ => new RemoteActorRef(remote, localAddressToUse, path / s, Nobody, props = None, deploy = None) } } @@ -551,11 +551,11 @@ private[akka] class RemoteActorRef private[akka] ( override private[akka] def isTerminated: Boolean = false private def handleException(message: Any, sender: ActorRef): Catcher[Unit] = { - case e: InterruptedException ⇒ + case e: InterruptedException => remote.system.eventStream.publish(Error(e, path.toString, getClass, "interrupted during message send")) remote.system.deadLetters.tell(message, sender) Thread.currentThread.interrupt() - case NonFatal(e) ⇒ + case NonFatal(e) => remote.system.eventStream.publish(Error(e, path.toString, getClass, "swallowing exception during message send")) remote.system.deadLetters.tell(message, sender) } @@ -577,12 +577,12 @@ private[akka] class RemoteActorRef private[akka] ( try { //send to remote, unless watch message is intercepted by the remoteWatcher message match { - case Watch(watchee, watcher) if isWatchIntercepted(watchee, watcher) ⇒ + case Watch(watchee, watcher) if isWatchIntercepted(watchee, watcher) => provider.remoteWatcher ! RemoteWatcher.WatchRemote(watchee, watcher) //Unwatch has a different signature, need to pattern match arguments against InternalActorRef - case Unwatch(watchee: InternalActorRef, watcher: InternalActorRef) if isWatchIntercepted(watchee, watcher) ⇒ + case Unwatch(watchee: InternalActorRef, watcher: InternalActorRef) if isWatchIntercepted(watchee, watcher) => provider.remoteWatcher ! RemoteWatcher.UnwatchRemote(watchee, watcher) - case _ ⇒ remote.send(message, OptionVal.None, this) + case _ => remote.send(message, OptionVal.None, this) } } catch handleException(message, Actor.noSender) diff --git a/akka-remote/src/main/scala/akka/remote/RemoteDaemon.scala b/akka-remote/src/main/scala/akka/remote/RemoteDaemon.scala index 2c6287b75a..50d847cdc4 100644 --- a/akka-remote/src/main/scala/akka/remote/RemoteDaemon.scala +++ b/akka-remote/src/main/scala/akka/remote/RemoteDaemon.scala @@ -68,18 +68,18 @@ private[akka] class RemoteSystemDaemon( @tailrec private def addChildParentNeedsWatch(parent: ActorRef, child: ActorRef): Boolean = parent2children.get(parent) match { - case null ⇒ + case null => if (parent2children.putIfAbsent(parent, Set(child)) == null) true else addChildParentNeedsWatch(parent, child) - case children ⇒ + case children => if (parent2children.replace(parent, children, children + child)) false else addChildParentNeedsWatch(parent, child) } @tailrec private def removeChildParentNeedsUnwatch(parent: ActorRef, child: ActorRef): Boolean = { parent2children.get(parent) match { - case null ⇒ false // no-op - case children ⇒ + case null => false // no-op + case children => val next = children - child if (next.isEmpty) { if (!parent2children.remove(parent, children)) removeChildParentNeedsUnwatch(parent, child) @@ -102,54 +102,54 @@ private[akka] class RemoteSystemDaemon( import akka.actor.ActorCell._ val (childName, uid) = splitNameAndUid(s) getChild(childName) match { - case null ⇒ + case null => val last = s.lastIndexOf('/') if (last == -1) (Nobody, n) else rec(s.substring(0, last), n + 1) - case ref if uid != undefinedUid && uid != ref.path.uid ⇒ (Nobody, n) - case ref ⇒ (ref, n) + case ref if uid != undefinedUid && uid != ref.path.uid => (Nobody, n) + case ref => (ref, n) } } val full = Vector() ++ names rec(full.mkString("/"), 0) match { - case (Nobody, _) ⇒ Nobody - case (ref, 0) ⇒ ref - case (ref, n) ⇒ ref.getChild(full.takeRight(n).iterator) + case (Nobody, _) => Nobody + case (ref, 0) => ref + case (ref, n) => ref.getChild(full.takeRight(n).iterator) } } override def sendSystemMessage(message: SystemMessage): Unit = message match { - case DeathWatchNotification(child: ActorRefWithCell with ActorRefScope, _, _) if child.isLocal ⇒ + case DeathWatchNotification(child: ActorRefWithCell with ActorRefScope, _, _) if child.isLocal => terminating.locked { removeChild(child.path.elements.drop(1).mkString("/"), child) val parent = child.getParent if (removeChildParentNeedsUnwatch(parent, child)) parent.sendSystemMessage(Unwatch(parent, this)) terminationHookDoneWhenNoChildren() } - case DeathWatchNotification(parent: ActorRef with ActorRefScope, _, _) if !parent.isLocal ⇒ + case DeathWatchNotification(parent: ActorRef with ActorRefScope, _, _) if !parent.isLocal => terminating.locked { parent2children.remove(parent) match { - case null ⇒ - case children ⇒ - for (c ← children) { + case null => + case children => + for (c <- children) { system.stop(c) removeChild(c.path.elements.drop(1).mkString("/"), c) } terminationHookDoneWhenNoChildren() } } - case _ ⇒ super.sendSystemMessage(message) + case _ => super.sendSystemMessage(message) } override def !(msg: Any)(implicit sender: ActorRef = Actor.noSender): Unit = try msg match { - case message: DaemonMsg ⇒ + case message: DaemonMsg => log.debug("Received command [{}] to RemoteSystemDaemon on [{}]", message, path.address) message match { - case DaemonMsgCreate(_, _, path, _) if untrustedMode ⇒ + case DaemonMsgCreate(_, _, path, _) if untrustedMode => log.debug("does not accept deployments (untrusted) for [{}]", path) // TODO add security marker? - case DaemonMsgCreate(props, deploy, path, supervisor) if whitelistEnabled ⇒ + case DaemonMsgCreate(props, deploy, path, supervisor) if whitelistEnabled => val name = props.clazz.getCanonicalName if (remoteDeploymentWhitelist.contains(name)) doCreateActor(message, props, deploy, path, supervisor) @@ -159,11 +159,11 @@ private[akka] class RemoteSystemDaemon( "Received command to create remote Actor, but class [{}] is not white-listed! " + "Target path: [{}]", props.actorClass, path) } - case DaemonMsgCreate(props, deploy, path, supervisor) ⇒ + case DaemonMsgCreate(props, deploy, path, supervisor) => doCreateActor(message, props, deploy, path, supervisor) } - case sel: ActorSelectionMessage ⇒ + case sel: ActorSelectionMessage => val (concatenatedChildNames, m) = { val iter = sel.elements.iterator // find child elements, and the message to send, which is a remaining ActorSelectionMessage @@ -173,46 +173,46 @@ private[akka] class RemoteSystemDaemon( (acc.reverse, sel.msg) else { iter.next() match { - case SelectChildName(name) ⇒ rec(name :: acc) - case SelectParent if acc.isEmpty ⇒ rec(acc) - case SelectParent ⇒ rec(acc.tail) - case pat: SelectChildPattern ⇒ (acc.reverse, sel.copy(elements = pat +: iter.toVector)) + case SelectChildName(name) => rec(name :: acc) + case SelectParent if acc.isEmpty => rec(acc) + case SelectParent => rec(acc.tail) + case pat: SelectChildPattern => (acc.reverse, sel.copy(elements = pat +: iter.toVector)) } } rec(Nil) } getChild(concatenatedChildNames.iterator) match { - case Nobody ⇒ + case Nobody => val emptyRef = new EmptyLocalActorRef(system.provider, path / sel.elements.map(_.toString), system.eventStream) emptyRef.tell(sel, sender) - case child ⇒ + case child => child.tell(m, sender) } - case Identify(messageId) ⇒ sender ! ActorIdentity(messageId, Some(this)) + case Identify(messageId) => sender ! ActorIdentity(messageId, Some(this)) - case TerminationHook ⇒ + case TerminationHook => terminating.switchOn { terminationHookDoneWhenNoChildren() foreachChild { system.stop } } - case AddressTerminated(address) ⇒ + case AddressTerminated(address) => foreachChild { - case a: InternalActorRef if a.getParent.path.address == address ⇒ system.stop(a) - case _ ⇒ // skip, this child doesn't belong to the terminated address + case a: InternalActorRef if a.getParent.path.address == address => system.stop(a) + case _ => // skip, this child doesn't belong to the terminated address } - case unknown ⇒ log.warning(LogMarker.Security, "Unknown message [{}] received by [{}]", unknown, this) + case unknown => log.warning(LogMarker.Security, "Unknown message [{}] received by [{}]", unknown, this) } catch { - case NonFatal(e) ⇒ log.error(e, "exception while processing remote command [{}] from [{}]", msg, sender) + case NonFatal(e) => log.error(e, "exception while processing remote command [{}] from [{}]", msg, sender) } private def doCreateActor(message: DaemonMsg, props: Props, deploy: Deploy, path: String, supervisor: ActorRef) = { path match { - case ActorPathExtractor(_, elems) if elems.nonEmpty && elems.head == "remote" ⇒ + case ActorPathExtractor(_, elems) if elems.nonEmpty && elems.head == "remote" => // TODO RK currently the extracted “address” is just ignored, is that okay? // TODO RK canonicalize path so as not to duplicate it always #1446 val subpath = elems.drop(1) @@ -233,7 +233,7 @@ private[akka] class RemoteSystemDaemon( if (addChildParentNeedsWatch(parent, actor)) parent.sendSystemMessage(Watch(parent, this)) } if (isTerminating) log.error("Skipping [{}] to RemoteSystemDaemon on [{}] while terminating", message, p.address) - case _ ⇒ + case _ => log.debug("remote path does not match path from message [{}]", message) } } diff --git a/akka-remote/src/main/scala/akka/remote/RemoteDeployer.scala b/akka-remote/src/main/scala/akka/remote/RemoteDeployer.scala index 7c4f3e7011..c1829311f6 100644 --- a/akka-remote/src/main/scala/akka/remote/RemoteDeployer.scala +++ b/akka-remote/src/main/scala/akka/remote/RemoteDeployer.scala @@ -25,19 +25,19 @@ private[akka] class RemoteDeployer(_settings: ActorSystem.Settings, _pm: Dynamic override def parseConfig(path: String, config: Config): Option[Deploy] = { super.parseConfig(path, config) match { - case d @ Some(deploy) ⇒ + case d @ Some(deploy) => deploy.config.getString("remote") match { - case AddressFromURIString(r) ⇒ Some(deploy.copy(scope = RemoteScope(r))) - case str if !str.isEmpty ⇒ throw new ConfigurationException(s"unparseable remote node name [${str}]") - case _ ⇒ + case AddressFromURIString(r) => Some(deploy.copy(scope = RemoteScope(r))) + case str if !str.isEmpty => throw new ConfigurationException(s"unparseable remote node name [${str}]") + case _ => val nodes = immutableSeq(deploy.config.getStringList("target.nodes")).map(AddressFromURIString(_)) if (nodes.isEmpty || deploy.routerConfig == NoRouter) d else deploy.routerConfig match { - case r: Pool ⇒ Some(deploy.copy(routerConfig = RemoteRouterConfig(r, nodes))) - case _ ⇒ d + case r: Pool => Some(deploy.copy(routerConfig = RemoteRouterConfig(r, nodes))) + case _ => d } } - case None ⇒ None + case None => None } } } diff --git a/akka-remote/src/main/scala/akka/remote/RemoteDeploymentWatcher.scala b/akka-remote/src/main/scala/akka/remote/RemoteDeploymentWatcher.scala index c5249c0ccd..764cc4ea85 100644 --- a/akka-remote/src/main/scala/akka/remote/RemoteDeploymentWatcher.scala +++ b/akka-remote/src/main/scala/akka/remote/RemoteDeploymentWatcher.scala @@ -29,16 +29,16 @@ private[akka] class RemoteDeploymentWatcher extends Actor with RequiresMessageQu var supervisors = Map.empty[ActorRef, InternalActorRef] def receive = { - case WatchRemote(a, supervisor: InternalActorRef) ⇒ - supervisors += (a → supervisor) + case WatchRemote(a, supervisor: InternalActorRef) => + supervisors += (a -> supervisor) context.watch(a) - case t @ Terminated(a) if supervisors isDefinedAt a ⇒ + case t @ Terminated(a) if supervisors isDefinedAt a => // send extra DeathWatchNotification to the supervisor so that it will remove the child supervisors(a).sendSystemMessage(DeathWatchNotification(a, existenceConfirmed = t.existenceConfirmed, addressTerminated = t.addressTerminated)) supervisors -= a - case _: Terminated ⇒ + case _: Terminated => } } diff --git a/akka-remote/src/main/scala/akka/remote/RemoteMetricsExtension.scala b/akka-remote/src/main/scala/akka/remote/RemoteMetricsExtension.scala index 7bf7247eeb..00ec176f1e 100644 --- a/akka-remote/src/main/scala/akka/remote/RemoteMetricsExtension.scala +++ b/akka-remote/src/main/scala/akka/remote/RemoteMetricsExtension.scala @@ -64,9 +64,9 @@ private[akka] class RemoteMetricsOn(system: ExtendedActorSystem) extends RemoteM override def logPayloadBytes(msg: Any, payloadBytes: Int): Unit = if (payloadBytes >= logFrameSizeExceeding) { val clazz = msg match { - case x: ActorSelectionMessage ⇒ x.msg.getClass - case x: RouterEnvelope ⇒ x.message.getClass - case _ ⇒ msg.getClass + case x: ActorSelectionMessage => x.msg.getClass + case x: RouterEnvelope => x.message.getClass + case _ => msg.getClass } // 10% threshold until next log diff --git a/akka-remote/src/main/scala/akka/remote/RemoteSettings.scala b/akka-remote/src/main/scala/akka/remote/RemoteSettings.scala index 7924f28341..b2dae862c1 100644 --- a/akka-remote/src/main/scala/akka/remote/RemoteSettings.scala +++ b/akka-remote/src/main/scala/akka/remote/RemoteSettings.scala @@ -37,10 +37,10 @@ final class RemoteSettings(val config: Config) { immutableSeq(getStringList("akka.remote.trusted-selection-paths")).toSet val RemoteLifecycleEventsLogLevel: LogLevel = toRootLowerCase(getString("akka.remote.log-remote-lifecycle-events")) match { - case "on" ⇒ Logging.DebugLevel - case other ⇒ Logging.levelFor(other) match { - case Some(level) ⇒ level - case None ⇒ throw new ConfigurationException("Logging level must be one of (on, off, debug, info, warning, error)") + case "on" => Logging.DebugLevel + case other => Logging.levelFor(other) match { + case Some(level) => level + case None => throw new ConfigurationException("Logging level must be one of (on, off, debug, info, warning, error)") } } @@ -73,8 +73,8 @@ final class RemoteSettings(val config: Config) { val LogBufferSizeExceeding: Int = { val key = "akka.remote.log-buffer-size-exceeding" config.getString(key).toLowerCase match { - case "off" | "false" ⇒ Int.MaxValue - case _ ⇒ config.getInt(key) + case "off" | "false" => Int.MaxValue + case _ => config.getInt(key) } } @@ -124,7 +124,7 @@ final class RemoteSettings(val config: Config) { WatchFailureDetectorConfig.getMillisDuration("expected-response-after") } requiring (_ > Duration.Zero, "watch-failure-detector.expected-response-after > 0") - val Transports: immutable.Seq[(String, immutable.Seq[String], Config)] = transportNames.map { name ⇒ + val Transports: immutable.Seq[(String, immutable.Seq[String], Config)] = transportNames.map { name => val transportConfig = transportConfigFor(name) ( transportConfig.getString("transport-class"), @@ -139,6 +139,6 @@ final class RemoteSettings(val config: Config) { private def transportConfigFor(transportName: String): Config = getConfig(transportName) private def configToMap(cfg: Config): Map[String, String] = - cfg.root.unwrapped.asScala.toMap.map { case (k, v) ⇒ (k, v.toString) } + cfg.root.unwrapped.asScala.toMap.map { case (k, v) => (k, v.toString) } } diff --git a/akka-remote/src/main/scala/akka/remote/RemoteWatcher.scala b/akka-remote/src/main/scala/akka/remote/RemoteWatcher.scala index d43232c59a..d3ae8a2e72 100644 --- a/akka-remote/src/main/scala/akka/remote/RemoteWatcher.scala +++ b/akka-remote/src/main/scala/akka/remote/RemoteWatcher.scala @@ -55,7 +55,7 @@ private[akka] object RemoteWatcher { val watchingAddresses: Set[Address]) { override def toString: String = { def formatWatchingRefs: String = - watchingRefs.map(x ⇒ x._2.path.name + " -> " + x._1.path.name).mkString("[", ", ", "]") + watchingRefs.map(x => x._2.path.name + " -> " + x._1.path.name).mkString("[", ", ", "]") def formatWatchingAddresses: String = watchingAddresses.mkString("[", ", ", "]") @@ -123,19 +123,19 @@ private[akka] class RemoteWatcher( } def receive = { - case HeartbeatTick ⇒ sendHeartbeat() - case Heartbeat | ArteryHeartbeat ⇒ receiveHeartbeat() - case HeartbeatRsp(uid) ⇒ receiveHeartbeatRsp(uid.toLong) - case ArteryHeartbeatRsp(uid) ⇒ receiveHeartbeatRsp(uid) - case ReapUnreachableTick ⇒ reapUnreachable() - case ExpectedFirstHeartbeat(from) ⇒ triggerFirstHeartbeat(from) - case WatchRemote(watchee, watcher) ⇒ addWatch(watchee, watcher) - case UnwatchRemote(watchee, watcher) ⇒ removeWatch(watchee, watcher) - case t @ Terminated(watchee: InternalActorRef) ⇒ terminated(watchee, t.existenceConfirmed, t.addressTerminated) + case HeartbeatTick => sendHeartbeat() + case Heartbeat | ArteryHeartbeat => receiveHeartbeat() + case HeartbeatRsp(uid) => receiveHeartbeatRsp(uid.toLong) + case ArteryHeartbeatRsp(uid) => receiveHeartbeatRsp(uid) + case ReapUnreachableTick => reapUnreachable() + case ExpectedFirstHeartbeat(from) => triggerFirstHeartbeat(from) + case WatchRemote(watchee, watcher) => addWatch(watchee, watcher) + case UnwatchRemote(watchee, watcher) => removeWatch(watchee, watcher) + case t @ Terminated(watchee: InternalActorRef) => terminated(watchee, t.existenceConfirmed, t.addressTerminated) // test purpose - case Stats ⇒ - val watchSet = watching.iterator.flatMap { case (wee, wers) ⇒ wers.map { wer ⇒ wee → wer } }.toSet[(ActorRef, ActorRef)] + case Stats => + val watchSet = watching.iterator.flatMap { case (wee, wers) => wers.map { wer => wee -> wer } }.toSet[(ActorRef, ActorRef)] sender() ! Stats( watching = watchSet.size, watchingNodes = watchingNodes.size)(watchSet, watchingNodes.toSet) @@ -155,13 +155,13 @@ private[akka] class RemoteWatcher( if (watcheeByNodes.contains(from) && !unreachable(from)) { if (!addressUids.contains(from) || addressUids(from) != uid) reWatch(from) - addressUids += (from → uid) + addressUids += (from -> uid) failureDetector.heartbeat(from) } } def reapUnreachable(): Unit = - watchingNodes foreach { a ⇒ + watchingNodes foreach { a => if (!unreachable(a) && !failureDetector.isAvailable(a)) { log.warning("Detected unreachable: [{}]", a) quarantine(a, addressUids.get(a), "Deemed unreachable by remote failure detector", harmless = false) @@ -175,8 +175,8 @@ private[akka] class RemoteWatcher( def quarantine(address: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = { remoteProvider.transport match { - case t: ArteryTransport if harmless ⇒ t.quarantine(address, uid, reason, harmless) - case _ ⇒ remoteProvider.quarantine(address, uid, reason) + case t: ArteryTransport if harmless => t.quarantine(address, uid, reason, harmless) + case _ => remoteProvider.quarantine(address, uid, reason) } } @@ -206,7 +206,7 @@ private[akka] class RemoteWatcher( // Could have used removeBinding, but it does not tell if this was the last entry. This saves a contains call. watching.get(watchee) match { - case Some(watchers) ⇒ + case Some(watchers) => watchers -= watcher if (watchers.isEmpty) { // clean up self watch when no more watchers of this watchee @@ -214,7 +214,7 @@ private[akka] class RemoteWatcher( context unwatch watchee removeWatchee(watchee) } - case None ⇒ + case None => } } @@ -223,14 +223,14 @@ private[akka] class RemoteWatcher( watching -= watchee // Could have used removeBinding, but it does not tell if this was the last entry. This saves a contains call. watcheeByNodes.get(watcheeAddress) match { - case Some(watchees) ⇒ + case Some(watchees) => watchees -= watchee if (watchees.isEmpty) { // unwatched last watchee on that node log.debug("Unwatched last watchee of node: [{}]", watcheeAddress) unwatchNode(watcheeAddress) } - case None ⇒ + case None => } } @@ -248,15 +248,15 @@ private[akka] class RemoteWatcher( // addressTerminated case is already handled by the watcher itself in DeathWatch trait if (!addressTerminated) for { - watchers ← watching.get(watchee) - watcher ← watchers + watchers <- watching.get(watchee) + watcher <- watchers } watcher.sendSystemMessage(DeathWatchNotification(watchee, existenceConfirmed, addressTerminated)) removeWatchee(watchee) } def sendHeartbeat(): Unit = - watchingNodes foreach { a ⇒ + watchingNodes foreach { a => if (!unreachable(a)) { if (failureDetector.isMonitoring(a)) { log.debug("Sending Heartbeat to [{}]", a) @@ -285,8 +285,8 @@ private[akka] class RemoteWatcher( */ def reWatch(address: Address): Unit = for { - watchees ← watcheeByNodes.get(address) - watchee ← watchees + watchees <- watcheeByNodes.get(address) + watchee <- watchees } { val watcher = self.asInstanceOf[InternalActorRef] log.debug("Re-watch [{} -> {}]", watcher.path, watchee.path) diff --git a/akka-remote/src/main/scala/akka/remote/Remoting.scala b/akka-remote/src/main/scala/akka/remote/Remoting.scala index 7c30f43261..d1fcb898d3 100644 --- a/akka-remote/src/main/scala/akka/remote/Remoting.scala +++ b/akka-remote/src/main/scala/akka/remote/Remoting.scala @@ -78,27 +78,27 @@ private[remote] object Remoting { def localAddressForRemote(transportMapping: Map[String, Set[(AkkaProtocolTransport, Address)]], remote: Address): Address = { transportMapping.get(remote.protocol) match { - case Some(transports) ⇒ - val responsibleTransports = transports.filter { case (t, _) ⇒ t.isResponsibleFor(remote) } + case Some(transports) => + val responsibleTransports = transports.filter { case (t, _) => t.isResponsibleFor(remote) } responsibleTransports.size match { - case 0 ⇒ + case 0 => throw new RemoteTransportException( s"No transport is responsible for address: [$remote] although protocol [${remote.protocol}] is available." + " Make sure at least one transport is configured to be responsible for the address.", null) - case 1 ⇒ + case 1 => responsibleTransports.head._2 - case _ ⇒ + case _ => throw new RemoteTransportException( s"Multiple transports are available for [$remote]: [${responsibleTransports.mkString(",")}]. " + "Remoting cannot decide which transport to use to reach the remote system. Change your configuration " + "so that only one transport is responsible for the address.", null) } - case None ⇒ throw new RemoteTransportException( + case None => throw new RemoteTransportException( s"No transport is loaded for protocol: [${remote.protocol}], available protocols: [${transportMapping.keys.mkString(", ")}]", null) } } @@ -107,11 +107,11 @@ private[remote] object Remoting { private[Remoting] class TransportSupervisor extends Actor with RequiresMessageQueue[UnboundedMessageQueueSemantics] { override def supervisorStrategy = OneForOneStrategy() { - case NonFatal(_) ⇒ Restart + case NonFatal(_) => Restart } def receive = { - case RegisterTransportActor(props, name) ⇒ + case RegisterTransportActor(props, name) => sender() ! context.actorOf( RARP(context.system).configureDispatcher(props.withDeploy(Deploy.local)), name) @@ -150,7 +150,7 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc override def shutdown(): Future[Done] = { endpointManager match { - case Some(manager) ⇒ + case Some(manager) => implicit val timeout = ShutdownTimeout def finalize(): Unit = { @@ -160,17 +160,17 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc import system.dispatcher (manager ? ShutdownAndFlush).mapTo[Boolean].andThen { - case Success(flushSuccessful) ⇒ + case Success(flushSuccessful) => if (!flushSuccessful) log.warning("Shutdown finished, but flushing might not have been successful and some messages might have been dropped. " + "Increase akka.remote.flush-wait-on-shutdown to a larger value to avoid this.") finalize() - case Failure(e) ⇒ + case Failure(e) => notifyError("Failure during shutdown of remoting.", e) finalize() - } map { _ ⇒ Done } // RARP needs only akka.Done, not a boolean - case None ⇒ + } map { _ => Done } // RARP needs only akka.Done, not a boolean + case None => log.warning("Remoting is not running. Ignoring shutdown attempt.") Future successful Done } @@ -179,7 +179,7 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc // Start assumes that it cannot be followed by another start() without having a shutdown() first override def start(): Unit = { endpointManager match { - case None ⇒ + case None => log.info("Starting remoting") val manager: ActorRef = system.systemActorOf( configureDispatcher(Props(classOf[EndpointManager], provider.remoteSettings.config, log)).withDeploy(Deploy.local), @@ -196,8 +196,8 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc if (transports.isEmpty) throw new RemoteTransportException("No transport drivers were loaded.", null) transportMapping = transports.groupBy { - case (transport, _) ⇒ transport.schemeIdentifier - } map { case (k, v) ⇒ k → v.toSet } + case (transport, _) => transport.schemeIdentifier + } map { case (k, v) => k -> v.toSet } defaultAddress = transports.head._2 addresses = transports.map { _._2 }.toSet @@ -208,45 +208,45 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc eventPublisher.notifyListeners(RemotingListenEvent(addresses)) } catch { - case e: TimeoutException ⇒ + case e: TimeoutException => notifyError("Startup timed out. This is usually related to actor system host setting or host name resolution misconfiguration.", e) throw e - case NonFatal(e) ⇒ + case NonFatal(e) => notifyError("Startup failed", e) throw e } - case Some(_) ⇒ + case Some(_) => log.warning("Remoting was already started. Ignoring start attempt.") } } override def send(message: Any, senderOption: OptionVal[ActorRef], recipient: RemoteActorRef): Unit = endpointManager match { - case Some(manager) ⇒ manager.tell(Send(message, senderOption, recipient), sender = senderOption getOrElse Actor.noSender) - case None ⇒ throw new RemoteTransportExceptionNoStackTrace("Attempted to send remote message but Remoting is not running.", null) + case Some(manager) => manager.tell(Send(message, senderOption, recipient), sender = senderOption getOrElse Actor.noSender) + case None => throw new RemoteTransportExceptionNoStackTrace("Attempted to send remote message but Remoting is not running.", null) } override def managementCommand(cmd: Any): Future[Boolean] = endpointManager match { - case Some(manager) ⇒ + case Some(manager) => import system.dispatcher implicit val timeout = CommandAckTimeout - manager ? ManagementCommand(cmd) map { case ManagementCommandAck(status) ⇒ status } - case None ⇒ throw new RemoteTransportExceptionNoStackTrace("Attempted to send management command but Remoting is not running.", null) + manager ? ManagementCommand(cmd) map { case ManagementCommandAck(status) => status } + case None => throw new RemoteTransportExceptionNoStackTrace("Attempted to send management command but Remoting is not running.", null) } override def quarantine(remoteAddress: Address, uid: Option[Long], reason: String): Unit = endpointManager match { - case Some(manager) ⇒ + case Some(manager) => manager ! Quarantine(remoteAddress, uid.map(_.toInt)) - case _ ⇒ throw new RemoteTransportExceptionNoStackTrace( + case _ => throw new RemoteTransportExceptionNoStackTrace( s"Attempted to quarantine address [$remoteAddress] with UID [$uid] but Remoting is not running", null) } private[akka] def boundAddresses: Map[String, Set[Address]] = { transportMapping.map { - case (scheme, transports) ⇒ - scheme → transports.flatMap { + case (scheme, transports) => + scheme -> transports.flatMap { // Need to do like this for binary compatibility reasons - case (t, _) ⇒ Option(t.boundAddress) + case (t, _) => Option(t.boundAddress) } } } @@ -315,20 +315,20 @@ private[remote] object EndpointManager { def registerWritableEndpoint(address: Address, uid: Option[Int], endpoint: ActorRef): ActorRef = addressToWritable.get(address) match { - case Some(Pass(e, _)) ⇒ + case Some(Pass(e, _)) => throw new IllegalArgumentException(s"Attempting to overwrite existing endpoint [$e] with [$endpoint]") - case _ ⇒ + case _ => // note that this overwrites Quarantine marker, // but that is ok since we keep the quarantined uid in addressToRefuseUid - addressToWritable += address → Pass(endpoint, uid) - writableToAddress += endpoint → address + addressToWritable += address -> Pass(endpoint, uid) + writableToAddress += endpoint -> address endpoint } def registerWritableEndpointUid(remoteAddress: Address, uid: Int): Unit = { addressToWritable.get(remoteAddress) match { - case Some(Pass(ep, _)) ⇒ addressToWritable += remoteAddress → Pass(ep, Some(uid)) - case _ ⇒ + case Some(Pass(ep, _)) => addressToWritable += remoteAddress -> Pass(ep, Some(uid)) + case _ => } } @@ -337,8 +337,8 @@ private[remote] object EndpointManager { } def registerReadOnlyEndpoint(address: Address, endpoint: ActorRef, uid: Int): ActorRef = { - addressToReadonly += address → ((endpoint, uid)) - readonlyToAddress += endpoint → address + addressToReadonly += address -> ((endpoint, uid)) + readonlyToAddress += endpoint -> address endpoint } @@ -346,8 +346,8 @@ private[remote] object EndpointManager { if (isWritable(endpoint)) { val address = writableToAddress(endpoint) addressToWritable.get(address) match { - case Some(policy) if policy.isTombstone ⇒ // There is already a tombstone directive, leave it there - case _ ⇒ addressToWritable -= address + case Some(policy) if policy.isTombstone => // There is already a tombstone directive, leave it there + case _ => addressToWritable -= address } writableToAddress -= endpoint // leave the refuseUid @@ -361,8 +361,8 @@ private[remote] object EndpointManager { def writableEndpointWithPolicyFor(address: Address): Option[EndpointPolicy] = addressToWritable.get(address) def hasWritableEndpointFor(address: Address): Boolean = writableEndpointWithPolicyFor(address) match { - case Some(_: Pass) ⇒ true - case _ ⇒ false + case Some(_: Pass) => true + case _ => false } def readOnlyEndpointFor(address: Address): Option[(ActorRef, Int)] = addressToReadonly.get(address) @@ -374,16 +374,16 @@ private[remote] object EndpointManager { def isQuarantined(address: Address, uid: Int): Boolean = writableEndpointWithPolicyFor(address) match { // timeOfRelease is only used for garbage collection. If an address is still probed, we should report the // known fact that it is quarantined. - case Some(Quarantined(`uid`, _)) ⇒ true - case _ ⇒ - addressToRefuseUid.get(address).exists { case (refuseUid, _) ⇒ refuseUid == uid } + case Some(Quarantined(`uid`, _)) => true + case _ => + addressToRefuseUid.get(address).exists { case (refuseUid, _) => refuseUid == uid } } def refuseUid(address: Address): Option[Int] = writableEndpointWithPolicyFor(address) match { // timeOfRelease is only used for garbage collection. If an address is still probed, we should report the // known fact that it is quarantined. - case Some(Quarantined(uid, _)) ⇒ Some(uid) - case _ ⇒ addressToRefuseUid.get(address).map { case (refuseUid, _) ⇒ refuseUid } + case Some(Quarantined(uid, _)) => Some(uid) + case _ => addressToRefuseUid.get(address).map { case (refuseUid, _) => refuseUid } } /** @@ -394,13 +394,13 @@ private[remote] object EndpointManager { if (isWritable(endpoint)) { val address = writableToAddress(endpoint) addressToWritable.get(address) match { - case Some(Quarantined(_, _)) ⇒ // don't overwrite Quarantined with Gated - case Some(Pass(_, _)) ⇒ - addressToWritable += address → Gated(timeOfRelease) + case Some(Quarantined(_, _)) => // don't overwrite Quarantined with Gated + case Some(Pass(_, _)) => + addressToWritable += address -> Gated(timeOfRelease) writableToAddress -= endpoint - case Some(Gated(_)) ⇒ // already gated - case None ⇒ - addressToWritable += address → Gated(timeOfRelease) + case Some(Gated(_)) => // already gated + case None => + addressToWritable += address -> Gated(timeOfRelease) writableToAddress -= endpoint } } else if (isReadOnly(endpoint)) { @@ -409,7 +409,7 @@ private[remote] object EndpointManager { } def markAsQuarantined(address: Address, uid: Int, timeOfRelease: Deadline): Unit = { - addressToWritable += address → Quarantined(uid, timeOfRelease) + addressToWritable += address -> Quarantined(uid, timeOfRelease) addressToRefuseUid = addressToRefuseUid.updated(address, (uid, timeOfRelease)) } @@ -420,17 +420,17 @@ private[remote] object EndpointManager { def prune(): Unit = { addressToWritable = addressToWritable.collect { - case entry @ (_, Gated(timeOfRelease)) if timeOfRelease.hasTimeLeft ⇒ + case entry @ (_, Gated(timeOfRelease)) if timeOfRelease.hasTimeLeft => // Gated removed when no time left entry - case entry @ (_, Quarantined(_, timeOfRelease)) if timeOfRelease.hasTimeLeft ⇒ + case entry @ (_, Quarantined(_, timeOfRelease)) if timeOfRelease.hasTimeLeft => // Quarantined removed when no time left entry - case entry @ (_, _: Pass) ⇒ entry + case entry @ (_, _: Pass) => entry } addressToRefuseUid = addressToRefuseUid.collect { - case entry @ (_, (_, timeOfRelease)) if timeOfRelease.hasTimeLeft ⇒ + case entry @ (_, (_, timeOfRelease)) if timeOfRelease.hasTimeLeft => // // Quarantined/refuseUid removed when no time left entry } @@ -473,28 +473,28 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends stashed foreach (handleInboundAssociation(_, writerIsIdle)) } - def keepQuarantinedOr(remoteAddress: Address)(body: ⇒ Unit): Unit = endpoints.refuseUid(remoteAddress) match { - case Some(uid) ⇒ + def keepQuarantinedOr(remoteAddress: Address)(body: => Unit): Unit = endpoints.refuseUid(remoteAddress) match { + case Some(uid) => log.info("Quarantined address [{}] is still unreachable or has not been restarted. Keeping it quarantined.", remoteAddress) // Restoring Quarantine marker overwritten by a Pass(endpoint, refuseUid) pair while probing remote system. endpoints.markAsQuarantined(remoteAddress, uid, Deadline.now + settings.QuarantineDuration) - case None ⇒ body + case None => body } override val supervisorStrategy = { def hopeless(e: HopelessAssociation): SupervisorStrategy.Directive = e match { - case HopelessAssociation(_, remoteAddress, Some(uid), reason) ⇒ + case HopelessAssociation(_, remoteAddress, Some(uid), reason) => log.error(reason, "Association to [{}] with UID [{}] irrecoverably failed. Quarantining address.", remoteAddress, uid) settings.QuarantineDuration match { - case d: FiniteDuration ⇒ + case d: FiniteDuration => endpoints.markAsQuarantined(remoteAddress, uid, Deadline.now + d) eventPublisher.notifyListeners(QuarantinedEvent(remoteAddress, uid)) - case _ ⇒ // disabled + case _ => // disabled } Stop - case HopelessAssociation(_, remoteAddress, None, _) ⇒ + case HopelessAssociation(_, remoteAddress, None, _) => keepQuarantinedOr(remoteAddress) { log.warning( "Association to [{}] with unknown UID is irrecoverably failed. " + @@ -506,7 +506,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends } OneForOneStrategy(loggingEnabled = false) { - case InvalidAssociation(localAddress, remoteAddress, reason, disassiciationInfo) ⇒ + case InvalidAssociation(localAddress, remoteAddress, reason, disassiciationInfo) => keepQuarantinedOr(remoteAddress) { val causedBy = if (reason.getCause == null) "" else s"Caused by: [${reason.getCause.getMessage}]" log.warning( @@ -517,13 +517,13 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends endpoints.markAsFailed(sender(), Deadline.now + settings.RetryGateClosedFor) } disassiciationInfo.foreach { - case AssociationHandle.Quarantined ⇒ + case AssociationHandle.Quarantined => context.system.eventStream.publish(ThisActorSystemQuarantinedEvent(localAddress, remoteAddress)) - case _ ⇒ // do nothing + case _ => // do nothing } Stop - case ShutDownAssociation(_, remoteAddress, _) ⇒ + case ShutDownAssociation(_, remoteAddress, _) => keepQuarantinedOr(remoteAddress) { log.debug( "Remote system with address [{}] has shut down. " + @@ -533,16 +533,16 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends } Stop - case e: HopelessAssociation ⇒ + case e: HopelessAssociation => hopeless(e) - case e: ActorInitializationException if e.getCause.isInstanceOf[HopelessAssociation] ⇒ + case e: ActorInitializationException if e.getCause.isInstanceOf[HopelessAssociation] => hopeless(e.getCause.asInstanceOf[HopelessAssociation]) - case NonFatal(e) ⇒ + case NonFatal(e) => e match { - case _: EndpointDisassociatedException | _: EndpointAssociationException ⇒ // no logging - case _ ⇒ log.error(e, e.getMessage) + case _: EndpointDisassociatedException | _: EndpointAssociationException => // no logging + case _ => log.error(e, e.getMessage) } endpoints.markAsFailed(sender(), Deadline.now + settings.RetryGateClosedFor) Stop @@ -553,79 +553,79 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends val receiveBuffers = new ConcurrentHashMap[Link, ResendState]() def receive = { - case Listen(addressesPromise) ⇒ + case Listen(addressesPromise) => listens map { ListensResult(addressesPromise, _) } recover { - case NonFatal(e) ⇒ ListensFailure(addressesPromise, e) + case NonFatal(e) => ListensFailure(addressesPromise, e) } pipeTo self - case ListensResult(addressesPromise, results) ⇒ + case ListensResult(addressesPromise, results) => transportMapping = results.groupBy { - case (_, transportAddress, _) ⇒ transportAddress + case (_, transportAddress, _) => transportAddress } map { - case (a, t) if t.size > 1 ⇒ + case (a, t) if t.size > 1 => throw new RemoteTransportException(s"There are more than one transports listening on local address [$a]", null) - case (a, t) ⇒ a → t.head._1 + case (a, t) => a -> t.head._1 } // Register to each transport as listener and collect mapping to addresses val transportsAndAddresses = results map { - case (transport, address, promise) ⇒ + case (transport, address, promise) => promise.success(ActorAssociationEventListener(self)) - transport → address + transport -> address } addressesPromise.success(transportsAndAddresses) - case ListensFailure(addressesPromise, cause) ⇒ + case ListensFailure(addressesPromise, cause) => addressesPromise.failure(cause) - case ia: InboundAssociation ⇒ + case ia: InboundAssociation => context.system.scheduler.scheduleOnce(10.milliseconds, self, ia) - case ManagementCommand(_) ⇒ + case ManagementCommand(_) => sender() ! ManagementCommandAck(status = false) - case StartupFinished ⇒ + case StartupFinished => context.become(accepting) - case ShutdownAndFlush ⇒ + case ShutdownAndFlush => sender() ! true context.stop(self) // Nothing to flush at this point } val accepting: Receive = { - case ManagementCommand(cmd) ⇒ + case ManagementCommand(cmd) => val allStatuses: immutable.Seq[Future[Boolean]] = - transportMapping.values.iterator.map(transport ⇒ transport.managementCommand(cmd)).to(immutable.IndexedSeq) + transportMapping.values.iterator.map(transport => transport.managementCommand(cmd)).to(immutable.IndexedSeq) akka.compat.Future.fold(allStatuses)(true)(_ && _) map ManagementCommandAck pipeTo sender() - case Quarantine(address, uidToQuarantineOption) ⇒ + case Quarantine(address, uidToQuarantineOption) => // Stop writers (endpoints.writableEndpointWithPolicyFor(address), uidToQuarantineOption) match { - case (Some(Pass(endpoint, _)), None) ⇒ + case (Some(Pass(endpoint, _)), None) => context.stop(endpoint) log.warning( "Association to [{}] with unknown UID is reported as quarantined, but " + "address cannot be quarantined without knowing the UID, gating instead for {} ms.", address, settings.RetryGateClosedFor.toMillis) endpoints.markAsFailed(endpoint, Deadline.now + settings.RetryGateClosedFor) - case (Some(Pass(endpoint, uidOption)), Some(quarantineUid)) ⇒ + case (Some(Pass(endpoint, uidOption)), Some(quarantineUid)) => uidOption match { - case Some(`quarantineUid`) ⇒ + case Some(`quarantineUid`) => endpoints.markAsQuarantined(address, quarantineUid, Deadline.now + settings.QuarantineDuration) eventPublisher.notifyListeners(QuarantinedEvent(address, quarantineUid)) context.stop(endpoint) // or it does not match with the UID to be quarantined - case None if !endpoints.refuseUid(address).contains(quarantineUid) ⇒ + case None if !endpoints.refuseUid(address).contains(quarantineUid) => // the quarantine uid may be got fresh by cluster gossip, so update refuseUid for late handle when the writer got uid endpoints.registerWritableEndpointRefuseUid(address, quarantineUid, Deadline.now + settings.QuarantineDuration) - case _ ⇒ //the quarantine uid has lost the race with some failure, do nothing + case _ => //the quarantine uid has lost the race with some failure, do nothing } - case (Some(Quarantined(uid, _)), Some(quarantineUid)) if uid == quarantineUid ⇒ // the UID to be quarantined already exists, do nothing - case (_, Some(quarantineUid)) ⇒ + case (Some(Quarantined(uid, _)), Some(quarantineUid)) if uid == quarantineUid => // the UID to be quarantined already exists, do nothing + case (_, Some(quarantineUid)) => // the current state is gated or quarantined, and we know the UID, update endpoints.markAsQuarantined(address, quarantineUid, Deadline.now + settings.QuarantineDuration) eventPublisher.notifyListeners(QuarantinedEvent(address, quarantineUid)) - case _ ⇒ // the current state is Gated, WasGated or Quarantined, and we don't know the UID, do nothing. + case _ => // the current state is Gated, WasGated or Quarantined, and we don't know the UID, do nothing. } // Stop inbound read-only associations (endpoints.readOnlyEndpointFor(address), uidToQuarantineOption) match { - case (Some((endpoint, _)), None) ⇒ context.stop(endpoint) - case (Some((endpoint, currentUid)), Some(quarantineUid)) if currentUid == quarantineUid ⇒ context.stop(endpoint) - case _ ⇒ // nothing to stop + case (Some((endpoint, _)), None) => context.stop(endpoint) + case (Some((endpoint, currentUid)), Some(quarantineUid)) if currentUid == quarantineUid => context.stop(endpoint) + case _ => // nothing to stop } def matchesQuarantine(handle: AkkaProtocolHandle): Boolean = { @@ -635,7 +635,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends // Stop all matching pending read handoffs pendingReadHandoffs = pendingReadHandoffs.filter { - case (pendingActor, pendingHandle) ⇒ + case (pendingActor, pendingHandle) => val drop = matchesQuarantine(pendingHandle) // Side-effecting here if (drop) { @@ -647,8 +647,8 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends // Stop all matching stashed connections stashedInbound = stashedInbound.map { - case (writer, associations) ⇒ - writer → associations.filter { assoc ⇒ + case (writer, associations) => + writer -> associations.filter { assoc => val handle = assoc.association.asInstanceOf[AkkaProtocolHandle] val drop = matchesQuarantine(handle) if (drop) handle.disassociate("the stashed inbound handle was quarantined", log) @@ -656,7 +656,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends } } - case s @ Send(_, _, recipientRef, _) ⇒ + case s @ Send(_, _, recipientRef, _) => val recipientAddress = recipientRef.path.address def createAndRegisterWritingEndpoint(): ActorRef = { @@ -673,62 +673,62 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends } endpoints.writableEndpointWithPolicyFor(recipientAddress) match { - case Some(Pass(endpoint, _)) ⇒ + case Some(Pass(endpoint, _)) => endpoint ! s - case Some(Gated(timeOfRelease)) ⇒ + case Some(Gated(timeOfRelease)) => if (timeOfRelease.isOverdue()) createAndRegisterWritingEndpoint() ! s else extendedSystem.deadLetters ! s - case Some(Quarantined(_, _)) ⇒ + case Some(Quarantined(_, _)) => // timeOfRelease is only used for garbage collection reasons, therefore it is ignored here. We still have // the Quarantined tombstone and we know what UID we don't want to accept, so use it. createAndRegisterWritingEndpoint() ! s - case None ⇒ + case None => createAndRegisterWritingEndpoint() ! s } - case ia @ InboundAssociation(_: AkkaProtocolHandle) ⇒ + case ia @ InboundAssociation(_: AkkaProtocolHandle) => handleInboundAssociation(ia, writerIsIdle = false) - case EndpointWriter.StoppedReading(endpoint) ⇒ + case EndpointWriter.StoppedReading(endpoint) => acceptPendingReader(takingOverFrom = endpoint) - case Terminated(endpoint) ⇒ + case Terminated(endpoint) => acceptPendingReader(takingOverFrom = endpoint) endpoints.unregisterEndpoint(endpoint) handleStashedInbound(endpoint, writerIsIdle = false) - case EndpointWriter.TookOver(endpoint, handle) ⇒ + case EndpointWriter.TookOver(endpoint, handle) => removePendingReader(takingOverFrom = endpoint, withHandle = handle) - case ReliableDeliverySupervisor.GotUid(uid, remoteAddress) ⇒ + case ReliableDeliverySupervisor.GotUid(uid, remoteAddress) => val refuseUidOption = endpoints.refuseUid(remoteAddress) endpoints.writableEndpointWithPolicyFor(remoteAddress) match { - case Some(Pass(endpoint, _)) ⇒ + case Some(Pass(endpoint, _)) => if (refuseUidOption.contains(uid)) { endpoints.markAsQuarantined(remoteAddress, uid, Deadline.now + settings.QuarantineDuration) eventPublisher.notifyListeners(QuarantinedEvent(remoteAddress, uid)) context.stop(endpoint) } else endpoints.registerWritableEndpointUid(remoteAddress, uid) handleStashedInbound(sender(), writerIsIdle = false) - case _ ⇒ // the GotUid might have lost the race with some failure + case _ => // the GotUid might have lost the race with some failure } - case ReliableDeliverySupervisor.Idle ⇒ + case ReliableDeliverySupervisor.Idle => handleStashedInbound(sender(), writerIsIdle = true) - case Prune ⇒ + case Prune => endpoints.prune() - case ShutdownAndFlush ⇒ + case ShutdownAndFlush => // Shutdown all endpoints and signal to sender() when ready (and whether all endpoints were shut down gracefully) - def shutdownAll[T](resources: IterableOnce[T])(shutdown: T ⇒ Future[Boolean]): Future[Boolean] = { + def shutdownAll[T](resources: IterableOnce[T])(shutdown: T => Future[Boolean]): Future[Boolean] = { Future.sequence(resources.toList.map(shutdown)) .map(_.forall(identity)) .recover { - case NonFatal(_) ⇒ false + case NonFatal(_) => false } } (for { // The construction of the future for shutdownStatus has to happen after the flushStatus future has been finished // so that endpoints are shut down before transports. - flushStatus ← shutdownAll(endpoints.allEndpoints)(gracefulStop(_, settings.FlushWait, EndpointWriter.FlushAndStop)) - shutdownStatus ← shutdownAll(transportMapping.values)(_.shutdown()) + flushStatus <- shutdownAll(endpoints.allEndpoints)(gracefulStop(_, settings.FlushWait, EndpointWriter.FlushAndStop)) + shutdownStatus <- shutdownAll(transportMapping.values)(_.shutdown()) } yield flushStatus && shutdownStatus) pipeTo sender() pendingReadHandoffs.valuesIterator foreach (_.disassociate(AssociationHandle.Shutdown)) @@ -739,37 +739,37 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends } def flushing: Receive = { - case s: Send ⇒ extendedSystem.deadLetters ! s - case InboundAssociation(h: AkkaProtocolHandle) ⇒ h.disassociate(AssociationHandle.Shutdown) - case Terminated(_) ⇒ // why should we care now? + case s: Send => extendedSystem.deadLetters ! s + case InboundAssociation(h: AkkaProtocolHandle) => h.disassociate(AssociationHandle.Shutdown) + case Terminated(_) => // why should we care now? } def handleInboundAssociation(ia: InboundAssociation, writerIsIdle: Boolean): Unit = ia match { - case ia @ InboundAssociation(handle: AkkaProtocolHandle) ⇒ endpoints.readOnlyEndpointFor(handle.remoteAddress) match { - case Some((endpoint, _)) ⇒ + case ia @ InboundAssociation(handle: AkkaProtocolHandle) => endpoints.readOnlyEndpointFor(handle.remoteAddress) match { + case Some((endpoint, _)) => pendingReadHandoffs.get(endpoint) foreach (_.disassociate("the existing readOnly association was replaced by a new incoming one", log)) - pendingReadHandoffs += endpoint → handle + pendingReadHandoffs += endpoint -> handle endpoint ! EndpointWriter.TakeOver(handle, self) endpoints.writableEndpointWithPolicyFor(handle.remoteAddress) match { - case Some(Pass(ep, _)) ⇒ ep ! ReliableDeliverySupervisor.Ungate - case _ ⇒ + case Some(Pass(ep, _)) => ep ! ReliableDeliverySupervisor.Ungate + case _ => } - case None ⇒ + case None => if (endpoints.isQuarantined(handle.remoteAddress, handle.handshakeInfo.uid)) handle.disassociate(AssociationHandle.Quarantined) else endpoints.writableEndpointWithPolicyFor(handle.remoteAddress) match { - case Some(Pass(ep, None)) ⇒ + case Some(Pass(ep, None)) => // Idle writer will never send a GotUid or a Terminated so we need to "provoke it" // to get an unstash event if (!writerIsIdle) { ep ! ReliableDeliverySupervisor.IsIdle - stashedInbound += ep → (stashedInbound.getOrElse(ep, Vector.empty) :+ ia) + stashedInbound += ep -> (stashedInbound.getOrElse(ep, Vector.empty) :+ ia) } else createAndRegisterEndpoint(handle) - case Some(Pass(ep, Some(uid))) ⇒ + case Some(Pass(ep, Some(uid))) => if (handle.handshakeInfo.uid == uid) { pendingReadHandoffs.get(ep) foreach (_.disassociate("the existing writable association was replaced by a new incoming one", log)) - pendingReadHandoffs += ep → handle + pendingReadHandoffs += ep -> handle ep ! EndpointWriter.StopReading(ep, self) ep ! ReliableDeliverySupervisor.Ungate } else { @@ -779,11 +779,11 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends endpoints.markAsQuarantined(handle.remoteAddress, uid, Deadline.now + settings.QuarantineDuration) createAndRegisterEndpoint(handle) } - case _ ⇒ + case _ => createAndRegisterEndpoint(handle) } } - case _ ⇒ // ignore + case _ => // ignore } private def createAndRegisterEndpoint(handle: AkkaProtocolHandle): Unit = { @@ -815,9 +815,9 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends * * The transports variable contains only the heads of each chains (the AkkaProtocolTransport instances). */ - val transports: Seq[AkkaProtocolTransport] = for ((fqn, adapters, config) ← settings.Transports) yield { + val transports: Seq[AkkaProtocolTransport] = for ((fqn, adapters, config) <- settings.Transports) yield { - val args = Seq(classOf[ExtendedActorSystem] → context.system, classOf[Config] → config) + val args = Seq(classOf[ExtendedActorSystem] -> context.system, classOf[Config] -> config) // Loads the driver -- the bottom element of the chain. // The chain at this point: @@ -825,7 +825,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends val driver = extendedSystem.dynamicAccess .createInstanceFor[Transport](fqn, args).recover({ - case exception ⇒ throw new IllegalArgumentException( + case exception => throw new IllegalArgumentException( s"Cannot instantiate transport [$fqn]. " + "Make sure it extends [akka.remote.transport.Transport] and has constructor with " + "[akka.actor.ExtendedActorSystem] and [com.typesafe.config.Config] parameters", exception) @@ -837,7 +837,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends // Adapter <- ... <- Adapter <- Driver val wrappedTransport = adapters.map { TransportAdaptersExtension.get(context.system).getAdapterProvider }.foldLeft(driver) { - (t: Transport, provider: TransportAdapterProvider) ⇒ + (t: Transport, provider: TransportAdapterProvider) => // The TransportAdapterProvider will wrap the given Transport and returns with a wrapped one provider.create(t, context.system.asInstanceOf[ExtendedActorSystem]) } @@ -849,8 +849,8 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends } // Collect all transports, listen addresses and listener promises in one future - Future.sequence(transports.map { transport ⇒ - transport.listen map { case (address, listenerPromise) ⇒ (transport, address, listenerPromise) } + Future.sequence(transports.map { transport => + transport.listen map { case (address, listenerPromise) => (transport, address, listenerPromise) } }) } @@ -872,7 +872,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) extends } private def removePendingReader(takingOverFrom: ActorRef, withHandle: AkkaProtocolHandle): Unit = { - if (pendingReadHandoffs.get(takingOverFrom).exists(handle ⇒ handle == withHandle)) + if (pendingReadHandoffs.get(takingOverFrom).exists(handle => handle == withHandle)) pendingReadHandoffs -= takingOverFrom } diff --git a/akka-remote/src/main/scala/akka/remote/artery/ArterySettings.scala b/akka-remote/src/main/scala/akka/remote/artery/ArterySettings.scala index bd5b8f2082..2e71091bb2 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/ArterySettings.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/ArterySettings.scala @@ -37,7 +37,7 @@ private[akka] final class ArterySettings private (config: Config) { val config: Config = getConfig("canonical") import config._ - val Port: Int = getInt("port").requiring(port ⇒ + val Port: Int = getInt("port").requiring(port => 0 to 65535 contains port, "canonical.port must be 0 through 65535") val Hostname: String = getHostname("hostname", config) } @@ -47,12 +47,12 @@ private[akka] final class ArterySettings private (config: Config) { import config._ val Port: Int = getString("port") match { - case "" ⇒ Canonical.Port - case _ ⇒ getInt("port").requiring(port ⇒ 0 to 65535 contains port, "bind.port must be 0 through 65535") + case "" => Canonical.Port + case _ => getInt("port").requiring(port => 0 to 65535 contains port, "bind.port must be 0 through 65535") } val Hostname: String = getHostname("hostname", config) match { - case "" ⇒ Canonical.Hostname - case other ⇒ other + case "" => Canonical.Hostname + case other => other } val BindTimeout: FiniteDuration = config.getMillisDuration("bind-timeout").requiring( @@ -60,7 +60,7 @@ private[akka] final class ArterySettings private (config: Config) { } val LargeMessageDestinations: WildcardIndex[NotUsed] = - config.getStringList("large-message-destinations").asScala.foldLeft(WildcardIndex[NotUsed]()) { (tree, entry) ⇒ + config.getStringList("large-message-destinations").asScala.foldLeft(WildcardIndex[NotUsed]()) { (tree, entry) => val segments = entry.split('/').tail tree.insert(segments, NotUsed) } @@ -75,10 +75,10 @@ private[akka] final class ArterySettings private (config: Config) { val LogAeronCounters: Boolean = config.getBoolean("log-aeron-counters") val Transport: Transport = toRootLowerCase(getString("transport")) match { - case AeronUpd.configName ⇒ AeronUpd - case Tcp.configName ⇒ Tcp - case TlsTcp.configName ⇒ TlsTcp - case other ⇒ throw new IllegalArgumentException(s"Unknown transport [$other], possible values: " + + case AeronUpd.configName => AeronUpd + case Tcp.configName => Tcp + case TlsTcp.configName => TlsTcp + case other => throw new IllegalArgumentException(s"Unknown transport [$other], possible values: " + s""""${AeronUpd.configName}", "${Tcp.configName}", or "${TlsTcp.configName}"""") } @@ -109,14 +109,14 @@ private[akka] final class ArterySettings private (config: Config) { } val EmbeddedMediaDriver: Boolean = getBoolean("embedded-media-driver") - val AeronDirectoryName: String = getString("aeron-dir") requiring (dir ⇒ + val AeronDirectoryName: String = getString("aeron-dir") requiring (dir => EmbeddedMediaDriver || dir.nonEmpty, "aeron-dir must be defined when using external media driver") val DeleteAeronDirectory: Boolean = getBoolean("delete-aeron-dir") - val IdleCpuLevel: Int = getInt("idle-cpu-level").requiring(level ⇒ + val IdleCpuLevel: Int = getInt("idle-cpu-level").requiring(level => 1 <= level && level <= 10, "idle-cpu-level must be between 1 and 10") - val OutboundLanes: Int = getInt("outbound-lanes").requiring(n ⇒ + val OutboundLanes: Int = getInt("outbound-lanes").requiring(n => n > 0, "outbound-lanes must be greater than zero") - val InboundLanes: Int = getInt("inbound-lanes").requiring(n ⇒ + val InboundLanes: Int = getInt("inbound-lanes").requiring(n => n > 0, "inbound-lanes must be greater than zero") val SysMsgBufferSize: Int = getInt("system-message-buffer-size").requiring( _ > 0, "system-message-buffer-size must be more than zero") @@ -127,56 +127,56 @@ private[akka] final class ArterySettings private (config: Config) { val OutboundLargeMessageQueueSize: Int = getInt("outbound-large-message-queue-size").requiring( _ > 0, "outbound-large-message-queue-size must be more than zero") val SystemMessageResendInterval: FiniteDuration = - config.getMillisDuration("system-message-resend-interval").requiring(interval ⇒ + config.getMillisDuration("system-message-resend-interval").requiring(interval => interval > Duration.Zero, "system-message-resend-interval must be more than zero") - val HandshakeTimeout: FiniteDuration = config.getMillisDuration("handshake-timeout").requiring(interval ⇒ + val HandshakeTimeout: FiniteDuration = config.getMillisDuration("handshake-timeout").requiring(interval => interval > Duration.Zero, "handshake-timeout must be more than zero") val HandshakeRetryInterval: FiniteDuration = - config.getMillisDuration("handshake-retry-interval").requiring(interval ⇒ + config.getMillisDuration("handshake-retry-interval").requiring(interval => interval > Duration.Zero, "handshake-retry-interval must be more than zero") val InjectHandshakeInterval: FiniteDuration = - config.getMillisDuration("inject-handshake-interval").requiring(interval ⇒ + config.getMillisDuration("inject-handshake-interval").requiring(interval => interval > Duration.Zero, "inject-handshake-interval must be more than zero") - val ConnectionTimeout: FiniteDuration = config.getMillisDuration("connection-timeout").requiring(interval ⇒ + val ConnectionTimeout: FiniteDuration = config.getMillisDuration("connection-timeout").requiring(interval => interval > Duration.Zero, "connection-timeout must be more than zero") - val GiveUpMessageAfter: FiniteDuration = config.getMillisDuration("give-up-message-after").requiring(interval ⇒ + val GiveUpMessageAfter: FiniteDuration = config.getMillisDuration("give-up-message-after").requiring(interval => interval > Duration.Zero, "give-up-message-after must be more than zero") val GiveUpSystemMessageAfter: FiniteDuration = - config.getMillisDuration("give-up-system-message-after").requiring(interval ⇒ + config.getMillisDuration("give-up-system-message-after").requiring(interval => interval > Duration.Zero, "give-up-system-message-after must be more than zero") val StopIdleOutboundAfter: FiniteDuration = config.getMillisDuration("stop-idle-outbound-after") - .requiring(interval ⇒ interval > Duration.Zero, "stop-idle-outbound-after must be more than zero") + .requiring(interval => interval > Duration.Zero, "stop-idle-outbound-after must be more than zero") val QuarantineIdleOutboundAfter: FiniteDuration = config.getMillisDuration("quarantine-idle-outbound-after") .requiring( - interval ⇒ interval > StopIdleOutboundAfter, + interval => interval > StopIdleOutboundAfter, "quarantine-idle-outbound-after must be greater than stop-idle-outbound-after") val StopQuarantinedAfterIdle: FiniteDuration = - config.getMillisDuration("stop-quarantined-after-idle").requiring(interval ⇒ + config.getMillisDuration("stop-quarantined-after-idle").requiring(interval => interval > Duration.Zero, "stop-quarantined-after-idle must be more than zero") val RemoveQuarantinedAssociationAfter: FiniteDuration = - config.getMillisDuration("remove-quarantined-association-after").requiring(interval ⇒ + config.getMillisDuration("remove-quarantined-association-after").requiring(interval => interval > Duration.Zero, "remove-quarantined-association-after must be more than zero") val ShutdownFlushTimeout: FiniteDuration = - config.getMillisDuration("shutdown-flush-timeout").requiring(interval ⇒ + config.getMillisDuration("shutdown-flush-timeout").requiring(interval => interval > Duration.Zero, "shutdown-flush-timeout must be more than zero") val InboundRestartTimeout: FiniteDuration = - config.getMillisDuration("inbound-restart-timeout").requiring(interval ⇒ + config.getMillisDuration("inbound-restart-timeout").requiring(interval => interval > Duration.Zero, "inbound-restart-timeout must be more than zero") val InboundMaxRestarts: Int = getInt("inbound-max-restarts") val OutboundRestartBackoff: FiniteDuration = - config.getMillisDuration("outbound-restart-backoff").requiring(interval ⇒ + config.getMillisDuration("outbound-restart-backoff").requiring(interval => interval > Duration.Zero, "outbound-restart-backoff must be more than zero") val OutboundRestartTimeout: FiniteDuration = - config.getMillisDuration("outbound-restart-timeout").requiring(interval ⇒ + config.getMillisDuration("outbound-restart-timeout").requiring(interval => interval > Duration.Zero, "outbound-restart-timeout must be more than zero") val OutboundMaxRestarts: Int = getInt("outbound-max-restarts") val ClientLivenessTimeout: FiniteDuration = - config.getMillisDuration("client-liveness-timeout").requiring(interval ⇒ + config.getMillisDuration("client-liveness-timeout").requiring(interval => interval > Duration.Zero, "client-liveness-timeout must be more than zero") - val ImageLivenessTimeout: FiniteDuration = config.getMillisDuration("image-liveness-timeout").requiring(interval ⇒ + val ImageLivenessTimeout: FiniteDuration = config.getMillisDuration("image-liveness-timeout").requiring(interval => interval > Duration.Zero, "image-liveness-timeout must be more than zero") require(ImageLivenessTimeout < HandshakeTimeout, "image-liveness-timeout must be less than handshake-timeout") - val DriverTimeout: FiniteDuration = config.getMillisDuration("driver-timeout").requiring(interval ⇒ + val DriverTimeout: FiniteDuration = config.getMillisDuration("driver-timeout").requiring(interval => interval > Duration.Zero, "driver-timeout must be more than zero") val FlightRecorderEnabled: Boolean = getBoolean("flight-recorder.enabled") val FlightRecorderDestination: String = getString("flight-recorder.destination") @@ -225,9 +225,9 @@ private[akka] object ArterySettings { } def getHostname(key: String, config: Config): String = config.getString(key) match { - case "" ⇒ InetAddress.getLocalHost.getHostAddress - case "" ⇒ InetAddress.getLocalHost.getHostName - case other ⇒ other + case "" => InetAddress.getLocalHost.getHostAddress + case "" => InetAddress.getLocalHost.getHostName + case other => other } sealed trait Transport { diff --git a/akka-remote/src/main/scala/akka/remote/artery/ArteryTransport.scala b/akka-remote/src/main/scala/akka/remote/artery/ArteryTransport.scala index ec5342e05e..2873a921b6 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/ArteryTransport.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/ArteryTransport.scala @@ -136,10 +136,10 @@ private[remote] final class AssociationState( uniqueRemoteAddressValueCache else { uniqueRemoteAddress.value match { - case Some(Success(peer)) ⇒ + case Some(Success(peer)) => uniqueRemoteAddressValueCache = Some(peer) uniqueRemoteAddressValueCache - case _ ⇒ None + case _ => None } } } @@ -150,20 +150,20 @@ private[remote] final class AssociationState( def newQuarantined(): AssociationState = uniqueRemoteAddressPromise.future.value match { - case Some(Success(a)) ⇒ + case Some(Success(a)) => new AssociationState( incarnation, uniqueRemoteAddressPromise, lastUsedTimestamp = new AtomicLong(System.nanoTime()), controlIdleKillSwitch, quarantined = quarantined.updated(a.uid, QuarantinedTimestamp(System.nanoTime()))) - case _ ⇒ this + case _ => this } def isQuarantined(): Boolean = { uniqueRemoteAddressValue match { - case Some(a) ⇒ isQuarantined(a.uid) - case _ ⇒ false // handshake not completed yet + case Some(a) => isQuarantined(a.uid) + case _ => false // handshake not completed yet } } @@ -175,9 +175,9 @@ private[remote] final class AssociationState( override def toString(): String = { val a = uniqueRemoteAddressPromise.future.value match { - case Some(Success(a)) ⇒ a - case Some(Failure(e)) ⇒ s"Failure($e)" - case None ⇒ "unknown" + case Some(Success(a)) => a + case Some(Failure(e)) => s"Failure($e)" + case None => "unknown" } s"AssociationState($incarnation, $a)" } @@ -253,11 +253,11 @@ private[remote] class FlushOnShutdown( override def preStart(): Unit = { try { - associations.foreach { a ⇒ + associations.foreach { a => val acksExpected = a.sendTerminationHint(self) a.associationState.uniqueRemoteAddressValue() match { - case Some(address) ⇒ remaining += address → acksExpected - case None ⇒ // Ignore, handshake was not completed on this association + case Some(address) => remaining += address -> acksExpected + case None => // Ignore, handshake was not completed on this association } } if (remaining.valuesIterator.sum == 0) { @@ -265,7 +265,7 @@ private[remote] class FlushOnShutdown( context.stop(self) } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // sendTerminationHint may throw done.tryFailure(e) throw e @@ -278,7 +278,7 @@ private[remote] class FlushOnShutdown( } def receive = { - case ActorSystemTerminatingAck(from) ⇒ + case ActorSystemTerminatingAck(from) => // Just treat unexpected acks as systems from which zero acks are expected val acksRemaining = remaining.getOrElse(from, 0) if (acksRemaining <= 1) { @@ -289,7 +289,7 @@ private[remote] class FlushOnShutdown( if (remaining.isEmpty) context.stop(self) - case FlushOnShutdown.Timeout ⇒ + case FlushOnShutdown.Timeout => context.stop(self) } } @@ -316,8 +316,8 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr override val log: LoggingAdapter = Logging(system, getClass.getName) val (afrFileChannel, afrFile, flightRecorder) = initializeFlightRecorder() match { - case None ⇒ (None, None, None) - case Some((c, f, r)) ⇒ (Some(c), Some(f), Some(r)) + case None => (None, None, None) + case Some((c, f, r)) => (Some(c), Some(f), Some(r)) } /** @@ -391,17 +391,17 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr def createFlightRecorderEventSink(synchr: Boolean = false): EventSink = { flightRecorder match { - case Some(f) ⇒ + case Some(f) => val eventSink = f.createEventSink() if (synchr) new SynchronizedEventSink(eventSink) else eventSink - case None ⇒ + case None => IgnoreEventSink } } private val associationRegistry = new AssociationRegistry( - remoteAddress ⇒ new Association( + remoteAddress => new Association( this, materializer, controlMaterializer, @@ -487,15 +487,15 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr // Select inbound lane based on destination to preserve message order, // Also include the uid of the sending system in the hash to spread // "hot" destinations, e.g. ActorSelection anchor. - protected val inboundLanePartitioner: InboundEnvelope ⇒ Int = env ⇒ { + protected val inboundLanePartitioner: InboundEnvelope => Int = env => { env.recipient match { - case OptionVal.Some(r) ⇒ + case OptionVal.Some(r) => val a = r.path.uid val b = env.originUid val hashA = 23 + a val hash: Int = 23 * hashA + java.lang.Long.hashCode(b) math.abs(hash % inboundLanes) - case OptionVal.None ⇒ + case OptionVal.None => // the lane is set by the DuplicateHandshakeReq stage, otherwise 0 env.lane } @@ -526,17 +526,17 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr override def notify(inboundEnvelope: InboundEnvelope): Unit = { try { inboundEnvelope.message match { - case m: CompressionMessage ⇒ + case m: CompressionMessage => import CompressionProtocol._ m match { - case ActorRefCompressionAdvertisement(from, table) ⇒ + case ActorRefCompressionAdvertisement(from, table) => if (table.originUid == localAddress.uid) { log.debug("Incoming ActorRef compression advertisement from [{}], table: [{}]", from, table) val a = association(from.address) // make sure uid is same for active association if (a.associationState.uniqueRemoteAddressValue().contains(from)) { import system.dispatcher - a.changeActorRefCompression(table).foreach { _ ⇒ + a.changeActorRefCompression(table).foreach { _ => a.sendControl(ActorRefCompressionAdvertisementAck(localAddress, table.version)) system.eventStream.publish(Events.ReceivedActorRefCompressionTable(from, table)) } @@ -546,22 +546,22 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr "Discarding incoming ActorRef compression advertisement from [{}] that was " + "prepared for another incarnation with uid [{}] than current uid [{}], table: [{}]", from, table.originUid, localAddress.uid, table) - case ack: ActorRefCompressionAdvertisementAck ⇒ + case ack: ActorRefCompressionAdvertisementAck => inboundCompressionAccess match { - case OptionVal.Some(access) ⇒ access.confirmActorRefCompressionAdvertisementAck(ack) - case _ ⇒ + case OptionVal.Some(access) => access.confirmActorRefCompressionAdvertisementAck(ack) + case _ => log.debug(s"Received {} version: [{}] however no inbound compression access was present. " + s"ACK will not take effect, however it will be redelivered and likely to apply then.", Logging.simpleName(ack), ack.tableVersion) } - case ClassManifestCompressionAdvertisement(from, table) ⇒ + case ClassManifestCompressionAdvertisement(from, table) => if (table.originUid == localAddress.uid) { log.debug("Incoming Class Manifest compression advertisement from [{}], table: [{}]", from, table) val a = association(from.address) // make sure uid is same for active association if (a.associationState.uniqueRemoteAddressValue().contains(from)) { import system.dispatcher - a.changeClassManifestCompression(table).foreach { _ ⇒ + a.changeClassManifestCompression(table).foreach { _ => a.sendControl(ClassManifestCompressionAdvertisementAck(localAddress, table.version)) system.eventStream.publish(Events.ReceivedClassManifestCompressionTable(from, table)) } @@ -571,16 +571,16 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr "Discarding incoming Class Manifest compression advertisement from [{}] that was " + "prepared for another incarnation with uid [{}] than current uid [{}], table: [{}]", from, table.originUid, localAddress.uid, table) - case ack: ClassManifestCompressionAdvertisementAck ⇒ + case ack: ClassManifestCompressionAdvertisementAck => inboundCompressionAccess match { - case OptionVal.Some(access) ⇒ access.confirmClassManifestCompressionAdvertisementAck(ack) - case _ ⇒ + case OptionVal.Some(access) => access.confirmClassManifestCompressionAdvertisementAck(ack) + case _ => log.debug(s"Received {} version: [{}] however no inbound compression access was present. " + s"ACK will not take effect, however it will be redelivered and likely to apply then.", Logging.simpleName(ack), ack.tableVersion) } } - case Quarantined(from, to) if to == localAddress ⇒ + case Quarantined(from, to) if to == localAddress => // Don't quarantine the other system here, since that will result cluster member removal // and can result in forming two separate clusters (cluster split). // Instead, the downing strategy should act on ThisActorSystemQuarantinedEvent, e.g. @@ -588,10 +588,10 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr val lifecycleEvent = ThisActorSystemQuarantinedEvent(localAddress.address, from.address) system.eventStream.publish(lifecycleEvent) - case _ ⇒ // not interesting + case _ => // not interesting } } catch { - case ShuttingDown ⇒ // silence it + case ShuttingDown => // silence it } } @@ -600,16 +600,16 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr } - protected def attachInboundStreamRestart(streamName: String, streamCompleted: Future[Done], restart: () ⇒ Unit): Unit = { + protected def attachInboundStreamRestart(streamName: String, streamCompleted: Future[Done], restart: () => Unit): Unit = { implicit val ec = materializer.executionContext streamCompleted.failed.foreach { - case ShutdownSignal ⇒ // shutdown as expected - case _: AeronTerminated ⇒ // shutdown already in progress - case cause if isShutdown ⇒ + case ShutdownSignal => // shutdown as expected + case _: AeronTerminated => // shutdown already in progress + case cause if isShutdown => // don't restart after shutdown, but log some details so we notice log.error(cause, s"{} failed after shutdown. {}", streamName, cause.getMessage) - case _: AbruptTerminationException ⇒ // ActorSystem shutdown - case cause ⇒ + case _: AbruptTerminationException => // ActorSystem shutdown + case cause => if (restartCounter.restart()) { log.error(cause, "{} failed. Restarting it. {}", streamName, cause.getMessage) topLevelFlightRecorder.loFreq(Transport_RestartInbound, s"$localAddress - $streamName") @@ -637,7 +637,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr flushingPromise.future } implicit val ec = system.dispatcher - flushing.recover { case _ ⇒ Done }.flatMap(_ ⇒ internalShutdown()) + flushing.recover { case _ => Done }.flatMap(_ => internalShutdown()) } else { Future.successful(Done) } @@ -649,8 +649,8 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr killSwitch.abort(ShutdownSignal) topLevelFlightRecorder.loFreq(Transport_KillSwitchPulled, NoMetaData) for { - _ ← streamsCompleted.recover { case _ ⇒ Done } - _ ← shutdownTransport().recover { case _ ⇒ Done } + _ <- streamsCompleted.recover { case _ => Done } + _ <- shutdownTransport().recover { case _ => Done } } yield { // no need to explicitly shut down the contained access since it's lifecycle is bound to the Decoder _inboundCompressionAccess = OptionVal.None @@ -667,7 +667,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr @tailrec final protected def updateStreamMatValues(streamId: Int, values: InboundStreamMatValues[LifeCycle]): Unit = { val prev = streamMatValues.get() - if (!streamMatValues.compareAndSet(prev, prev + (streamId → values))) { + if (!streamMatValues.compareAndSet(prev, prev + (streamId -> values))) { updateStreamMatValues(streamId, values) } } @@ -679,9 +679,9 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr private def streamsCompleted: Future[Done] = { implicit val ec = system.dispatcher for { - _ ← Future.traverse(associationRegistry.allAssociations)(_.streamsCompleted) - _ ← Future.sequence(streamMatValues.get().valuesIterator.map { - case InboundStreamMatValues(_, done) ⇒ done + _ <- Future.traverse(associationRegistry.allAssociations)(_.streamsCompleted) + _ <- Future.sequence(streamMatValues.get().valuesIterator.map { + case InboundStreamMatValues(_, done) => done }) } yield Done } @@ -690,11 +690,11 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr override def managementCommand(cmd: Any): Future[Boolean] = { cmd match { - case SetThrottle(address, direction, Blackhole) ⇒ + case SetThrottle(address, direction, Blackhole) => testState.blackhole(localAddress.address, address, direction) - case SetThrottle(address, direction, Unthrottled) ⇒ + case SetThrottle(address, direction, Unthrottled) => testState.passThrough(localAddress.address, address, direction) - case TestManagementCommands.FailInboundStreamOnce(ex) ⇒ + case TestManagementCommands.FailInboundStreamOnce(ex) => testState.failInboundStreamOnce(ex) } Future.successful(true) @@ -705,7 +705,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr try { association(to).sendControl(message) } catch { - case ShuttingDown ⇒ // silence it + case ShuttingDown => // silence it } override def send(message: Any, sender: OptionVal[ActorRef], recipient: RemoteActorRef): Unit = @@ -722,7 +722,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr a.send(message, sender, OptionVal.Some(recipient)) } catch { - case ShuttingDown ⇒ // silence it + case ShuttingDown => // silence it } override def association(remoteAddress: Address): Association = { @@ -739,7 +739,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr try { associationRegistry.setUID(peer).completeHandshake(peer) } catch { - case ShuttingDown ⇒ Future.successful(Done) // silence it + case ShuttingDown => Future.successful(Done) // silence it } } @@ -751,13 +751,13 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr try { association(remoteAddress).quarantine(reason, uid, harmless) } catch { - case ShuttingDown ⇒ // silence it + case ShuttingDown => // silence it } } def outboundLarge(outboundContext: OutboundContext): Sink[OutboundEnvelope, Future[Done]] = createOutboundSink(LargeStreamId, outboundContext, largeEnvelopeBufferPool) - .mapMaterializedValue { case (_, d) ⇒ d } + .mapMaterializedValue { case (_, d) => d } def outbound(outboundContext: OutboundContext): Sink[OutboundEnvelope, (OutboundCompressionAccess, Future[Done])] = createOutboundSink(OrdinaryStreamId, outboundContext, envelopeBufferPool) @@ -815,11 +815,11 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr def createDeserializer(bufferPool: EnvelopeBufferPool): Flow[InboundEnvelope, InboundEnvelope, NotUsed] = Flow.fromGraph(new Deserializer(this, system, bufferPool)) - val messageDispatcherSink: Sink[InboundEnvelope, Future[Done]] = Sink.foreach[InboundEnvelope] { m ⇒ + val messageDispatcherSink: Sink[InboundEnvelope, Future[Done]] = Sink.foreach[InboundEnvelope] { m => messageDispatcher.dispatch(m) m match { - case r: ReusableInboundEnvelope ⇒ inboundEnvelopePool.release(r) - case _ ⇒ + case r: ReusableInboundEnvelope => inboundEnvelopePool.release(r) + case _ => } } @@ -827,22 +827,22 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr // Purpose of this stage is flushing, the sender can wait for the ACKs up to try flushing // pending messages. def terminationHintReplier(inControlStream: Boolean): Flow[InboundEnvelope, InboundEnvelope, NotUsed] = { - Flow[InboundEnvelope].filter { envelope ⇒ + Flow[InboundEnvelope].filter { envelope => envelope.message match { - case ActorSystemTerminating(from) ⇒ + case ActorSystemTerminating(from) => envelope.sender match { - case OptionVal.Some(snd) ⇒ + case OptionVal.Some(snd) => snd.tell(ActorSystemTerminatingAck(localAddress), ActorRef.noSender) if (inControlStream) system.scheduler.scheduleOnce(settings.Advanced.ShutdownFlushTimeout) { if (!isShutdown) quarantine(from.address, Some(from.uid), "ActorSystem terminated", harmless = true) }(materializer.executionContext) - case OptionVal.None ⇒ + case OptionVal.None => log.error("Expected sender for ActorSystemTerminating message from [{}]", from) } false - case _ ⇒ true + case _ => true } } } @@ -896,11 +896,11 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr /** INTERNAL API: for testing only. */ private[remote] def triggerCompressionAdvertisements(actorRef: Boolean, manifest: Boolean) = { inboundCompressionAccess match { - case OptionVal.Some(c) if actorRef || manifest ⇒ + case OptionVal.Some(c) if actorRef || manifest => log.info("Triggering compression table advertisement for {}", c) if (actorRef) c.runNextActorRefAdvertisement() if (manifest) c.runNextClassManifestAdvertisement() - case _ ⇒ + case _ => } } @@ -952,9 +952,9 @@ private[remote] object ArteryTransport { def streamName(streamId: Int): String = streamId match { - case ControlStreamId ⇒ "control" - case LargeStreamId ⇒ "large message" - case _ ⇒ "message" + case ControlStreamId => "control" + case LargeStreamId => "large message" + case _ => "message" } } diff --git a/akka-remote/src/main/scala/akka/remote/artery/Association.scala b/akka-remote/src/main/scala/akka/remote/artery/Association.scala index 327e721275..9e932b128a 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/Association.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/Association.scala @@ -83,7 +83,7 @@ private[remote] object Association { override def isEnabled: Boolean = false } - final case class LazyQueueWrapper(queue: Queue[OutboundEnvelope], materialize: () ⇒ Unit) extends QueueWrapper { + final case class LazyQueueWrapper(queue: Queue[OutboundEnvelope], materialize: () => Unit) extends QueueWrapper { private val onlyOnce = new AtomicBoolean def runMaterialize(): Unit = { @@ -167,7 +167,7 @@ private[remote] class Association( else DisabledQueueWrapper - (0 until outboundLanes).foreach { i ⇒ + (0 until outboundLanes).foreach { i => queues(OrdinaryQueueIndex + i) = QueueWrapperImpl(createQueue(queueSize, OrdinaryQueueIndex + i)) // ordinary messages stream } @volatile private[this] var queuesVisibility = false @@ -185,44 +185,44 @@ private[remote] class Association( private[this] val stopQuarantinedTimer = new AtomicReference[Option[Cancellable]](None) private[remote] def changeActorRefCompression(table: CompressionTable[ActorRef]): Future[Done] = - updateOutboundCompression(c ⇒ c.changeActorRefCompression(table)) + updateOutboundCompression(c => c.changeActorRefCompression(table)) private[remote] def changeClassManifestCompression(table: CompressionTable[String]): Future[Done] = - updateOutboundCompression(c ⇒ c.changeClassManifestCompression(table)) + updateOutboundCompression(c => c.changeClassManifestCompression(table)) private def clearOutboundCompression(): Future[Done] = - updateOutboundCompression(c ⇒ c.clearCompression()) + updateOutboundCompression(c => c.clearCompression()) - private def updateOutboundCompression(action: OutboundCompressionAccess ⇒ Future[Done]): Future[Done] = { + private def updateOutboundCompression(action: OutboundCompressionAccess => Future[Done]): Future[Done] = { import transport.system.dispatcher val c = outboundCompressionAccess if (c.isEmpty) Future.successful(Done) else if (c.size == 1) action(c.head) - else Future.sequence(c.map(action(_))).map(_ ⇒ Done) + else Future.sequence(c.map(action(_))).map(_ => Done) } private def clearInboundCompression(originUid: Long): Unit = transport.inboundCompressionAccess match { - case OptionVal.Some(access) ⇒ access.closeCompressionFor(originUid) - case _ ⇒ // do nothing + case OptionVal.Some(access) => access.closeCompressionFor(originUid) + case _ => // do nothing } private def deadletters = transport.system.deadLetters def outboundControlIngress: OutboundControlIngress = { _outboundControlIngress match { - case OptionVal.Some(o) ⇒ o - case OptionVal.None ⇒ + case OptionVal.Some(o) => o + case OptionVal.None => controlQueue match { - case w: LazyQueueWrapper ⇒ w.runMaterialize() - case _ ⇒ + case w: LazyQueueWrapper => w.runMaterialize() + case _ => } // the outboundControlIngress may be accessed before the stream is materialized // using CountDownLatch to make sure that materialization is completed materializing.await(10, TimeUnit.SECONDS) _outboundControlIngress match { - case OptionVal.Some(o) ⇒ o - case OptionVal.None ⇒ + case OptionVal.Some(o) => o + case OptionVal.None => if (transport.isShutdown) throw ShuttingDown else throw new IllegalStateException("outboundControlIngress not initialized yet") } @@ -266,30 +266,30 @@ private[remote] class Association( val current = associationState current.uniqueRemoteAddressValue() match { - case Some(`peer`) ⇒ + case Some(`peer`) => // handshake already completed Future.successful(Done) - case _ ⇒ + case _ => // clear outbound compression, it's safe to do that several times if someone else // completes handshake at same time, but it's important to clear it before // we signal that the handshake is completed (uniqueRemoteAddressPromise.trySuccess) import transport.system.dispatcher - clearOutboundCompression().map { _ ⇒ + clearOutboundCompression().map { _ => current.uniqueRemoteAddressPromise.trySuccess(peer) current.uniqueRemoteAddressValue() match { - case Some(`peer`) ⇒ + case Some(`peer`) => // our value - case _ ⇒ + case _ => val newState = current.newIncarnation(Promise.successful(peer)) if (swapState(current, newState)) { current.uniqueRemoteAddressValue() match { - case Some(old) ⇒ + case Some(old) => cancelStopQuarantinedTimer() log.debug( "Incarnation {} of association to [{}] with new UID [{}] (old UID [{}])", newState.incarnation, peer.address, peer.uid, old.uid) clearInboundCompression(old.uid) - case None ⇒ + case None => // Failed, nothing to do } // if swap failed someone else completed before us, and that is fine @@ -312,7 +312,7 @@ private[remote] class Association( outboundControlIngress.sendControlMessage(message) } } catch { - case ShuttingDown ⇒ // silence it + case ShuttingDown => // silence it } } @@ -327,8 +327,8 @@ private[remote] class Association( def dropped(queueIndex: Int, qSize: Int, env: OutboundEnvelope): Unit = { val removed = isRemovedAfterQuarantined() if (removed) recipient match { - case OptionVal.Some(ref) ⇒ ref.cachedAssociation = null // don't use this Association instance any more - case OptionVal.None ⇒ + case OptionVal.Some(ref) => ref.cachedAssociation = null // don't use this Association instance any more + case OptionVal.None => } if (log.isDebugEnabled) { val reason = @@ -355,24 +355,24 @@ private[remote] class Association( try { val outboundEnvelope = createOutboundEnvelope() message match { - case _: SystemMessage ⇒ + case _: SystemMessage => if (!controlQueue.offer(outboundEnvelope)) { quarantine(reason = s"Due to overflow of control queue, size [$controlQueueSize]") dropped(ControlQueueIndex, controlQueueSize, outboundEnvelope) } - case ActorSelectionMessage(_: PriorityMessage, _, _) | _: ControlMessage | _: ClearSystemMessageDelivery ⇒ + case ActorSelectionMessage(_: PriorityMessage, _, _) | _: ControlMessage | _: ClearSystemMessageDelivery => // ActorSelectionMessage with PriorityMessage is used by cluster and remote failure detector heartbeating if (!controlQueue.offer(outboundEnvelope)) { dropped(ControlQueueIndex, controlQueueSize, outboundEnvelope) } - case _: DaemonMsgCreate ⇒ + case _: DaemonMsgCreate => // DaemonMsgCreate is not a SystemMessage, but must be sent over the control stream because // remote deployment process depends on message ordering for DaemonMsgCreate and Watch messages. // First ordinary message may arrive earlier but then the resolve in the Decoder is retried // so that the first message can be delivered after the remote actor has been created. if (!controlQueue.offer(outboundEnvelope)) dropped(ControlQueueIndex, controlQueueSize, outboundEnvelope) - case _ ⇒ + case _ => val queueIndex = selectQueue(recipient) val queue = queues(queueIndex) val offerOk = queue.offer(outboundEnvelope) @@ -380,7 +380,7 @@ private[remote] class Association( dropped(queueIndex, queueSize, outboundEnvelope) } } catch { - case ShuttingDown ⇒ // silence it + case ShuttingDown => // silence it } } else if (log.isDebugEnabled) log.debug( @@ -390,9 +390,9 @@ private[remote] class Association( private def selectQueue(recipient: OptionVal[RemoteActorRef]): Int = { recipient match { - case OptionVal.Some(r) ⇒ + case OptionVal.Some(r) => r.cachedSendQueueIndex match { - case -1 ⇒ + case -1 => // only happens when messages are sent to new remote destination // and is then cached on the RemoteActorRef val elements = r.path.elements @@ -411,10 +411,10 @@ private[remote] class Association( } r.cachedSendQueueIndex = idx idx - case idx ⇒ idx + case idx => idx } - case OptionVal.None ⇒ + case OptionVal.None => OrdinaryQueueIndex } } @@ -424,10 +424,10 @@ private[remote] class Association( def isStreamActive(queueIndex: Int): Boolean = { queues(queueIndex) match { - case _: LazyQueueWrapper ⇒ false - case DisabledQueueWrapper ⇒ false - case RemovedQueueWrapper ⇒ false - case _ ⇒ true + case _: LazyQueueWrapper => false + case DisabledQueueWrapper => false + case RemovedQueueWrapper => false + case _ => true } } @@ -435,7 +435,7 @@ private[remote] class Association( if (!associationState.isQuarantined()) { val msg = ActorSystemTerminating(localAddress) var sent = 0 - queues.iterator.filter(q ⇒ q.isEnabled && !q.isInstanceOf[LazyQueueWrapper]).foreach { queue ⇒ + queues.iterator.filter(q => q.isEnabled && !q.isInstanceOf[LazyQueueWrapper]).foreach { queue => try { val envelope = outboundEnvelopePool.acquire() .init(OptionVal.None, msg, OptionVal.Some(replyTo)) @@ -443,7 +443,7 @@ private[remote] class Association( queue.offer(envelope) sent += 1 } catch { - case ShuttingDown ⇒ // can be thrown if `offer` triggers new materialization + case ShuttingDown => // can be thrown if `offer` triggers new materialization } } sent @@ -458,10 +458,10 @@ private[remote] class Association( @tailrec final def quarantine(reason: String, uid: Option[Long], harmless: Boolean): Unit = { uid match { - case Some(u) ⇒ + case Some(u) => val current = associationState current.uniqueRemoteAddressValue() match { - case Some(peer) if peer.uid == u ⇒ + case Some(peer) if peer.uid == u => if (!current.isQuarantined(u)) { val newState = current.newQuarantined() if (swapState(current, newState)) { @@ -493,17 +493,17 @@ private[remote] class Association( } else quarantine(reason, uid, harmless) // recursive } - case Some(peer) ⇒ + case Some(peer) => log.info( "Quarantine of [{}] ignored due to non-matching UID, quarantine requested for [{}] but current is [{}]. {}", remoteAddress, u, peer.uid, reason) send(ClearSystemMessageDelivery(current.incarnation - 1), OptionVal.None, OptionVal.None) - case None ⇒ + case None => log.info( "Quarantine of [{}] ignored because handshake not completed, quarantine request was for old incarnation. {}", remoteAddress, reason) } - case None ⇒ + case None => log.warning("Quarantine of [{}] ignored because unknown UID", remoteAddress) } @@ -520,7 +520,7 @@ private[remote] class Association( if (transport.largeMessageChannelEnabled) queues(LargeQueueIndex) = RemovedQueueWrapper - (0 until outboundLanes).foreach { i ⇒ + (0 until outboundLanes).foreach { i => queues(OrdinaryQueueIndex + i) = RemovedQueueWrapper } queuesVisibility = true // volatile write for visibility of the queues array @@ -555,13 +555,13 @@ private[remote] class Association( private def abortQuarantined(): Unit = { cancelIdleTimer() streamMatValues.get.foreach { - case (queueIndex, OutboundStreamMatValues(killSwitch, _, _)) ⇒ + case (queueIndex, OutboundStreamMatValues(killSwitch, _, _)) => killSwitch match { - case OptionVal.Some(k) ⇒ + case OptionVal.Some(k) => setStopReason(queueIndex, OutboundStreamStopQuarantinedSignal) clearStreamKillSwitch(queueIndex, k) k.abort(OutboundStreamStopQuarantinedSignal) - case OptionVal.None ⇒ // already aborted + case OptionVal.None => // already aborted } } } @@ -586,30 +586,30 @@ private[remote] class Association( quarantine(s"Idle longer than quarantine-idle-outbound-after [${QuarantineIdleOutboundAfter.pretty}]") } else if (lastUsedDurationNanos >= StopIdleOutboundAfter.toNanos) { streamMatValues.get.foreach { - case (queueIndex, OutboundStreamMatValues(streamKillSwitch, _, stopping)) ⇒ + case (queueIndex, OutboundStreamMatValues(streamKillSwitch, _, stopping)) => if (isStreamActive(queueIndex) && stopping.isEmpty) { if (queueIndex != ControlQueueIndex) { streamKillSwitch match { - case OptionVal.Some(k) ⇒ + case OptionVal.Some(k) => // for non-control streams we can stop the entire stream log.info("Stopping idle outbound stream [{}] to [{}]", queueIndex, remoteAddress) flightRecorder.loFreq(Transport_StopIdleOutbound, s"$remoteAddress - $queueIndex") setStopReason(queueIndex, OutboundStreamStopIdleSignal) clearStreamKillSwitch(queueIndex, k) k.abort(OutboundStreamStopIdleSignal) - case OptionVal.None ⇒ // already aborted + case OptionVal.None => // already aborted } } else { // only stop the transport parts of the stream because SystemMessageDelivery stage has // state (seqno) and system messages might be sent at the same time associationState.controlIdleKillSwitch match { - case OptionVal.Some(killSwitch) ⇒ + case OptionVal.Some(killSwitch) => log.info("Stopping idle outbound control stream to [{}]", remoteAddress) flightRecorder.loFreq(Transport_StopIdleOutbound, s"$remoteAddress - $queueIndex") setControlIdleKillSwitch(OptionVal.None) killSwitch.abort(OutboundStreamStopIdleSignal) - case OptionVal.None ⇒ // already stopped + case OptionVal.None => // already stopped } } } @@ -670,7 +670,7 @@ private[remote] class Association( def sendQueuePostStop[T](pending: Vector[OutboundEnvelope]): Unit = { sendToDeadLetters(pending) - val systemMessagesCount = pending.count(env ⇒ env.message.isInstanceOf[SystemMessage]) + val systemMessagesCount = pending.count(env => env.message.isInstanceOf[SystemMessage]) if (systemMessagesCount > 0) quarantine(s"SendQueue stopped with [$systemMessagesCount] pending system messages.") } @@ -691,14 +691,14 @@ private[remote] class Association( updateStreamMatValues(ControlQueueIndex, streamKillSwitch, completed) setupIdleTimer() attachOutboundStreamRestart("Outbound control stream", ControlQueueIndex, controlQueueSize, - completed, () ⇒ runOutboundControlStream()) + completed, () => runOutboundControlStream()) } private def getOrCreateQueueWrapper(queueIndex: Int, capacity: Int): QueueWrapper = { val unused = queuesVisibility // volatile read to see latest queues array queues(queueIndex) match { - case existing: QueueWrapper ⇒ existing - case _ ⇒ + case existing: QueueWrapper => existing + case _ => // use new queue for restarts QueueWrapperImpl(createQueue(capacity, queueIndex)) } @@ -720,7 +720,7 @@ private[remote] class Association( Source.fromGraph(new SendQueue[OutboundEnvelope](sendToDeadLetters)) .via(streamKillSwitch.flow) .viaMat(transport.outboundTestFlow(this))(Keep.both) - .toMat(transport.outbound(this))({ case ((a, b), (c, d)) ⇒ (a, b, c, d) }) // "keep all, exploded" + .toMat(transport.outbound(this))({ case ((a, b), (c, d)) => (a, b, c, d) }) // "keep all, exploded" .run()(materializer) queueValue.inject(wrapper.queue) @@ -731,11 +731,11 @@ private[remote] class Association( updateStreamMatValues(OrdinaryQueueIndex, streamKillSwitch, completed) attachOutboundStreamRestart("Outbound message stream", OrdinaryQueueIndex, queueSize, - completed, () ⇒ runOutboundOrdinaryMessagesStream()) + completed, () => runOutboundOrdinaryMessagesStream()) } else { log.debug("Starting outbound message stream to [{}] with [{}] lanes", remoteAddress, outboundLanes) - val wrappers = (0 until outboundLanes).map { i ⇒ + val wrappers = (0 until outboundLanes).map { i => val wrapper = getOrCreateQueueWrapper(OrdinaryQueueIndex + i, queueSize) queues(OrdinaryQueueIndex + i) = wrapper // use new underlying queue immediately for restarts queuesVisibility = true // volatile write for visibility of the queues array @@ -748,9 +748,9 @@ private[remote] class Association( .viaMat(transport.outboundLane(this))(Keep.both) .watchTermination()(Keep.both) // recover to avoid error logging by MergeHub - .recoverWithRetries(-1, { case _: Throwable ⇒ Source.empty }) + .recoverWithRetries(-1, { case _: Throwable => Source.empty }) .mapMaterializedValue { - case ((q, c), w) ⇒ (q, c, w) + case ((q, c), w) => (q, c, w) } val (mergeHub, transportSinkCompleted) = MergeHub.source[EnvelopeBuffer] @@ -758,7 +758,7 @@ private[remote] class Association( .toMat(transport.outboundTransportSink(this))(Keep.both).run()(materializer) val values: Vector[(SendQueue.QueueValue[OutboundEnvelope], Encoder.OutboundCompressionAccess, Future[Done])] = - (0 until outboundLanes).iterator.map { _ ⇒ + (0 until outboundLanes).iterator.map { _ => lane.to(mergeHub).run()(materializer) }.to(Vector) @@ -767,15 +767,15 @@ private[remote] class Association( import transport.system.dispatcher // tear down all parts if one part fails or completes - Future.firstCompletedOf(laneCompletedValues).failed.foreach { reason ⇒ + Future.firstCompletedOf(laneCompletedValues).failed.foreach { reason => streamKillSwitch.abort(reason) } - (laneCompletedValues :+ transportSinkCompleted).foreach(_.foreach { _ ⇒ streamKillSwitch.shutdown() }) + (laneCompletedValues :+ transportSinkCompleted).foreach(_.foreach { _ => streamKillSwitch.shutdown() }) - val allCompleted = Future.sequence(laneCompletedValues).flatMap(_ ⇒ transportSinkCompleted) + val allCompleted = Future.sequence(laneCompletedValues).flatMap(_ => transportSinkCompleted) queueValues.zip(wrappers).zipWithIndex.foreach { - case ((q, w), i) ⇒ + case ((q, w), i) => q.inject(w.queue) queues(OrdinaryQueueIndex + i) = q // replace with the materialized value, still same underlying queue } @@ -784,7 +784,7 @@ private[remote] class Association( outboundCompressionAccess = compressionAccessValues attachOutboundStreamRestart("Outbound message stream", OrdinaryQueueIndex, queueSize, - allCompleted, () ⇒ runOutboundOrdinaryMessagesStream()) + allCompleted, () => runOutboundOrdinaryMessagesStream()) } } @@ -810,11 +810,11 @@ private[remote] class Association( updateStreamMatValues(LargeQueueIndex, streamKillSwitch, completed) attachOutboundStreamRestart("Outbound large message stream", LargeQueueIndex, largeQueueSize, - completed, () ⇒ runOutboundLargeMessagesStream()) + completed, () => runOutboundLargeMessagesStream()) } private def attachOutboundStreamRestart(streamName: String, queueIndex: Int, queueCapacity: Int, - streamCompleted: Future[Done], restart: () ⇒ Unit): Unit = { + streamCompleted: Future[Done], restart: () => Unit): Unit = { def lazyRestart(): Unit = { flightRecorder.loFreq(Transport_RestartOutbound, s"$remoteAddress - $streamName") @@ -824,7 +824,7 @@ private[remote] class Association( _outboundControlIngress = OptionVal.None } // LazyQueueWrapper will invoke the `restart` function when first message is offered - val wrappedRestartFun: () ⇒ Unit = () ⇒ { + val wrappedRestartFun: () => Unit = () => { restart() } @@ -835,18 +835,18 @@ private[remote] class Association( } implicit val ec = materializer.executionContext - streamCompleted.foreach { _ ⇒ + streamCompleted.foreach { _ => // shutdown as expected // countDown the latch in case threads are waiting on the latch in outboundControlIngress method materializing.countDown() } streamCompleted.failed.foreach { - case ArteryTransport.ShutdownSignal ⇒ + case ArteryTransport.ShutdownSignal => // shutdown as expected cancelAllTimers() // countDown the latch in case threads are waiting on the latch in outboundControlIngress method materializing.countDown() - case cause if transport.isShutdown || isRemovedAfterQuarantined() ⇒ + case cause if transport.isShutdown || isRemovedAfterQuarantined() => // don't restart after shutdown, but log some details so we notice // for the TCP transport the ShutdownSignal is "converted" to StreamTcpException if (!cause.isInstanceOf[StreamTcpException]) @@ -854,13 +854,13 @@ private[remote] class Association( cancelAllTimers() // countDown the latch in case threads are waiting on the latch in outboundControlIngress method materializing.countDown() - case _: AeronTerminated ⇒ + case _: AeronTerminated => // shutdown already in progress cancelAllTimers() - case _: AbruptTerminationException ⇒ + case _: AbruptTerminationException => // ActorSystem shutdown cancelAllTimers() - case cause ⇒ + case cause => // it might have been stopped as expected due to idle or quarantine // for the TCP transport the exception is "converted" to StreamTcpException @@ -871,14 +871,14 @@ private[remote] class Association( // for some cases restart unconditionally, without counting restarts val bypassRestartCounter = cause match { - case _: GaveUpMessageException ⇒ true - case _ ⇒ stoppedIdle || stoppedQuarantined + case _: GaveUpMessageException => true + case _ => stoppedIdle || stoppedQuarantined } if (queueIndex == ControlQueueIndex && !stoppedQuarantined) { cause match { - case _: HandshakeTimeoutException ⇒ // ok, quarantine not possible without UID - case _ ⇒ + case _: HandshakeTimeoutException => // ok, quarantine not possible without UID + case _ => // Must quarantine in case all system messages haven't been delivered. // See also comment in the stoppedIdle case below quarantine(s"Outbound control stream restarted. $cause") @@ -908,13 +908,13 @@ private[remote] class Association( implicit val ec = materializer.executionContext updateStreamMatValues( streamId, - OutboundStreamMatValues(OptionVal.Some(streamKillSwitch), completed.recover { case _ ⇒ Done }, + OutboundStreamMatValues(OptionVal.Some(streamKillSwitch), completed.recover { case _ => Done }, stopping = OptionVal.None)) } @tailrec private def updateStreamMatValues(streamId: Int, values: OutboundStreamMatValues): Unit = { val prev = streamMatValues.get() - if (!streamMatValues.compareAndSet(prev, prev + (streamId → values))) { + if (!streamMatValues.compareAndSet(prev, prev + (streamId -> values))) { updateStreamMatValues(streamId, values) } } @@ -922,17 +922,17 @@ private[remote] class Association( @tailrec private def setStopReason(streamId: Int, stopSignal: StopSignal): Unit = { val prev = streamMatValues.get() prev.get(streamId) match { - case Some(v) ⇒ + case Some(v) => if (!streamMatValues.compareAndSet(prev, prev.updated(streamId, v.copy(stopping = OptionVal.Some(stopSignal))))) setStopReason(streamId, stopSignal) - case None ⇒ throw new IllegalStateException(s"Expected streamMatValues for [$streamId]") + case None => throw new IllegalStateException(s"Expected streamMatValues for [$streamId]") } } private def getStopReason(streamId: Int): OptionVal[StopSignal] = { streamMatValues.get().get(streamId) match { - case Some(OutboundStreamMatValues(_, _, stopping)) ⇒ stopping - case None ⇒ OptionVal.None + case Some(OutboundStreamMatValues(_, _, stopping)) => stopping + case None => OptionVal.None } } @@ -941,12 +941,12 @@ private[remote] class Association( @tailrec private def clearStreamKillSwitch(streamId: Int, old: SharedKillSwitch): Unit = { val prev = streamMatValues.get() prev.get(streamId) match { - case Some(v) ⇒ + case Some(v) => if (v.streamKillSwitch.isDefined && (v.streamKillSwitch.get eq old)) { if (!streamMatValues.compareAndSet(prev, prev.updated(streamId, v.copy(streamKillSwitch = OptionVal.None)))) clearStreamKillSwitch(streamId, old) } - case None ⇒ throw new IllegalStateException(s"Expected streamMatValues for [$streamId]") + case None => throw new IllegalStateException(s"Expected streamMatValues for [$streamId]") } } @@ -957,8 +957,8 @@ private[remote] class Association( def streamsCompleted: Future[Done] = { implicit val ec = materializer.executionContext Future.sequence(streamMatValues.get().values.map { - case OutboundStreamMatValues(_, done, _) ⇒ done - }).map(_ ⇒ Done) + case OutboundStreamMatValues(_, done, _) => done + }).map(_ => Done) } override def toString: String = @@ -969,7 +969,7 @@ private[remote] class Association( /** * INTERNAL API */ -private[remote] class AssociationRegistry(createAssociation: Address ⇒ Association) { +private[remote] class AssociationRegistry(createAssociation: Address => Association) { private[this] val associationsByAddress = new AtomicReference[Map[Address, Association]](Map.empty) private[this] val associationsByUid = new AtomicReference[ImmutableLongMap[Association]](ImmutableLongMap.empty) @@ -979,8 +979,8 @@ private[remote] class AssociationRegistry(createAssociation: Address ⇒ Associa @tailrec final def association(remoteAddress: Address): Association = { val currentMap = associationsByAddress.get currentMap.get(remoteAddress) match { - case Some(existing) ⇒ existing - case None ⇒ + case Some(existing) => existing + case None => val newAssociation = createAssociation(remoteAddress) val newMap = currentMap.updated(remoteAddress, newAssociation) if (associationsByAddress.compareAndSet(currentMap, newMap)) { @@ -1003,14 +1003,14 @@ private[remote] class AssociationRegistry(createAssociation: Address ⇒ Associa val currentMap = associationsByUid.get currentMap.get(peer.uid) match { - case OptionVal.Some(previous) ⇒ + case OptionVal.Some(previous) => if (previous eq a) // associationsByUid Map already contains the right association a else // make sure we don't overwrite same UID with different association throw new IllegalArgumentException(s"UID collision old [$previous] new [$a]") - case _ ⇒ + case _ => // update associationsByUid Map with the uid -> association val newMap = currentMap.updated(peer.uid, a) if (associationsByUid.compareAndSet(currentMap, newMap)) @@ -1033,7 +1033,7 @@ private[remote] class AssociationRegistry(createAssociation: Address ⇒ Associa val afterNanos = after.toNanos val currentMap = associationsByAddress.get val remove = currentMap.foldLeft(Map.empty[Address, Association]) { - case (acc, (address, association)) ⇒ + case (acc, (address, association)) => val state = association.associationState if (state.isQuarantined() && ((now - state.lastUsedTimestamp.get) >= afterNanos)) acc.updated(address, association) @@ -1054,14 +1054,14 @@ private[remote] class AssociationRegistry(createAssociation: Address ⇒ Associa val afterNanos = after.toNanos val currentMap = associationsByUid.get var remove = Map.empty[Long, Association] - currentMap.keysIterator.foreach { uid ⇒ + currentMap.keysIterator.foreach { uid => val association = currentMap.get(uid).get val state = association.associationState if (state.isQuarantined() && ((now - state.lastUsedTimestamp.get) >= afterNanos)) remove = remove.updated(uid, association) } if (remove.nonEmpty) { - val newMap = remove.keysIterator.foldLeft(currentMap)((acc, uid) ⇒ acc.remove(uid)) + val newMap = remove.keysIterator.foldLeft(currentMap)((acc, uid) => acc.remove(uid)) if (associationsByUid.compareAndSet(currentMap, newMap)) remove.valuesIterator.foreach(_.removedAfterQuarantined()) else diff --git a/akka-remote/src/main/scala/akka/remote/artery/Codecs.scala b/akka-remote/src/main/scala/akka/remote/artery/Codecs.scala index 43f833265f..b5cc1ab2b7 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/Codecs.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/Codecs.scala @@ -63,8 +63,8 @@ private[remote] class Encoder( // lazy init of SerializationExtension to avoid loading serializers before ActorRefProvider has been initialized private var _serialization: OptionVal[Serialization] = OptionVal.None private def serialization: Serialization = _serialization match { - case OptionVal.Some(s) ⇒ s - case OptionVal.None ⇒ + case OptionVal.Some(s) => s + case OptionVal.None => val s = SerializationExtension(system) _serialization = OptionVal.Some(s) s @@ -72,15 +72,15 @@ private[remote] class Encoder( private val instruments: RemoteInstruments = RemoteInstruments(system) - private val changeActorRefCompressionCb = getAsyncCallback[CompressionTable[ActorRef]] { table ⇒ + private val changeActorRefCompressionCb = getAsyncCallback[CompressionTable[ActorRef]] { table => headerBuilder.setOutboundActorRefCompression(table) } - private val changeClassManifsetCompressionCb = getAsyncCallback[CompressionTable[String]] { table ⇒ + private val changeClassManifsetCompressionCb = getAsyncCallback[CompressionTable[String]] { table => headerBuilder.setOutboundClassManifestCompression(table) } - private val clearCompressionCb = getAsyncCallback[Unit] { _ ⇒ + private val clearCompressionCb = getAsyncCallback[Unit] { _ => headerBuilder.setOutboundActorRefCompression(CompressionTable.empty[ActorRef]) headerBuilder.setOutboundClassManifestCompression(CompressionTable.empty[String]) } @@ -111,13 +111,13 @@ private[remote] class Encoder( // internally compression is applied by the builder: outboundEnvelope.recipient match { - case OptionVal.Some(r) ⇒ headerBuilder.setRecipientActorRef(r) - case OptionVal.None ⇒ headerBuilder.setNoRecipient() + case OptionVal.Some(r) => headerBuilder.setRecipientActorRef(r) + case OptionVal.None => headerBuilder.setNoRecipient() } outboundEnvelope.sender match { - case OptionVal.None ⇒ headerBuilder.setNoSender() - case OptionVal.Some(s) ⇒ headerBuilder.setSenderActorRef(s) + case OptionVal.None => headerBuilder.setNoSender() + case OptionVal.Some(s) => headerBuilder.setSenderActorRef(s) } val startTime: Long = if (instruments.timeSerialization) System.nanoTime else 0 @@ -141,29 +141,29 @@ private[remote] class Encoder( push(out, envelope) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => bufferPool.release(envelope) outboundEnvelope.message match { - case _: SystemMessageEnvelope ⇒ + case _: SystemMessageEnvelope => log.error(e, "Failed to serialize system message [{}].", Logging.messageClassName(outboundEnvelope.message)) throw e - case _ if e.isInstanceOf[java.nio.BufferOverflowException] ⇒ + case _ if e.isInstanceOf[java.nio.BufferOverflowException] => val reason = new OversizedPayloadException("Discarding oversized payload sent to " + s"${outboundEnvelope.recipient}: max allowed size ${envelope.byteBuffer.limit()} " + s"bytes. Message type [${Logging.messageClassName(outboundEnvelope.message)}].") log.error(reason, "Failed to serialize oversized message [{}].", Logging.messageClassName(outboundEnvelope.message)) pull(in) - case _ ⇒ + case _ => log.error(e, "Failed to serialize message [{}].", Logging.messageClassName(outboundEnvelope.message)) pull(in) } } finally { Serialization.currentTransportInformation.value = oldInfo outboundEnvelope match { - case r: ReusableOutboundEnvelope ⇒ outboundEnvelopePool.release(r) - case _ ⇒ // no need to release it + case r: ReusableOutboundEnvelope => outboundEnvelopePool.release(r) + case _ => // no need to release it } } } @@ -222,28 +222,28 @@ private[remote] object Decoder { } private[remote] trait InboundCompressionAccessImpl extends InboundCompressionAccess { - this: GraphStageLogic with StageLogging ⇒ + this: GraphStageLogic with StageLogging => def compressions: InboundCompressions - private val closeCompressionForCb = getAsyncCallback[Long] { uid ⇒ + private val closeCompressionForCb = getAsyncCallback[Long] { uid => compressions.close(uid) } private val confirmActorRefCompressionAdvertisementCb = getAsyncCallback[ActorRefCompressionAdvertisementAck] { - case ActorRefCompressionAdvertisementAck(from, tableVersion) ⇒ + case ActorRefCompressionAdvertisementAck(from, tableVersion) => compressions.confirmActorRefCompressionAdvertisement(from.uid, tableVersion) } private val confirmClassManifestCompressionAdvertisementCb = getAsyncCallback[ClassManifestCompressionAdvertisementAck] { - case ClassManifestCompressionAdvertisementAck(from, tableVersion) ⇒ + case ClassManifestCompressionAdvertisementAck(from, tableVersion) => compressions.confirmClassManifestCompressionAdvertisement(from.uid, tableVersion) } private val runNextActorRefAdvertisementCb = getAsyncCallback[Unit] { - _ ⇒ compressions.runNextActorRefAdvertisement() + _ => compressions.runNextActorRefAdvertisement() } private val runNextClassManifestAdvertisementCb = getAsyncCallback[Unit] { - _ ⇒ compressions.runNextClassManifestAdvertisement() + _ => compressions.runNextClassManifestAdvertisement() } - private val currentCompressionOriginUidsCb = getAsyncCallback[Promise[Set[Long]]] { p ⇒ + private val currentCompressionOriginUidsCb = getAsyncCallback[Promise[Set[Long]]] { p => p.success(compressions.currentOriginUids) } @@ -352,12 +352,12 @@ private[remote] class Decoder( if (settings.Advanced.Compression.Enabled) { settings.Advanced.Compression.ActorRefs.AdvertisementInterval match { - case d: FiniteDuration ⇒ schedulePeriodicallyWithInitialDelay(AdvertiseActorRefsCompressionTable, d, d) - case _ ⇒ // not advertising actor ref compressions + case d: FiniteDuration => schedulePeriodicallyWithInitialDelay(AdvertiseActorRefsCompressionTable, d, d) + case _ => // not advertising actor ref compressions } settings.Advanced.Compression.Manifests.AdvertisementInterval match { - case d: FiniteDuration ⇒ schedulePeriodicallyWithInitialDelay(AdvertiseClassManifestsCompressionTable, d, d) - case _ ⇒ // not advertising class manifest compressions + case d: FiniteDuration => schedulePeriodicallyWithInitialDelay(AdvertiseClassManifestsCompressionTable, d, d) + case _ => // not advertising class manifest compressions } } } @@ -371,35 +371,35 @@ private[remote] class Decoder( val association = inboundContext.association(originUid) val recipient: OptionVal[InternalActorRef] = try headerBuilder.recipientActorRef(originUid) match { - case OptionVal.Some(ref) ⇒ + case OptionVal.Some(ref) => OptionVal(ref.asInstanceOf[InternalActorRef]) - case OptionVal.None if headerBuilder.recipientActorRefPath.isDefined ⇒ + case OptionVal.None if headerBuilder.recipientActorRefPath.isDefined => resolveRecipient(headerBuilder.recipientActorRefPath.get) - case _ ⇒ + case _ => OptionVal.None } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // probably version mismatch due to restarted system log.warning("Couldn't decompress sender from originUid [{}]. {}", originUid, e) OptionVal.None } val sender: OptionVal[InternalActorRef] = try headerBuilder.senderActorRef(originUid) match { - case OptionVal.Some(ref) ⇒ + case OptionVal.Some(ref) => OptionVal(ref.asInstanceOf[InternalActorRef]) - case OptionVal.None if headerBuilder.senderActorRefPath.isDefined ⇒ + case OptionVal.None if headerBuilder.senderActorRefPath.isDefined => OptionVal(actorRefResolver.getOrCompute(headerBuilder.senderActorRefPath.get)) - case _ ⇒ + case _ => OptionVal.None } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // probably version mismatch due to restarted system log.warning("Couldn't decompress sender from originUid [{}]. {}", originUid, e) OptionVal.None } val classManifestOpt = try headerBuilder.manifest(originUid) catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // probably version mismatch due to restarted system log.warning("Couldn't decompress manifest from originUid [{}]. {}", originUid, e) OptionVal.None @@ -424,23 +424,23 @@ private[remote] class Decoder( if ((messageCount & heavyHitterMask) == 0) { // --- hit refs and manifests for heavy-hitter counting association match { - case OptionVal.Some(assoc) ⇒ + case OptionVal.Some(assoc) => val remoteAddress = assoc.remoteAddress sender match { - case OptionVal.Some(snd) ⇒ + case OptionVal.Some(snd) => compressions.hitActorRef(originUid, remoteAddress, snd, 1) - case OptionVal.None ⇒ + case OptionVal.None => } recipient match { - case OptionVal.Some(rcp) ⇒ + case OptionVal.Some(rcp) => compressions.hitActorRef(originUid, remoteAddress, rcp, 1) - case OptionVal.None ⇒ + case OptionVal.None => } compressions.hitClassManifest(originUid, remoteAddress, classManifest, 1) - case _ ⇒ + case _ => // we don't want to record hits for compression while handshake is still in progress. log.debug("Decoded message but unable to record hits for compression as no remoteAddress known. No association yet?") } @@ -470,13 +470,13 @@ private[remote] class Decoder( if (bannedRemoteDeployedActorRefs.contains(recipientActorRefPath)) { headerBuilder.recipientActorRefPath match { - case OptionVal.Some(path) ⇒ + case OptionVal.Some(path) => val ref = actorRefResolver.getOrCompute(path) if (ref.isInstanceOf[EmptyLocalActorRef]) log.warning( "Message for banned (terminated, unresolved) remote deployed recipient [{}].", recipientActorRefPath) push(out, decoded.withRecipient(ref)) - case OptionVal.None ⇒ + case OptionVal.None => log.warning( "Dropping message for banned (terminated, unresolved) remote deployed recipient [{}].", recipientActorRefPath) @@ -492,18 +492,18 @@ private[remote] class Decoder( } } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning("Dropping message due to: {}", e) pull(in) } private def resolveRecipient(path: String): OptionVal[InternalActorRef] = { actorRefResolver.getOrCompute(path) match { - case empty: EmptyLocalActorRef ⇒ + case empty: EmptyLocalActorRef => val pathElements = empty.path.elements if (pathElements.nonEmpty && pathElements.head == "remote") OptionVal.None else OptionVal(empty) - case ref ⇒ OptionVal(ref) + case ref => OptionVal(ref) } } @@ -511,7 +511,7 @@ private[remote] class Decoder( override protected def onTimer(timerKey: Any): Unit = { timerKey match { - case Tick ⇒ + case Tick => val now = System.nanoTime() val d = math.max(1, now - tickTimestamp) val rate = (messageCount - tickMessageCount) * TimeUnit.SECONDS.toNanos(1) / d @@ -528,15 +528,15 @@ private[remote] class Decoder( tickMessageCount = messageCount tickTimestamp = now - case AdvertiseActorRefsCompressionTable ⇒ + case AdvertiseActorRefsCompressionTable => compressions.runNextActorRefAdvertisement() // TODO: optimise these operations, otherwise they stall the hotpath - case AdvertiseClassManifestsCompressionTable ⇒ + case AdvertiseClassManifestsCompressionTable => compressions.runNextClassManifestAdvertisement() // TODO: optimise these operations, otherwise they stall the hotpath - case RetryResolveRemoteDeployedRecipient(attemptsLeft, recipientPath, inboundEnvelope) ⇒ + case RetryResolveRemoteDeployedRecipient(attemptsLeft, recipientPath, inboundEnvelope) => resolveRecipient(recipientPath) match { - case OptionVal.None ⇒ + case OptionVal.None => if (attemptsLeft > 0) scheduleOnce(RetryResolveRemoteDeployedRecipient( attemptsLeft - 1, @@ -555,7 +555,7 @@ private[remote] class Decoder( val recipient = actorRefResolver.getOrCompute(recipientPath) push(out, inboundEnvelope.withRecipient(recipient)) } - case OptionVal.Some(recipient) ⇒ + case OptionVal.Some(recipient) => push(out, inboundEnvelope.withRecipient(recipient)) } } @@ -588,8 +588,8 @@ private[remote] class Deserializer( // lazy init of SerializationExtension to avoid loading serializers before ActorRefProvider has been initialized private var _serialization: OptionVal[Serialization] = OptionVal.None private def serialization: Serialization = _serialization match { - case OptionVal.Some(s) ⇒ s - case OptionVal.None ⇒ + case OptionVal.Some(s) => s + case OptionVal.None => val s = SerializationExtension(system) _serialization = OptionVal.Some(s) s @@ -615,10 +615,10 @@ private[remote] class Deserializer( } push(out, envelopeWithMessage) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => val from = envelope.association match { - case OptionVal.Some(a) ⇒ a.remoteAddress - case OptionVal.None ⇒ "unknown" + case OptionVal.Some(a) => a.remoteAddress + case OptionVal.None => "unknown" } log.warning( "Failed to deserialize message from [{}] with serializer id [{}] and manifest [{}]. {}", @@ -683,7 +683,7 @@ private[remote] class DuplicateHandshakeReq( if (envelope.association.isEmpty && envelope.serializer == serializerId && envelope.classManifest == manifest) { // only need to duplicate HandshakeReq before handshake is completed try { - currentIterator = Vector.tabulate(numberOfLanes)(i ⇒ envelope.copyForLane(i)).iterator + currentIterator = Vector.tabulate(numberOfLanes)(i => envelope.copyForLane(i)).iterator push(out, currentIterator.next()) } finally { val buf = envelope.envelopeBuffer diff --git a/akka-remote/src/main/scala/akka/remote/artery/Control.scala b/akka-remote/src/main/scala/akka/remote/artery/Control.scala index f2e3c4176f..981a17a46b 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/Control.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/Control.scala @@ -101,10 +101,10 @@ private[remote] class InboundControlJunction private var observers: Vector[ControlMessageObserver] = Vector.empty private val callback = getAsyncCallback[CallbackMessage] { - case Attach(observer, done) ⇒ + case Attach(observer, done) => observers :+= observer done.success(Done) - case Dettach(observer) ⇒ + case Dettach(observer) => observers = observers.filterNot(_ == observer) } @@ -116,10 +116,10 @@ private[remote] class InboundControlJunction // InHandler override def onPush(): Unit = { grab(in) match { - case env: InboundEnvelope if env.message.isInstanceOf[ControlMessage] ⇒ + case env: InboundEnvelope if env.message.isInstanceOf[ControlMessage] => observers.foreach(_.notify(env)) pull(in) - case env ⇒ + case env => push(out, env) } } diff --git a/akka-remote/src/main/scala/akka/remote/artery/FixedSizePartitionHub.scala b/akka-remote/src/main/scala/akka/remote/artery/FixedSizePartitionHub.scala index 239a172973..95a33b0e5c 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/FixedSizePartitionHub.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/FixedSizePartitionHub.scala @@ -12,12 +12,12 @@ import org.agrona.concurrent.OneToOneConcurrentArrayQueue * INTERNAL API */ @InternalApi private[akka] class FixedSizePartitionHub[T]( - partitioner: T ⇒ Int, + partitioner: T => Int, lanes: Int, bufferSize: Int) extends PartitionHub[T]( // during tear down or restart it's possible that some streams have been removed // and then we must drop elements (return -1) - () ⇒ (info, elem) ⇒ if (info.size < lanes) -1 else info.consumerIdByIdx(partitioner(elem)), + () => (info, elem) => if (info.size < lanes) -1 else info.consumerIdByIdx(partitioner(elem)), lanes, bufferSize - 1) { // -1 because of the Completed token diff --git a/akka-remote/src/main/scala/akka/remote/artery/FlightRecorder.scala b/akka-remote/src/main/scala/akka/remote/artery/FlightRecorder.scala index caf7f5f379..a4e0080c3b 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/FlightRecorder.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/FlightRecorder.scala @@ -149,7 +149,7 @@ private[remote] class RollingEventLogSection( require((entryCount & (entryCount - 1)) == 0, "entryCount must be power of two") private[this] val LogMask: Long = entryCount - 1L - private[this] val buffers: Array[MappedResizeableBuffer] = Array.tabulate(FlightRecorder.SnapshotCount) { logId ⇒ + private[this] val buffers: Array[MappedResizeableBuffer] = Array.tabulate(FlightRecorder.SnapshotCount) { logId => val buffer = new MappedResizeableBuffer(fileChannel, offset + logId * logBufferSize, logBufferSize) // Clear old data buffer.setMemory(0, logBufferSize.toInt, 0.toByte) @@ -210,9 +210,9 @@ private[remote] object FlightRecorder { // TODO safer file permissions (e.g. only user readable on POSIX)? destination match { // not defined, use temporary directory - case "" ⇒ Files.createTempFile("artery", ".afr") + case "" => Files.createTempFile("artery", ".afr") - case directory if directory.endsWith(".afr") ⇒ + case directory if directory.endsWith(".afr") => val path = fs.getPath(directory).toAbsolutePath if (!Files.exists(path)) { Files.createDirectories(path.getParent) @@ -220,7 +220,7 @@ private[remote] object FlightRecorder { } path - case directory ⇒ + case directory => val path = fs.getPath(directory).toAbsolutePath if (!Files.exists(path)) Files.createDirectories(path) @@ -356,8 +356,8 @@ private[remote] class FlightRecorder(val fileChannel: FileChannel) extends Atomi def close(): Unit = { getAndSet(ShutDown) match { - case SnapshotInProgress(latch) ⇒ latch.await(3, TimeUnit.SECONDS) - case _ ⇒ // Nothing to unlock + case SnapshotInProgress(latch) => latch.await(3, TimeUnit.SECONDS) + case _ => // Nothing to unlock } alertLogs.close() hiFreqLogs.close() diff --git a/akka-remote/src/main/scala/akka/remote/artery/FlightRecorderEvents.scala b/akka-remote/src/main/scala/akka/remote/artery/FlightRecorderEvents.scala index de84b44d17..bbc19eb1d4 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/FlightRecorderEvents.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/FlightRecorderEvents.scala @@ -70,20 +70,20 @@ private[remote] object FlightRecorderEvents { // Used for presentation of the entries in the flight recorder lazy val eventDictionary = Map( - Transport_MediaDriverStarted → "Transport: Media driver started", - Transport_Started → "Transport: started", - Transport_AeronErrorLogStarted → "Transport: Aeron error log started", - Transport_TaskRunnerStarted → "Transport: Task runner started", - Transport_UniqueAddressSet → "Transport: Unique address set", - Transport_MaterializerStarted → "Transport: Materializer started", - Transport_StartupFinished → "Transport: Startup finished", - Transport_OnAvailableImage → "Transport: onAvailableImage", - Transport_KillSwitchPulled → "Transport: KillSwitch pulled", - Transport_Stopped → "Transport: Stopped", - Transport_AeronErrorLogTaskStopped → "Transport: Aeron errorLog task stopped", - Transport_MediaFileDeleted → "Transport: Media file deleted", - Transport_FlightRecorderClose → "Transport: Flight recorder closed", - Transport_SendQueueOverflow → "Transport: Send queue overflow", + Transport_MediaDriverStarted -> "Transport: Media driver started", + Transport_Started -> "Transport: started", + Transport_AeronErrorLogStarted -> "Transport: Aeron error log started", + Transport_TaskRunnerStarted -> "Transport: Task runner started", + Transport_UniqueAddressSet -> "Transport: Unique address set", + Transport_MaterializerStarted -> "Transport: Materializer started", + Transport_StartupFinished -> "Transport: Startup finished", + Transport_OnAvailableImage -> "Transport: onAvailableImage", + Transport_KillSwitchPulled -> "Transport: KillSwitch pulled", + Transport_Stopped -> "Transport: Stopped", + Transport_AeronErrorLogTaskStopped -> "Transport: Aeron errorLog task stopped", + Transport_MediaFileDeleted -> "Transport: Media file deleted", + Transport_FlightRecorderClose -> "Transport: Flight recorder closed", + Transport_SendQueueOverflow -> "Transport: Send queue overflow", Transport_StopIdleOutbound -> "Transport: Remove idle outbound", Transport_Quarantined -> "Transport: Quarantined association", Transport_RemovedQuarantined -> "Transport: Removed idle quarantined association", @@ -91,30 +91,30 @@ private[remote] object FlightRecorderEvents { Transport_RestartInbound -> "Transport: Restart outbound", // Aeron Sink events - AeronSink_Started → "AeronSink: Started", - AeronSink_TaskRunnerRemoved → "AeronSink: Task runner removed", - AeronSink_PublicationClosed → "AeronSink: Publication closed", - AeronSink_Stopped → "AeronSink: Stopped", - AeronSink_EnvelopeGrabbed → "AeronSink: Envelope grabbed", - AeronSink_EnvelopeOffered → "AeronSink: Envelope offered", - AeronSink_GaveUpEnvelope → "AeronSink: Gave up envelope", - AeronSink_DelegateToTaskRunner → "AeronSink: Delegate to task runner", - AeronSink_ReturnFromTaskRunner → "AeronSink: Return from task runner", + AeronSink_Started -> "AeronSink: Started", + AeronSink_TaskRunnerRemoved -> "AeronSink: Task runner removed", + AeronSink_PublicationClosed -> "AeronSink: Publication closed", + AeronSink_Stopped -> "AeronSink: Stopped", + AeronSink_EnvelopeGrabbed -> "AeronSink: Envelope grabbed", + AeronSink_EnvelopeOffered -> "AeronSink: Envelope offered", + AeronSink_GaveUpEnvelope -> "AeronSink: Gave up envelope", + AeronSink_DelegateToTaskRunner -> "AeronSink: Delegate to task runner", + AeronSink_ReturnFromTaskRunner -> "AeronSink: Return from task runner", // Aeron Source events - AeronSource_Started → "AeronSource: Started", - AeronSource_Stopped → "AeronSource: Stopped", - AeronSource_Received → "AeronSource: Received", - AeronSource_DelegateToTaskRunner → "AeronSource: Delegate to task runner", - AeronSource_ReturnFromTaskRunner → "AeronSource: Return from task runner", + AeronSource_Started -> "AeronSource: Started", + AeronSource_Stopped -> "AeronSource: Stopped", + AeronSource_Received -> "AeronSource: Received", + AeronSource_DelegateToTaskRunner -> "AeronSource: Delegate to task runner", + AeronSource_ReturnFromTaskRunner -> "AeronSource: Return from task runner", // Compression events - Compression_CompressedActorRef → "Compression: Compressed ActorRef", - Compression_AllocatedActorRefCompressionId → "Compression: Allocated ActorRef compression id", - Compression_CompressedManifest → "Compression: Compressed manifest", - Compression_AllocatedManifestCompressionId → "Compression: Allocated manifest compression id", - Compression_Inbound_RunActorRefAdvertisement → "InboundCompression: Run class manifest compression advertisement", - Compression_Inbound_RunClassManifestAdvertisement → "InboundCompression: Run class manifest compression advertisement", + Compression_CompressedActorRef -> "Compression: Compressed ActorRef", + Compression_AllocatedActorRefCompressionId -> "Compression: Allocated ActorRef compression id", + Compression_CompressedManifest -> "Compression: Compressed manifest", + Compression_AllocatedManifestCompressionId -> "Compression: Allocated manifest compression id", + Compression_Inbound_RunActorRefAdvertisement -> "InboundCompression: Run class manifest compression advertisement", + Compression_Inbound_RunClassManifestAdvertisement -> "InboundCompression: Run class manifest compression advertisement", // TCP outbound events TcpOutbound_Connected -> "TCP out: Connected", @@ -126,6 +126,6 @@ private[remote] object FlightRecorderEvents { TcpInbound_Connected -> "TCP in: New connection", TcpInbound_Received -> "TCP in: Received message" - ).map { case (int, str) ⇒ int.toLong → str } + ).map { case (int, str) => int.toLong -> str } } diff --git a/akka-remote/src/main/scala/akka/remote/artery/FlightRecorderReader.scala b/akka-remote/src/main/scala/akka/remote/artery/FlightRecorderReader.scala index 22d6e4bc03..f4f8666984 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/FlightRecorderReader.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/FlightRecorderReader.scala @@ -91,7 +91,7 @@ private[akka] object FlightRecorderReader { val hiFreq: Seq[FlightRecorderReader#Entry] = reader.structure.hiFreqLog.logs.flatMap(_.compactEntries) val loFreq: Seq[FlightRecorderReader#Entry] = reader.structure.loFreqLog.logs.flatMap(_.richEntries) - implicit val ordering = Ordering.fromLessThan[FlightRecorderReader#Entry]((a, b) ⇒ a.timeStamp.isBefore(b.timeStamp)) + implicit val ordering = Ordering.fromLessThan[FlightRecorderReader#Entry]((a, b) => a.timeStamp.isBefore(b.timeStamp)) val sorted = SortedSet[FlightRecorderReader#Entry](alerts: _*) ++ hiFreq ++ loFreq println("--- FLIGHT RECORDER LOG") @@ -247,7 +247,7 @@ private[akka] final class FlightRecorderReader(fileChannel: FileChannel) { } private def readRollingLog(sectionParameters: SectionParameters): RollingLog = { - val logs = Vector.tabulate(SnapshotCount) { idx ⇒ + val logs = Vector.tabulate(SnapshotCount) { idx => readLog(idx, sectionParameters.offset + (idx * sectionParameters.logSize), sectionParameters) } RollingLog(sectionParameters, logs) @@ -255,10 +255,10 @@ private[akka] final class FlightRecorderReader(fileChannel: FileChannel) { private def readLog(id: Int, offset: Long, sectionParameters: SectionParameters): Log = { val state = fileBuffer.getLong(offset + RollingEventLogSection.LogStateOffset) match { - case RollingEventLogSection.Empty ⇒ Empty - case RollingEventLogSection.Live ⇒ Live - case RollingEventLogSection.Snapshot ⇒ Snapshot - case other ⇒ throw new IOException(s"Unrecognized log state: $other in log at offset $offset") + case RollingEventLogSection.Empty => Empty + case RollingEventLogSection.Live => Live + case RollingEventLogSection.Snapshot => Snapshot + case other => throw new IOException(s"Unrecognized log state: $other in log at offset $offset") } Log(sectionParameters, offset, id, state, fileBuffer.getLong(offset + RollingEventLogSection.HeadPointerOffset)) } diff --git a/akka-remote/src/main/scala/akka/remote/artery/Handshake.scala b/akka-remote/src/main/scala/akka/remote/artery/Handshake.scala index e60c7eccf4..14d06c0c77 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/Handshake.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/Handshake.scala @@ -75,8 +75,8 @@ private[remote] class OutboundHandshake( override def preStart(): Unit = { scheduleOnce(HandshakeTimeout, timeout) livenessProbeInterval match { - case d: FiniteDuration ⇒ schedulePeriodically(LivenessProbeTick, d) - case _ ⇒ // only used in control stream + case d: FiniteDuration => schedulePeriodically(LivenessProbeTick, d) + case _ => // only used in control stream } } @@ -105,17 +105,17 @@ private[remote] class OutboundHandshake( // OutHandler override def onPull(): Unit = { handshakeState match { - case Completed ⇒ + case Completed => pendingMessage match { - case OptionVal.None ⇒ + case OptionVal.None => if (!hasBeenPulled(in)) pull(in) - case OptionVal.Some(p) ⇒ + case OptionVal.Some(p) => push(out, p) pendingMessage = OptionVal.None } - case Start ⇒ + case Start => val uniqueRemoteAddress = outboundContext.associationState.uniqueRemoteAddress if (uniqueRemoteAddress.isCompleted) { handshakeCompleted() @@ -128,7 +128,7 @@ private[remote] class OutboundHandshake( // when it receives the HandshakeRsp reply implicit val ec = materializer.executionContext uniqueRemoteAddress.foreach { - getAsyncCallback[UniqueAddress] { _ ⇒ + getAsyncCallback[UniqueAddress] { _ => if (handshakeState != Completed) { handshakeCompleted() if (isAvailable(out)) @@ -141,7 +141,7 @@ private[remote] class OutboundHandshake( // always push a HandshakeReq as the first message pushHandshakeReq() - case ReqInProgress ⇒ // will pull when handshake reply is received + case ReqInProgress => // will pull when handshake reply is received } } @@ -181,15 +181,15 @@ private[remote] class OutboundHandshake( override protected def onTimer(timerKey: Any): Unit = timerKey match { - case InjectHandshakeTick ⇒ + case InjectHandshakeTick => // next onPush message will trigger sending of HandshakeReq injectHandshakeTickScheduled = false - case LivenessProbeTick ⇒ + case LivenessProbeTick => pushLivenessProbeReq() - case HandshakeRetryTick ⇒ + case HandshakeRetryTick => if (isAvailable(out)) pushHandshakeReq() - case HandshakeTimeout ⇒ + case HandshakeTimeout => failStage(new HandshakeTimeoutException( s"Handshake with [${outboundContext.remoteAddress}] did not complete within ${timeout.toMillis} ms")) } @@ -217,8 +217,8 @@ private[remote] class InboundHandshake(inboundContext: InboundContext, inControl override def onPush(): Unit = { val env = grab(in) env.message match { - case HandshakeReq(from, to) ⇒ onHandshakeReq(from, to) - case HandshakeRsp(from) ⇒ + case HandshakeReq(from, to) => onHandshakeReq(from, to) + case HandshakeRsp(from) => // Touch the lastUsedTimestamp here also because when sending the extra low frequency HandshakeRsp // the timestamp is not supposed to be updated when sending but when receiving reply, which confirms // that the other system is alive. @@ -227,7 +227,7 @@ private[remote] class InboundHandshake(inboundContext: InboundContext, inControl after(inboundContext.completeHandshake(from)) { pull(in) } - case _ ⇒ + case _ => onMessage(env) } } @@ -237,8 +237,8 @@ private[remote] class InboundHandshake(inboundContext: InboundContext, inControl override def onPush(): Unit = { val env = grab(in) env.message match { - case HandshakeReq(from, to) ⇒ onHandshakeReq(from, to) - case _ ⇒ + case HandshakeReq(from, to) => onHandshakeReq(from, to) + case _ => onMessage(env) } } @@ -263,17 +263,17 @@ private[remote] class InboundHandshake(inboundContext: InboundContext, inControl } } - private def after(first: Future[Done])(thenInside: ⇒ Unit): Unit = { + private def after(first: Future[Done])(thenInside: => Unit): Unit = { first.value match { - case Some(_) ⇒ + case Some(_) => // This in the normal case (all but the first). The future will be completed // because handshake was already completed. Note that we send those HandshakeReq // periodically. thenInside - case None ⇒ + case None => implicit val ec = materializer.executionContext - first.onComplete { _ ⇒ - getAsyncCallback[Done](_ ⇒ thenInside).invoke(Done) + first.onComplete { _ => + getAsyncCallback[Done](_ => thenInside).invoke(Done) } } diff --git a/akka-remote/src/main/scala/akka/remote/artery/ImmutableLongMap.scala b/akka-remote/src/main/scala/akka/remote/artery/ImmutableLongMap.scala index be639acee2..d0afcc0170 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/ImmutableLongMap.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/ImmutableLongMap.scala @@ -106,7 +106,7 @@ private[akka] class ImmutableLongMap[A >: Null] private ( keys.iterator override def toString: String = - keysIterator.map(key ⇒ s"$key -> ${get(key).get}").mkString("ImmutableLongMap(", ", ", ")") + keysIterator.map(key => s"$key -> ${get(key).get}").mkString("ImmutableLongMap(", ", ", ")") override def hashCode: Int = { var result = HashCode.SEED @@ -116,7 +116,7 @@ private[akka] class ImmutableLongMap[A >: Null] private ( } override def equals(obj: Any): Boolean = obj match { - case other: ImmutableLongMap[A] ⇒ + case other: ImmutableLongMap[A] => if (other eq this) true else if (size != other.size) false else if (size == 0 && other.size == 0) true @@ -129,6 +129,6 @@ private[akka] class ImmutableLongMap[A >: Null] private ( } check(0) } - case _ ⇒ false + case _ => false } } diff --git a/akka-remote/src/main/scala/akka/remote/artery/InboundEnvelope.scala b/akka-remote/src/main/scala/akka/remote/artery/InboundEnvelope.scala index 493804170b..962ecff2b6 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/InboundEnvelope.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/InboundEnvelope.scala @@ -62,7 +62,7 @@ private[remote] trait InboundEnvelope extends NoSerializationVerificationNeeded private[remote] object ReusableInboundEnvelope { def createObjectPool(capacity: Int) = new ObjectPool[ReusableInboundEnvelope]( capacity, - create = () ⇒ new ReusableInboundEnvelope, clear = inEnvelope ⇒ inEnvelope.asInstanceOf[ReusableInboundEnvelope].clear()) + create = () => new ReusableInboundEnvelope, clear = inEnvelope => inEnvelope.asInstanceOf[ReusableInboundEnvelope].clear()) } /** diff --git a/akka-remote/src/main/scala/akka/remote/artery/InboundQuarantineCheck.scala b/akka-remote/src/main/scala/akka/remote/artery/InboundQuarantineCheck.scala index 107d61a492..d8453d7591 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/InboundQuarantineCheck.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/InboundQuarantineCheck.scala @@ -32,10 +32,10 @@ private[remote] class InboundQuarantineCheck(inboundContext: InboundContext) ext override def onPush(): Unit = { val env = grab(in) env.association match { - case OptionVal.None ⇒ + case OptionVal.None => // unknown, handshake not completed push(out, env) - case OptionVal.Some(association) ⇒ + case OptionVal.Some(association) => if (association.associationState.isQuarantined(env.originUid)) { if (log.isDebugEnabled) log.debug( @@ -53,9 +53,9 @@ private[remote] class InboundQuarantineCheck(inboundContext: InboundContext) ext } private def isHeartbeat(msg: Any): Boolean = msg match { - case _: HeartbeatMessage ⇒ true - case ActorSelectionMessage(_: HeartbeatMessage, _, _) ⇒ true - case _ ⇒ false + case _: HeartbeatMessage => true + case ActorSelectionMessage(_: HeartbeatMessage, _, _) => true + case _ => false } // OutHandler diff --git a/akka-remote/src/main/scala/akka/remote/artery/MessageDispatcher.scala b/akka-remote/src/main/scala/akka/remote/artery/MessageDispatcher.scala index 7d8ec2cff8..55d1a240c9 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/MessageDispatcher.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/MessageDispatcher.scala @@ -36,15 +36,15 @@ private[remote] class MessageDispatcher( val message = inboundEnvelope.message val senderOption = inboundEnvelope.sender val originAddress = inboundEnvelope.association match { - case OptionVal.Some(a) ⇒ OptionVal.Some(a.remoteAddress) - case OptionVal.None ⇒ OptionVal.None + case OptionVal.Some(a) => OptionVal.Some(a.remoteAddress) + case OptionVal.None => OptionVal.None } val sender: ActorRef = senderOption.getOrElse(system.deadLetters) recipient match { - case `remoteDaemon` ⇒ + case `remoteDaemon` => if (UntrustedMode) { if (debugLogEnabled) log.debug( LogMarker.Security, @@ -57,12 +57,12 @@ private[remote] class MessageDispatcher( remoteDaemon ! message } - case l @ (_: LocalRef | _: RepointableRef) if l.isLocal ⇒ + case l @ (_: LocalRef | _: RepointableRef) if l.isLocal => if (LogReceive && debugLogEnabled) log.debug( "received message [{}] to [{}] from [{}]", message, recipient, senderOption.getOrElse("")) message match { - case sel: ActorSelectionMessage ⇒ + case sel: ActorSelectionMessage => if (UntrustedMode && (!TrustedSelectionPaths.contains(sel.elements.mkString("/", "/", "")) || sel.msg.isInstanceOf[PossiblyHarmful] || l != provider.rootGuardian)) { if (debugLogEnabled) log.debug( @@ -73,23 +73,23 @@ private[remote] class MessageDispatcher( } else // run the receive logic for ActorSelectionMessage here to make sure it is not stuck on busy user actor ActorSelection.deliverSelection(l, sender, sel) - case msg: PossiblyHarmful if UntrustedMode ⇒ + case msg: PossiblyHarmful if UntrustedMode => if (debugLogEnabled) log.debug( LogMarker.Security, "operating in UntrustedMode, dropping inbound PossiblyHarmful message of type [{}] to [{}] from [{}]", messageClassName(msg), recipient, senderOption.getOrElse(originAddress.getOrElse(""))) - case msg: SystemMessage ⇒ l.sendSystemMessage(msg) - case msg ⇒ l.!(msg)(sender) + case msg: SystemMessage => l.sendSystemMessage(msg) + case msg => l.!(msg)(sender) } - case r @ (_: RemoteRef | _: RepointableRef) if !r.isLocal && !UntrustedMode ⇒ + case r @ (_: RemoteRef | _: RepointableRef) if !r.isLocal && !UntrustedMode => if (LogReceive && debugLogEnabled) log.debug( "received remote-destined message [{}] to [{}] from [{}]", message, recipient, senderOption.getOrElse(originAddress.getOrElse(""))) // if it was originally addressed to us but is in fact remote from our point of view (i.e. remote-deployed) r.!(message)(sender) - case r ⇒ log.error( + case r => log.error( "dropping message [{}] for unknown recipient [{}] from [{}]", messageClassName(message), r, senderOption.getOrElse(originAddress.getOrElse(""))) diff --git a/akka-remote/src/main/scala/akka/remote/artery/ObjectPool.scala b/akka-remote/src/main/scala/akka/remote/artery/ObjectPool.scala index 466d62698d..36a455f08f 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/ObjectPool.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/ObjectPool.scala @@ -9,7 +9,7 @@ import org.agrona.concurrent.ManyToManyConcurrentArrayQueue /** * INTERNAL API */ -private[remote] class ObjectPool[A <: AnyRef](capacity: Int, create: () ⇒ A, clear: A ⇒ Unit) { +private[remote] class ObjectPool[A <: AnyRef](capacity: Int, create: () => A, clear: A => Unit) { private val pool = new ManyToManyConcurrentArrayQueue[A](capacity) def acquire(): A = { diff --git a/akka-remote/src/main/scala/akka/remote/artery/OutboundEnvelope.scala b/akka-remote/src/main/scala/akka/remote/artery/OutboundEnvelope.scala index 444f64b78d..fc14ae8749 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/OutboundEnvelope.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/OutboundEnvelope.scala @@ -42,7 +42,7 @@ private[remote] trait OutboundEnvelope extends NoSerializationVerificationNeeded private[remote] object ReusableOutboundEnvelope { def createObjectPool(capacity: Int) = new ObjectPool[ReusableOutboundEnvelope]( capacity, - create = () ⇒ new ReusableOutboundEnvelope, clear = outEnvelope ⇒ outEnvelope.clear()) + create = () => new ReusableOutboundEnvelope, clear = outEnvelope => outEnvelope.clear()) } /** diff --git a/akka-remote/src/main/scala/akka/remote/artery/RemoteInstrument.scala b/akka-remote/src/main/scala/akka/remote/artery/RemoteInstrument.scala index cb03435d33..02f8d32796 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/RemoteInstrument.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/RemoteInstrument.scala @@ -121,7 +121,7 @@ private[remote] final class RemoteInstruments( try { serializeInstrument(instrument, oe, buffer) } catch { - case NonFatal(t) ⇒ + case NonFatal(t) => log.debug( "Skipping serialization of RemoteInstrument {} since it failed with {}", instrument.identifier, t.getMessage) @@ -138,7 +138,7 @@ private[remote] final class RemoteInstruments( buffer.putInt(startPos, endPos - dataPos) } } catch { - case NonFatal(t) ⇒ + case NonFatal(t) => log.debug("Skipping serialization of all RemoteInstruments due to unhandled failure {}", t) buffer.position(startPos) } @@ -187,7 +187,7 @@ private[remote] final class RemoteInstruments( try { deserializeInstrument(instrument, inboundEnvelope, buffer) } catch { - case NonFatal(t) ⇒ + case NonFatal(t) => log.debug( "Skipping deserialization of RemoteInstrument {} since it failed with {}", instrument.identifier, t.getMessage) @@ -210,7 +210,7 @@ private[remote] final class RemoteInstruments( remoteInstrumentIdIteratorRaw(buffer, endPos).mkString("[", ", ", "]")) } } catch { - case NonFatal(t) ⇒ + case NonFatal(t) => log.debug("Skipping further deserialization of remaining RemoteInstruments due to unhandled failure {}", t) } finally { buffer.position(endPos) @@ -228,7 +228,7 @@ private[remote] final class RemoteInstruments( try { messageSentInstrument(instrument, outboundEnvelope, size, time) } catch { - case NonFatal(t) ⇒ + case NonFatal(t) => log.debug("Message sent in RemoteInstrument {} failed with {}", instrument.identifier, t.getMessage) } messageSent(pos + 1) @@ -248,7 +248,7 @@ private[remote] final class RemoteInstruments( try { messageReceivedInstrument(instrument, inboundEnvelope, size, time) } catch { - case NonFatal(t) ⇒ + case NonFatal(t) => log.debug("Message received in RemoteInstrument {} failed with {}", instrument.identifier, t.getMessage) } messageRecieved(pos + 1) @@ -294,10 +294,10 @@ private[remote] object RemoteInstruments { val c = system.settings.config val path = "akka.remote.artery.advanced.instruments" import scala.collection.JavaConverters._ - c.getStringList(path).asScala.iterator.map { fqcn ⇒ + c.getStringList(path).asScala.iterator.map { fqcn => system .dynamicAccess.createInstanceFor[RemoteInstrument](fqcn, Nil) - .orElse(system.dynamicAccess.createInstanceFor[RemoteInstrument](fqcn, List(classOf[ExtendedActorSystem] → system))) + .orElse(system.dynamicAccess.createInstanceFor[RemoteInstrument](fqcn, List(classOf[ExtendedActorSystem] -> system))) .get }.to(immutable.Vector) } diff --git a/akka-remote/src/main/scala/akka/remote/artery/SendQueue.scala b/akka-remote/src/main/scala/akka/remote/artery/SendQueue.scala index a5149f4399..93af187d4b 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/SendQueue.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/SendQueue.scala @@ -41,7 +41,7 @@ private[remote] object SendQueue { /** * INTERNAL API */ -private[remote] final class SendQueue[T](postStopAction: Vector[T] ⇒ Unit) +private[remote] final class SendQueue[T](postStopAction: Vector[T] => Unit) extends GraphStageWithMaterializedValue[SourceShape[T], SendQueue.QueueValue[T]] { import SendQueue._ @@ -57,7 +57,7 @@ private[remote] final class SendQueue[T](postStopAction: Vector[T] ⇒ Unit) // using a local field for the consumer side of queue to avoid volatile access private var consumerQueue: Queue[T] = null - private val wakeupCallback = getAsyncCallback[Unit] { _ ⇒ + private val wakeupCallback = getAsyncCallback[Unit] { _ => if (isAvailable(out)) tryPush() } @@ -65,12 +65,12 @@ private[remote] final class SendQueue[T](postStopAction: Vector[T] ⇒ Unit) override def preStart(): Unit = { implicit val ec = materializer.executionContext queuePromise.future.onComplete(getAsyncCallback[Try[Queue[T]]] { - case Success(q) ⇒ + case Success(q) => consumerQueue = q needWakeup = true if (isAvailable(out)) tryPush() - case Failure(e) ⇒ + case Failure(e) => failStage(e) }.invoke) } @@ -82,13 +82,13 @@ private[remote] final class SendQueue[T](postStopAction: Vector[T] ⇒ Unit) @tailrec private def tryPush(firstAttempt: Boolean = true): Unit = { consumerQueue.poll() match { - case null ⇒ + case null => needWakeup = true // additional poll() to grab any elements that might missed the needWakeup // and have been enqueued just after it if (firstAttempt) tryPush(firstAttempt = false) - case elem ⇒ + case elem => needWakeup = false // there will be another onPull push(out, elem) } diff --git a/akka-remote/src/main/scala/akka/remote/artery/SystemMessageDelivery.scala b/akka-remote/src/main/scala/akka/remote/artery/SystemMessageDelivery.scala index fa504f2080..d296c52c32 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/SystemMessageDelivery.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/SystemMessageDelivery.scala @@ -106,7 +106,7 @@ import akka.util.OptionVal override def preStart(): Unit = { implicit val ec = materializer.executionContext outboundContext.controlSubject.attach(this).foreach { - getAsyncCallback[Done] { _ ⇒ + getAsyncCallback[Done] { _ => replyObserverAttached = true if (isAvailable(out)) pull(in) // onPull from downstream already called @@ -132,7 +132,7 @@ import akka.util.OptionVal override protected def onTimer(timerKey: Any): Unit = timerKey match { - case ResendTick ⇒ + case ResendTick => checkGiveUp() if (resending.isEmpty && !unacknowledged.isEmpty) { resending = unacknowledged.clone() @@ -145,25 +145,25 @@ import akka.util.OptionVal // ControlMessageObserver, external call override def notify(inboundEnvelope: InboundEnvelope): Unit = { inboundEnvelope.message match { - case ack: Ack ⇒ if (ack.from.address == remoteAddress) ackCallback.invoke(ack) - case nack: Nack ⇒ if (nack.from.address == remoteAddress) nackCallback.invoke(nack) - case _ ⇒ // not interested + case ack: Ack => if (ack.from.address == remoteAddress) ackCallback.invoke(ack) + case nack: Nack => if (nack.from.address == remoteAddress) nackCallback.invoke(nack) + case _ => // not interested } } // ControlMessageObserver, external call override def controlSubjectCompleted(signal: Try[Done]): Unit = { getAsyncCallback[Try[Done]] { - case Success(_) ⇒ completeStage() - case Failure(cause) ⇒ failStage(cause) + case Success(_) => completeStage() + case Failure(cause) => failStage(cause) }.invoke(signal) } - private val ackCallback = getAsyncCallback[Ack] { reply ⇒ + private val ackCallback = getAsyncCallback[Ack] { reply => ack(reply.seqNo) } - private val nackCallback = getAsyncCallback[Nack] { reply ⇒ + private val nackCallback = getAsyncCallback[Nack] { reply => if (reply.seqNo <= seqNo) { ack(reply.seqNo) log.warning( @@ -200,9 +200,9 @@ import akka.util.OptionVal if (log.isDebugEnabled) { env.message match { - case SystemMessageEnvelope(msg, n, _) ⇒ + case SystemMessageEnvelope(msg, n, _) => log.debug("Resending system message [{}] [{}]", Logging.simpleName(msg), n) - case _ ⇒ + case _ => log.debug("Resending control message [{}]", Logging.simpleName(env.message)) } } @@ -225,7 +225,7 @@ import akka.util.OptionVal override def onPush(): Unit = { val outboundEnvelope = grab(in) outboundEnvelope.message match { - case msg @ (_: SystemMessage | _: AckedDeliveryMessage) ⇒ + case msg @ (_: SystemMessage | _: AckedDeliveryMessage) => if (unacknowledged.size < maxBufferSize) { if (seqNo == 0) { incarnation = outboundContext.associationState.incarnation @@ -253,17 +253,17 @@ import akka.util.OptionVal deadLetters ! outboundEnvelope pull(in) } - case _: HandshakeReq ⇒ + case _: HandshakeReq => // pass on HandshakeReq if (isAvailable(out)) pushCopy(outboundEnvelope) - case ClearSystemMessageDelivery(i) ⇒ + case ClearSystemMessageDelivery(i) => if (i <= incarnation) { log.debug("Clear system message delivery of [{}]", remoteAddressLogParam) clear() } pull(in) - case _ ⇒ + case _ => // e.g. ActorSystemTerminating or ActorSelectionMessage with PriorityMessage, no need for acked delivery if (resending.isEmpty && isAvailable(out)) push(out, outboundEnvelope) @@ -346,15 +346,15 @@ import akka.util.OptionVal // for logging def fromRemoteAddressStr: String = env.association match { - case OptionVal.Some(a) ⇒ a.remoteAddress.toString - case OptionVal.None ⇒ "N/A" + case OptionVal.Some(a) => a.remoteAddress.toString + case OptionVal.None => "N/A" } env.message match { - case sysEnv @ SystemMessageEnvelope(_, n, ackReplyTo) ⇒ + case sysEnv @ SystemMessageEnvelope(_, n, ackReplyTo) => val expectedSeqNo = sequenceNumbers.get(ackReplyTo) match { - case None ⇒ 1L - case Some(seqNo) ⇒ seqNo + case None => 1L + case Some(seqNo) => seqNo } if (n == expectedSeqNo) { inboundContext.sendControl(ackReplyTo.address, Ack(n, localAddress)) @@ -382,7 +382,7 @@ import akka.util.OptionVal inboundContext.sendControl(ackReplyTo.address, Nack(expectedSeqNo - 1, localAddress)) pull(in) } - case _ ⇒ + case _ => // messages that don't need acking push(out, env) } diff --git a/akka-remote/src/main/scala/akka/remote/artery/TestStage.scala b/akka-remote/src/main/scala/akka/remote/artery/TestStage.scala index 8b02c5d23e..9b2acf01c0 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/TestStage.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/TestStage.scala @@ -33,16 +33,16 @@ private[remote] class SharedTestState { def isBlackhole(from: Address, to: Address): Boolean = state.get.blackholes.get(from) match { - case Some(destinations) ⇒ destinations(to) - case None ⇒ false + case Some(destinations) => destinations(to) + case None => false } /** Enable blackholing between given address in given direction */ def blackhole(a: Address, b: Address, direction: Direction): Unit = direction match { - case Direction.Send ⇒ addBlackhole(a, b) - case Direction.Receive ⇒ addBlackhole(b, a) - case Direction.Both ⇒ + case Direction.Send => addBlackhole(a, b) + case Direction.Receive => addBlackhole(b, a) + case Direction.Both => addBlackhole(a, b) addBlackhole(b, a) } @@ -69,8 +69,8 @@ private[remote] class SharedTestState { @tailrec private def addBlackhole(from: Address, to: Address): Unit = { val current = state.get val newState = current.blackholes.get(from) match { - case Some(destinations) ⇒ current.copy(blackholes = current.blackholes.updated(from, destinations + to)) - case None ⇒ current.copy(blackholes = current.blackholes.updated(from, Set(to))) + case Some(destinations) => current.copy(blackholes = current.blackholes.updated(from, destinations + to)) + case None => current.copy(blackholes = current.blackholes.updated(from, Set(to))) } if (!state.compareAndSet(current, newState)) addBlackhole(from, to) @@ -78,9 +78,9 @@ private[remote] class SharedTestState { def passThrough(a: Address, b: Address, direction: Direction): Unit = direction match { - case Direction.Send ⇒ removeBlackhole(a, b) - case Direction.Receive ⇒ removeBlackhole(b, a) - case Direction.Both ⇒ + case Direction.Send => removeBlackhole(a, b) + case Direction.Receive => removeBlackhole(b, a) + case Direction.Both => removeBlackhole(a, b) removeBlackhole(b, a) } @@ -88,8 +88,8 @@ private[remote] class SharedTestState { @tailrec private def removeBlackhole(from: Address, to: Address): Unit = { val current = state.get val newState = current.blackholes.get(from) match { - case Some(destinations) ⇒ current.copy(blackholes = current.blackholes.updated(from, destinations - to)) - case None ⇒ current + case Some(destinations) => current.copy(blackholes = current.blackholes.updated(from, destinations - to)) + case None => current } if (!state.compareAndSet(current, newState)) removeBlackhole(from, to) @@ -151,16 +151,16 @@ private[remote] class InboundTestStage(inboundContext: InboundContext, state: Sh // InHandler override def onPush(): Unit = { state.getInboundFailureOnce match { - case Some(shouldFailEx) ⇒ + case Some(shouldFailEx) => log.info("Fail inbound stream from [{}]: {}", classOf[InboundTestStage].getName, shouldFailEx.getMessage) failStage(shouldFailEx) - case _ ⇒ + case _ => val env = grab(in) env.association match { - case OptionVal.None ⇒ + case OptionVal.None => // unknown, handshake not completed push(out, env) - case OptionVal.Some(association) ⇒ + case OptionVal.Some(association) => if (state.isBlackhole(inboundContext.localAddress.address, association.remoteAddress)) { log.debug( "dropping inbound message [{}] from [{}] with UID [{}] because of blackhole", diff --git a/akka-remote/src/main/scala/akka/remote/artery/aeron/AeronSink.scala b/akka-remote/src/main/scala/akka/remote/artery/aeron/AeronSink.scala index b13f7bc346..c333ecadfd 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/aeron/AeronSink.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/aeron/AeronSink.scala @@ -41,10 +41,10 @@ private[remote] object AeronSink { private final class OfferTask(pub: Publication, var buffer: UnsafeBuffer, var msgSize: Int, onOfferSuccess: AsyncCallback[Unit], giveUpAfter: Duration, onGiveUp: AsyncCallback[Unit], onPublicationClosed: AsyncCallback[Unit]) - extends (() ⇒ Boolean) { + extends (() => Boolean) { val giveUpAfterNanos = giveUpAfter match { - case f: FiniteDuration ⇒ f.toNanos - case _ ⇒ -1L + case f: FiniteDuration => f.toNanos + case _ => -1L } var n = 0L var startTime = 0L @@ -108,8 +108,8 @@ private[remote] class AeronSink( private val spinning = 2 * taskRunner.idleCpuLevel private var backoffCount = spinning private var lastMsgSize = 0 - private val offerTask = new OfferTask(pub, null, lastMsgSize, getAsyncCallback(_ ⇒ taskOnOfferSuccess()), - giveUpAfter, getAsyncCallback(_ ⇒ onGiveUp()), getAsyncCallback(_ ⇒ onPublicationClosed())) + private val offerTask = new OfferTask(pub, null, lastMsgSize, getAsyncCallback(_ => taskOnOfferSuccess()), + giveUpAfter, getAsyncCallback(_ => onGiveUp()), getAsyncCallback(_ => onPublicationClosed())) private val addOfferTask: Add = Add(offerTask) private var offerTaskInProgress = false diff --git a/akka-remote/src/main/scala/akka/remote/artery/aeron/AeronSource.scala b/akka-remote/src/main/scala/akka/remote/artery/aeron/AeronSource.scala index 9067478340..f5df9c6511 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/aeron/AeronSource.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/aeron/AeronSource.scala @@ -30,8 +30,8 @@ import scala.concurrent.{ Future, Promise } */ private[remote] object AeronSource { - private def pollTask(sub: Subscription, handler: MessageHandler, onMessage: AsyncCallback[EnvelopeBuffer]): () ⇒ Boolean = { - () ⇒ + private def pollTask(sub: Subscription, handler: MessageHandler, onMessage: AsyncCallback[EnvelopeBuffer]): () => Boolean = { + () => { handler.reset sub.poll(handler.fragmentsHandler, 1) @@ -50,10 +50,10 @@ private[remote] object AeronSource { private[remote] var messageReceived: EnvelopeBuffer = null // private to avoid scalac warning about exposing EnvelopeBuffer - val fragmentsHandler = new Fragments(data ⇒ messageReceived = data, pool) + val fragmentsHandler = new Fragments(data => messageReceived = data, pool) } - class Fragments(onMessage: EnvelopeBuffer ⇒ Unit, pool: EnvelopeBufferPool) extends FragmentAssembler(new FragmentHandler { + class Fragments(onMessage: EnvelopeBuffer => Unit, pool: EnvelopeBufferPool) extends FragmentAssembler(new FragmentHandler { override def onFragment(aeronBuffer: DirectBuffer, offset: Int, length: Int, header: Header): Unit = { val envelope = pool.acquire() aeronBuffer.getBytes(offset, envelope.byteBuffer, length) @@ -109,11 +109,11 @@ private[remote] class AeronSource( private var delegatingToTaskRunner = false private var pendingUnavailableImages: List[Int] = Nil - private val onUnavailableImageCb = getAsyncCallback[Int] { sessionId ⇒ + private val onUnavailableImageCb = getAsyncCallback[Int] { sessionId => pendingUnavailableImages = sessionId :: pendingUnavailableImages freeSessionBuffers() } - private val getStatusCb = getAsyncCallback[Promise[Long]] { promise ⇒ + private val getStatusCb = getAsyncCallback[Promise[Long]] { promise => promise.success(subscription.channelStatus()) } @@ -126,7 +126,7 @@ private[remote] class AeronSource( override def postStop(): Unit = { taskRunner.command(Remove(addPollTask.task)) try subscription.close() catch { - case e: DriverTimeoutException ⇒ + case e: DriverTimeoutException => // media driver was shutdown log.debug("DriverTimeout when closing subscription. {}", e) } finally @@ -188,8 +188,8 @@ private[remote] class AeronSource( if (!delegatingToTaskRunner) { def loop(remaining: List[Int]): Unit = { remaining match { - case Nil ⇒ - case sessionId :: tail ⇒ + case Nil => + case sessionId :: tail => messageHandler.fragmentsHandler.freeSessionBuffer(sessionId) loop(tail) } @@ -204,7 +204,7 @@ private[remote] class AeronSource( try { onUnavailableImageCb.invoke(sessionId) } catch { - case NonFatal(_) ⇒ // just in case it's called before stage is initialized, ignore + case NonFatal(_) => // just in case it's called before stage is initialized, ignore } setHandler(out, this) diff --git a/akka-remote/src/main/scala/akka/remote/artery/aeron/ArteryAeronUdpTransport.scala b/akka-remote/src/main/scala/akka/remote/artery/aeron/ArteryAeronUdpTransport.scala index 7c96da7560..1730ad1a61 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/aeron/ArteryAeronUdpTransport.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/aeron/ArteryAeronUdpTransport.scala @@ -129,17 +129,17 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro } private def aeronDir: String = mediaDriver.get match { - case Some(driver) ⇒ driver.aeronDirectoryName - case None ⇒ settings.Advanced.AeronDirectoryName + case Some(driver) => driver.aeronDirectoryName + case None => settings.Advanced.AeronDirectoryName } private def stopMediaDriver(): Unit = { // make sure we only close the driver once or we will crash the JVM val maybeDriver = mediaDriver.getAndSet(None) - maybeDriver.foreach { driver ⇒ + maybeDriver.foreach { driver => // this is only for embedded media driver try driver.close() catch { - case NonFatal(e) ⇒ + case NonFatal(e) => // don't think driver.close will ever throw, but just in case log.warning("Couldn't close Aeron embedded media driver due to [{}]", e) } @@ -150,7 +150,7 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro topLevelFlightRecorder.loFreq(Transport_MediaFileDeleted, NoMetaData) } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.warning( "Couldn't delete Aeron embedded media driver files in [{}] due to [{}]", driver.aeronDirectoryName, e) @@ -177,7 +177,7 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro // freeSessionBuffer in AeronSource FragmentAssembler streamMatValues.get.valuesIterator.foreach { - case InboundStreamMatValues(resourceLife, _) ⇒ + case InboundStreamMatValues(resourceLife, _) => resourceLife.onUnavailableImage(img.sessionId) } } @@ -188,10 +188,10 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro override def onError(cause: Throwable): Unit = { cause match { - case e: ConductorServiceTimeoutException ⇒ handleFatalError(e) - case e: DriverTimeoutException ⇒ handleFatalError(e) - case _: AeronTerminated ⇒ // already handled, via handleFatalError - case _ ⇒ + case e: ConductorServiceTimeoutException => handleFatalError(e) + case e: DriverTimeoutException => handleFatalError(e) + case _: AeronTerminated => // already handled, via handleFatalError + case _ => log.error(cause, s"Aeron error, $cause") } } @@ -313,13 +313,13 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro val (resourceLife, ctrl, completed) = aeronSource(ControlStreamId, envelopeBufferPool) .via(inboundFlow(settings, NoInboundCompressions)) - .toMat(inboundControlSink)({ case (a, (c, d)) ⇒ (a, c, d) }) + .toMat(inboundControlSink)({ case (a, (c, d)) => (a, c, d) }) .run()(controlMaterializer) attachControlMessageObserver(ctrl) updateStreamMatValues(ControlStreamId, resourceLife, completed) - attachInboundStreamRestart("Inbound control stream", completed, () ⇒ runInboundControlStream()) + attachInboundStreamRestart("Inbound control stream", completed, () => runInboundControlStream()) } private def runInboundOrdinaryMessagesStream(): Unit = { @@ -329,7 +329,7 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro if (inboundLanes == 1) { aeronSource(OrdinaryStreamId, envelopeBufferPool) .viaMat(inboundFlow(settings, _inboundCompressions))(Keep.both) - .toMat(inboundSink(envelopeBufferPool))({ case ((a, b), c) ⇒ (a, b, c) }) + .toMat(inboundSink(envelopeBufferPool))({ case ((a, b), c) => (a, b, c) }) .run()(materializer) } else { @@ -343,12 +343,12 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro val (resourceLife, compressionAccess, laneHub) = laneSource .toMat(Sink.fromGraph(new FixedSizePartitionHub[InboundEnvelope](inboundLanePartitioner, inboundLanes, - settings.Advanced.InboundHubBufferSize)))({ case ((a, b), c) ⇒ (a, b, c) }) + settings.Advanced.InboundHubBufferSize)))({ case ((a, b), c) => (a, b, c) }) .run()(materializer) val lane = inboundSink(envelopeBufferPool) val completedValues: Vector[Future[Done]] = - (0 until inboundLanes).iterator.map { _ ⇒ + (0 until inboundLanes).iterator.map { _ => laneHub.toMat(lane)(Keep.right).run()(materializer) }.to(immutable.Vector) @@ -356,8 +356,8 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro // tear down the upstream hub part if downstream lane fails // lanes are not completed with success by themselves so we don't have to care about onSuccess - Future.firstCompletedOf(completedValues).failed.foreach { reason ⇒ laneKillSwitch.abort(reason) } - val allCompleted = Future.sequence(completedValues).map(_ ⇒ Done) + Future.firstCompletedOf(completedValues).failed.foreach { reason => laneKillSwitch.abort(reason) } + val allCompleted = Future.sequence(completedValues).map(_ => Done) (resourceLife, compressionAccess, allCompleted) } @@ -365,7 +365,7 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro setInboundCompressionAccess(inboundCompressionAccess) updateStreamMatValues(OrdinaryStreamId, resourceLife, completed) - attachInboundStreamRestart("Inbound message stream", completed, () ⇒ runInboundOrdinaryMessagesStream()) + attachInboundStreamRestart("Inbound message stream", completed, () => runInboundOrdinaryMessagesStream()) } private def runInboundLargeMessagesStream(): Unit = { @@ -377,19 +377,19 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro .run()(materializer) updateStreamMatValues(LargeStreamId, resourceLife, completed) - attachInboundStreamRestart("Inbound large message stream", completed, () ⇒ runInboundLargeMessagesStream()) + attachInboundStreamRestart("Inbound large message stream", completed, () => runInboundLargeMessagesStream()) } private def updateStreamMatValues(streamId: Int, aeronSourceLifecycle: AeronSource.AeronLifecycle, completed: Future[Done]): Unit = { implicit val ec = materializer.executionContext updateStreamMatValues(streamId, InboundStreamMatValues[AeronLifecycle]( aeronSourceLifecycle, - completed.recover { case _ ⇒ Done })) + completed.recover { case _ => Done })) } override protected def shutdownTransport(): Future[Done] = { import system.dispatcher - taskRunner.stop().map { _ ⇒ + taskRunner.stop().map { _ => topLevelFlightRecorder.loFreq(Transport_Stopped, NoMetaData) if (aeronErrorLogTask != null) { aeronErrorLogTask.cancel() diff --git a/akka-remote/src/main/scala/akka/remote/artery/aeron/TaskRunner.scala b/akka-remote/src/main/scala/akka/remote/artery/aeron/TaskRunner.scala index de9e6957ac..4eb3ca65ba 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/aeron/TaskRunner.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/aeron/TaskRunner.scala @@ -23,7 +23,7 @@ import scala.util.control.NonFatal */ private[akka] object TaskRunner { - type Task = () ⇒ Boolean + type Task = () => Boolean sealed trait Command case object Shutdown extends Command final case class Add(task: Task) extends Command @@ -126,9 +126,9 @@ private[akka] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: In def start(): Unit = { val tf = system.threadFactory match { - case m: MonitorableThreadFactory ⇒ + case m: MonitorableThreadFactory => m.withName(m.name + "-taskrunner") - case other ⇒ other + case other => other } val thread = tf.newThread(this) thread.start() @@ -158,7 +158,7 @@ private[akka] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: In } } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, e.getMessage) } } @@ -175,7 +175,7 @@ private[akka] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: In reset = true } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "Task failed") tasks.remove(task) } @@ -185,10 +185,10 @@ private[akka] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: In private def processCommand(cmd: Command): Unit = { cmd match { - case null ⇒ // no command - case Add(task) ⇒ tasks.add(task) - case Remove(task) ⇒ tasks.remove(task) - case Shutdown ⇒ + case null => // no command + case Add(task) => tasks.add(task) + case Remove(task) => tasks.remove(task) + case Shutdown => running = false tasks.removeAll() // gc friendly while (cmdQueue.poll() != null) () // gc friendly diff --git a/akka-remote/src/main/scala/akka/remote/artery/compress/CompressionTable.scala b/akka-remote/src/main/scala/akka/remote/artery/compress/CompressionTable.scala index d433bce89c..c7fa31397f 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/compress/CompressionTable.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/compress/CompressionTable.scala @@ -17,8 +17,8 @@ private[remote] final case class CompressionTable[T](originUid: Long, version: B def compress(value: T): Int = dictionary.get(value) match { - case Some(id) ⇒ id - case None ⇒ NotCompressedId + case Some(id) => id + case None => NotCompressedId } def invert: DecompressionTable[T] = diff --git a/akka-remote/src/main/scala/akka/remote/artery/compress/DecompressionTable.scala b/akka-remote/src/main/scala/akka/remote/artery/compress/DecompressionTable.scala index bfba8cdd4c..cd1364d284 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/compress/DecompressionTable.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/compress/DecompressionTable.scala @@ -26,7 +26,7 @@ private[remote] final case class DecompressionTable[T](originUid: Long, version: /** Writes complete table as String (heavy operation) */ override def toString = s"DecompressionTable($originUid, $version, " + - s"Map(${table.zipWithIndex.map({ case (t, i) ⇒ s"$i -> $t" }).mkString(",")}))" + s"Map(${table.zipWithIndex.map({ case (t, i) => s"$i -> $t" }).mkString(",")}))" } /** INTERNAL API */ diff --git a/akka-remote/src/main/scala/akka/remote/artery/compress/InboundCompressions.scala b/akka-remote/src/main/scala/akka/remote/artery/compress/InboundCompressions.scala index d7dd6592a8..0d5e9c65b9 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/compress/InboundCompressions.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/compress/InboundCompressions.scala @@ -92,8 +92,8 @@ private[remote] final class InboundCompressionsImpl( override def confirmActorRefCompressionAdvertisement(originUid: Long, tableVersion: Byte): Unit = { _actorRefsIns.get(originUid) match { - case null ⇒ // ignore - case a ⇒ a.confirmAdvertisement(tableVersion, gaveUp = false) + case null => // ignore + case a => a.confirmAdvertisement(tableVersion, gaveUp = false) } } /** Send compression table advertisement over control stream. Should be called from Decoder. */ @@ -103,10 +103,10 @@ private[remote] final class InboundCompressionsImpl( while (vs.hasNext) { val inbound = vs.next() inboundContext.association(inbound.originUid) match { - case OptionVal.Some(a) if !a.associationState.isQuarantined(inbound.originUid) ⇒ + case OptionVal.Some(a) if !a.associationState.isQuarantined(inbound.originUid) => eventSink.hiFreq(FlightRecorderEvents.Compression_Inbound_RunActorRefAdvertisement, inbound.originUid) inbound.runNextTableAdvertisement() - case _ ⇒ remove :+= inbound.originUid + case _ => remove :+= inbound.originUid } } if (remove.nonEmpty) remove.foreach(close) @@ -123,8 +123,8 @@ private[remote] final class InboundCompressionsImpl( } override def confirmClassManifestCompressionAdvertisement(originUid: Long, tableVersion: Byte): Unit = { _classManifestsIns.get(originUid) match { - case null ⇒ // ignore - case a ⇒ a.confirmAdvertisement(tableVersion, gaveUp = false) + case null => // ignore + case a => a.confirmAdvertisement(tableVersion, gaveUp = false) } } /** Send compression table advertisement over control stream. Should be called from Decoder. */ @@ -134,10 +134,10 @@ private[remote] final class InboundCompressionsImpl( while (vs.hasNext) { val inbound = vs.next() inboundContext.association(inbound.originUid) match { - case OptionVal.Some(a) if !a.associationState.isQuarantined(inbound.originUid) ⇒ + case OptionVal.Some(a) if !a.associationState.isQuarantined(inbound.originUid) => eventSink.hiFreq(FlightRecorderEvents.Compression_Inbound_RunClassManifestAdvertisement, inbound.originUid) inbound.runNextTableAdvertisement() - case _ ⇒ remove :+= inbound.originUid + case _ => remove :+= inbound.originUid } } if (remove.nonEmpty) remove.foreach(close) @@ -242,8 +242,8 @@ private[remote] object InboundCompression { } else { @tailrec def find(tables: List[DecompressionTable[T]]): OptionVal[DecompressionTable[T]] = { tables match { - case Nil ⇒ OptionVal.None - case t :: tail ⇒ + case Nil => OptionVal.None + case t :: tail => if (t.version == version) OptionVal.Some(t) else find(tail) } @@ -252,9 +252,9 @@ private[remote] object InboundCompression { if (ArterySettings.Compression.Debug) { found match { - case OptionVal.Some(t) ⇒ + case OptionVal.Some(t) => println(s"[compress] Found table [version: ${version}], was [OLD][${t}], old tables: [${oldTables.map(_.version)}]") - case OptionVal.None ⇒ + case OptionVal.None => println(s"[compress] Did not find table [version: ${version}], old tables: [${oldTables.map(_.version)}], activeTable: ${activeTable}, nextTable: ${nextTable}") } } @@ -329,12 +329,12 @@ private[remote] abstract class InboundCompression[T >: Null]( OptionVal.None } else { current.selectTable(version = incomingTableVersion) match { - case OptionVal.Some(selectedTable) ⇒ + case OptionVal.Some(selectedTable) => val value: T = selectedTable.get(idx) if (value != null) OptionVal.Some[T](value) else throw new UnknownCompressedIdException(idx) - case _ if incomingVersionIsAdvertisementInProgress(incomingTableVersion) ⇒ + case _ if incomingVersionIsAdvertisementInProgress(incomingTableVersion) => log.debug( "Received first value from originUid [{}] compressed using the advertised compression table, " + "flipping to it (version: {})", @@ -342,7 +342,7 @@ private[remote] abstract class InboundCompression[T >: Null]( confirmAdvertisement(incomingTableVersion, gaveUp = false) decompressInternal(incomingTableVersion, idx, attemptCounter + 1) // recurse - case _ ⇒ + case _ => // which means that incoming version was > nextTable.version, which likely that // it is using a table that was built for previous incarnation of this system log.warning( @@ -357,16 +357,16 @@ private[remote] abstract class InboundCompression[T >: Null]( final def confirmAdvertisement(tableVersion: Byte, gaveUp: Boolean): Unit = { tables.advertisementInProgress match { - case Some(inProgress) if tableVersion == inProgress.version ⇒ + case Some(inProgress) if tableVersion == inProgress.version => tables = tables.startUsingNextTable() log.debug( "{} compression table version [{}] for originUid [{}]", if (gaveUp) "Gave up" else "Confirmed", tableVersion, originUid) - case Some(inProgress) if tableVersion != inProgress.version ⇒ + case Some(inProgress) if tableVersion != inProgress.version => log.debug( "{} compression table version [{}] for originUid [{}] but other version in progress [{}]", if (gaveUp) "Gave up" else "Confirmed", tableVersion, originUid, inProgress.version) - case None ⇒ + case None => // already confirmed } @@ -402,9 +402,9 @@ private[remote] abstract class InboundCompression[T >: Null]( private[remote] def runNextTableAdvertisement(): Unit = { if (ArterySettings.Compression.Debug) println(s"[compress] runNextTableAdvertisement, tables = $tables") tables.advertisementInProgress match { - case None ⇒ + case None => inboundContext.association(originUid) match { - case OptionVal.Some(association) ⇒ + case OptionVal.Some(association) => if (alive && association.isOrdinaryMessageStreamActive()) { val table = prepareCompressionAdvertisement(tables.nextTable.version) // TODO expensive, check if building the other way wouldn't be faster? @@ -417,24 +417,24 @@ private[remote] abstract class InboundCompression[T >: Null]( log.debug("{} for originUid [{}] not changed, no need to advertise same.", Logging.simpleName(tables.activeTable), originUid) } - case OptionVal.None ⇒ + case OptionVal.None => // otherwise it's too early, association not ready yet. // so we don't build the table since we would not be able to send it anyway. log.debug("No Association for originUid [{}] yet, unable to advertise compression table.", originUid) } - case Some(inProgress) ⇒ + case Some(inProgress) => resendCount += 1 if (resendCount <= maxResendCount) { // The ActorRefCompressionAdvertisement message is resent because it can be lost inboundContext.association(originUid) match { - case OptionVal.Some(association) ⇒ + case OptionVal.Some(association) => log.debug( "Advertisement in progress for originUid [{}] version [{}], resending [{}:{}]", originUid, inProgress.version, resendCount, maxResendCount) advertiseCompressionTable(association, inProgress) // resend - case OptionVal.None ⇒ + case OptionVal.None => } } else { // give up, it might be dead diff --git a/akka-remote/src/main/scala/akka/remote/artery/compress/TopHeavyHitters.scala b/akka-remote/src/main/scala/akka/remote/artery/compress/TopHeavyHitters.scala index c41a3a524a..6c7bd95777 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/compress/TopHeavyHitters.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/compress/TopHeavyHitters.scala @@ -23,7 +23,7 @@ import scala.reflect.ClassTag * This class is a hybrid data structure containing a hashmap and a heap pointing to slots in the hashmap. The capacity * of the hashmap is twice that of the heap to reduce clumping of entries on collisions. */ -private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit classTag: ClassTag[T]) { self ⇒ +private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit classTag: ClassTag[T]) { self => require((max & (max - 1)) == 0, "Maximum numbers of heavy hitters should be in form of 2^k for any natural k") diff --git a/akka-remote/src/main/scala/akka/remote/artery/tcp/ArteryTcpTransport.scala b/akka-remote/src/main/scala/akka/remote/artery/tcp/ArteryTcpTransport.scala index 3a5060b56f..a1dae590f6 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/tcp/ArteryTcpTransport.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/tcp/ArteryTcpTransport.scala @@ -54,8 +54,8 @@ private[remote] object ArteryTcpTransport { private val successUnit = Success(()) def optionToTry(opt: Option[Throwable]): Try[Unit] = opt match { - case None ⇒ successUnit - case Some(t) ⇒ Failure(t) + case None => successUnit + case Some(t) => Failure(t) } } @@ -80,14 +80,14 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider private val sslEngineProvider: OptionVal[SSLEngineProvider] = if (tlsEnabled) { system.settings.setup.get[SSLEngineProviderSetup] match { - case Some(p) ⇒ + case Some(p) => OptionVal.Some(p.sslEngineProvider(system)) - case None ⇒ + case None => // load from config OptionVal.Some(system.dynamicAccess.createInstanceFor[SSLEngineProvider]( settings.SSLEngineProviderClassName, List((classOf[ActorSystem], system))).recover { - case e ⇒ throw new ConfigurationException( + case e => throw new ConfigurationException( s"Could not create SSLEngineProvider [${settings.SSLEngineProviderClassName}]", e) }.get) } @@ -114,9 +114,9 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider val sslProvider = sslEngineProvider.get Tcp().outgoingTlsConnectionWithSSLEngine( remoteAddress, - createSSLEngine = () ⇒ sslProvider.createClientSSLEngine(host, port), + createSSLEngine = () => sslProvider.createClientSSLEngine(host, port), connectTimeout = settings.Advanced.ConnectionTimeout, - verifySession = session ⇒ optionToTry(sslProvider.verifyClientSession(host, session))) + verifySession = session => optionToTry(sslProvider.verifyClientSession(host, session))) } else { Tcp() .outgoingConnection( @@ -126,11 +126,11 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider } def connectionFlowWithRestart: Flow[ByteString, ByteString, NotUsed] = { - val flowFactory = () ⇒ { + val flowFactory = () => { def flow(controlIdleKillSwitch: OptionVal[SharedKillSwitch]) = Flow[ByteString] - .via(Flow.lazyInitAsync(() ⇒ { + .via(Flow.lazyInitAsync(() => { // only open the actual connection if any new messages are sent afr.loFreq( TcpOutbound_Connected, @@ -143,7 +143,7 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider .prepend(Source.single(TcpFraming.encodeConnectionHeader(streamId))) .via(connectionFlow)) })) - .recoverWithRetries(1, { case ArteryTransport.ShutdownSignal ⇒ Source.empty }) + .recoverWithRetries(1, { case ArteryTransport.ShutdownSignal => Source.empty }) .log(name = s"outbound connection to [${outboundContext.remoteAddress}], ${streamName(streamId)} stream") .addAttributes(Attributes.logLevels(onElement = LogLevels.Off, onFailure = Logging.WarningLevel)) @@ -168,7 +168,7 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider } Flow[EnvelopeBuffer] - .map { env ⇒ + .map { env => val size = env.byteBuffer.limit() afr.hiFreq(TcpOutbound_Sent, size) @@ -179,7 +179,7 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider TcpFraming.encodeFrameHeader(size) ++ bytes } .via(connectionFlowWithRestart) - .map(_ ⇒ throw new IllegalStateException(s"Unexpected incoming bytes in outbound connection to [${outboundContext.remoteAddress}]")) + .map(_ => throw new IllegalStateException(s"Unexpected incoming bytes in outbound connection to [${outboundContext.remoteAddress}]")) .toMat(Sink.ignore)(Keep.right) } @@ -212,7 +212,7 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider else ( Flow[EnvelopeBuffer] - .map(_ ⇒ log.warning("Dropping large message, missing large-message-destinations configuration.")) + .map(_ => log.warning("Dropping large message, missing large-message-destinations configuration.")) .to(Sink.ignore), Promise[Done]().future) // never completed, not enabled } @@ -224,14 +224,14 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider // frame. That was not chosen because it is more complicated to implement and might have more runtime // overhead. inboundStream = - OptionVal.Some(Sink.fromGraph(GraphDSL.create() { implicit b ⇒ + OptionVal.Some(Sink.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ - val partition = b.add(Partition[EnvelopeBuffer](3, env ⇒ { + val partition = b.add(Partition[EnvelopeBuffer](3, env => { env.streamId match { - case OrdinaryStreamId ⇒ 1 - case ControlStreamId ⇒ 0 - case LargeStreamId ⇒ 2 - case other ⇒ throw new IllegalArgumentException(s"Unexpected streamId [$other]") + case OrdinaryStreamId => 1 + case ControlStreamId => 0 + case LargeStreamId => 2 + case other => throw new IllegalArgumentException(s"Unexpected streamId [$other]") } })) partition.out(0) ~> controlStream @@ -249,8 +249,8 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider .via(inboundKillSwitch.flow) .via(new TcpFraming(afr)) .alsoTo(inboundStream.get) - .filter(_ ⇒ false) // don't send back anything in this TCP socket - .map(_ ⇒ ByteString.empty) // make it a Flow[ByteString] again + .filter(_ => false) // don't send back anything in this TCP socket + .map(_ => ByteString.empty) // make it a Flow[ByteString] again } val bindHost = bindAddress.address.host.get @@ -262,8 +262,8 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider Tcp().bindTlsWithSSLEngine( interface = bindHost, port = bindPort, - createSSLEngine = () ⇒ sslProvider.createServerSSLEngine(bindHost, bindPort), - verifySession = session ⇒ optionToTry(sslProvider.verifyServerSession(bindHost, session))) + createSSLEngine = () => sslProvider.createServerSSLEngine(bindHost, bindPort), + verifySession = session => optionToTry(sslProvider.verifyServerSession(bindHost, session))) } else { Tcp().bind( interface = bindHost, @@ -272,10 +272,10 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider } serverBinding = serverBinding match { - case None ⇒ + case None => val afr = createFlightRecorderEventSink() val binding = connectionSource - .to(Sink.foreach { connection ⇒ + .to(Sink.foreach { connection => afr.loFreq( TcpInbound_Connected, s"${connection.remoteAddress.getHostString}:${connection.remoteAddress.getPort}") @@ -283,7 +283,7 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider }) .run() .recoverWith { - case e ⇒ Future.failed(new RemoteTransportException( + case e => Future.failed(new RemoteTransportException( s"Failed to bind TCP to [${localAddress.address.host.get}:${localAddress.address.port.get}] due to: " + e.getMessage, e)) }(ExecutionContexts.sameThreadExecutionContext) @@ -292,7 +292,7 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider Await.result(binding, settings.Bind.BindTimeout) afr.loFreq(TcpInbound_Bound, s"$bindHost:$bindPort") Some(binding) - case s @ Some(_) ⇒ + case s @ Some(_) => // already bound, when restarting s } @@ -303,17 +303,17 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider implicit val ec: ExecutionContext = materializer.executionContext val completed = Future.firstCompletedOf( List(controlStreamCompleted, ordinaryMessagesStreamCompleted, largeMessagesStreamCompleted)) - val restart = () ⇒ { + val restart = () => { inboundKillSwitch.shutdown() inboundKillSwitch = KillSwitches.shared("inboundKillSwitch") val allStopped: Future[Done] = for { - _ ← controlStreamCompleted.recover { case _ ⇒ Done } - _ ← ordinaryMessagesStreamCompleted.recover { case _ ⇒ Done } - _ ← if (largeMessageChannelEnabled) - largeMessagesStreamCompleted.recover { case _ ⇒ Done } else Future.successful(Done) + _ <- controlStreamCompleted.recover { case _ => Done } + _ <- ordinaryMessagesStreamCompleted.recover { case _ => Done } + _ <- if (largeMessageChannelEnabled) + largeMessagesStreamCompleted.recover { case _ => Done } else Future.successful(Done) } yield Done - allStopped.foreach(_ ⇒ runInboundStreams()) + allStopped.foreach(_ => runInboundStreams()) } attachInboundStreamRestart("Inbound streams", completed, restart) @@ -326,7 +326,7 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider MergeHub.source[EnvelopeBuffer].addAttributes(Attributes.logLevels(onFailure = LogLevels.Off)) .via(inboundKillSwitch.flow) .via(inboundFlow(settings, NoInboundCompressions)) - .toMat(inboundControlSink)({ case (a, (c, d)) ⇒ (a, c, d) }) + .toMat(inboundControlSink)({ case (a, (c, d)) => (a, c, d) }) .run()(controlMaterializer) attachControlMessageObserver(ctrl) updateStreamMatValues(completed) @@ -342,7 +342,7 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider MergeHub.source[EnvelopeBuffer].addAttributes(Attributes.logLevels(onFailure = LogLevels.Off)) .via(inboundKillSwitch.flow) .viaMat(inboundFlow(settings, _inboundCompressions))(Keep.both) - .toMat(inboundSink(envelopeBufferPool))({ case ((a, b), c) ⇒ (a, b, c) }) + .toMat(inboundSink(envelopeBufferPool))({ case ((a, b), c) => (a, b, c) }) .run()(materializer) } else { @@ -358,12 +358,12 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider val (inboundHub, compressionAccess, laneHub) = laneSource .toMat(Sink.fromGraph(new FixedSizePartitionHub[InboundEnvelope](inboundLanePartitioner, inboundLanes, - settings.Advanced.InboundHubBufferSize)))({ case ((a, b), c) ⇒ (a, b, c) }) + settings.Advanced.InboundHubBufferSize)))({ case ((a, b), c) => (a, b, c) }) .run()(materializer) val lane = inboundSink(envelopeBufferPool) val completedValues: Vector[Future[Done]] = - (0 until inboundLanes).iterator.map { _ ⇒ + (0 until inboundLanes).iterator.map { _ => laneHub.toMat(lane)(Keep.right).run()(materializer) }.to(immutable.Vector) @@ -371,8 +371,8 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider // tear down the upstream hub part if downstream lane fails // lanes are not completed with success by themselves so we don't have to care about onSuccess - Future.firstCompletedOf(completedValues).failed.foreach { reason ⇒ laneKillSwitch.abort(reason) } - val allCompleted = Future.sequence(completedValues).map(_ ⇒ Done) + Future.firstCompletedOf(completedValues).failed.foreach { reason => laneKillSwitch.abort(reason) } + val allCompleted = Future.sequence(completedValues).map(_ => Done) (inboundHub, compressionAccess, allCompleted) } @@ -403,13 +403,13 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider implicit val ec: ExecutionContext = materializer.executionContext updateStreamMatValues(ControlStreamId, InboundStreamMatValues[NotUsed]( NotUsed, - completed.recover { case _ ⇒ Done })) + completed.recover { case _ => Done })) } override protected def shutdownTransport(): Future[Done] = { import system.dispatcher inboundKillSwitch.shutdown() - unbind().map { _ ⇒ + unbind().map { _ => topLevelFlightRecorder.loFreq(Transport_Stopped, NoMetaData) Done } @@ -417,16 +417,16 @@ private[remote] class ArteryTcpTransport(_system: ExtendedActorSystem, _provider private def unbind(): Future[Done] = { serverBinding match { - case Some(binding) ⇒ + case Some(binding) => import system.dispatcher for { - b ← binding - _ ← b.unbind() + b <- binding + _ <- b.unbind() } yield { topLevelFlightRecorder.loFreq(TcpInbound_Bound, s"${localAddress.address.host.get}:${localAddress.address.port}") Done } - case None ⇒ + case None => Future.successful(Done) } } diff --git a/akka-remote/src/main/scala/akka/remote/artery/tcp/SSLEngineProvider.scala b/akka-remote/src/main/scala/akka/remote/artery/tcp/SSLEngineProvider.scala index a6af8bdce8..b35e35b547 100644 --- a/akka-remote/src/main/scala/akka/remote/artery/tcp/SSLEngineProvider.scala +++ b/akka-remote/src/main/scala/akka/remote/artery/tcp/SSLEngineProvider.scala @@ -103,11 +103,11 @@ class SslTransportException(message: String, cause: Throwable) extends RuntimeEx ctx.init(keyManagers, trustManagers, rng) ctx } catch { - case e: FileNotFoundException ⇒ + case e: FileNotFoundException => throw new SslTransportException("Server SSL connection could not be established because key store could not be loaded", e) - case e: IOException ⇒ + case e: IOException => throw new SslTransportException("Server SSL connection could not be established because: " + e.getMessage, e) - case e: GeneralSecurityException ⇒ + case e: GeneralSecurityException => throw new SslTransportException("Server SSL connection could not be established because SSL context could not be constructed", e) } } @@ -191,7 +191,7 @@ object SSLEngineProviderSetup { * Scala API: factory for defining a `SSLEngineProvider` that is passed in when ActorSystem * is created rather than creating one from configured class name. */ - def apply(sslEngineProvider: ExtendedActorSystem ⇒ SSLEngineProvider): SSLEngineProviderSetup = + def apply(sslEngineProvider: ExtendedActorSystem => SSLEngineProvider): SSLEngineProviderSetup = new SSLEngineProviderSetup(sslEngineProvider) /** @@ -199,7 +199,7 @@ object SSLEngineProviderSetup { * is created rather than creating one from configured class name. */ def create(sslEngineProvider: java.util.function.Function[ExtendedActorSystem, SSLEngineProvider]): SSLEngineProviderSetup = - apply(sys ⇒ sslEngineProvider(sys)) + apply(sys => sslEngineProvider(sys)) } @@ -212,7 +212,7 @@ object SSLEngineProviderSetup { * Constructor is *Internal API*, use factories in [[SSLEngineProviderSetup()]] */ @ApiMayChange class SSLEngineProviderSetup private ( - val sslEngineProvider: ExtendedActorSystem ⇒ SSLEngineProvider) extends Setup + val sslEngineProvider: ExtendedActorSystem => SSLEngineProvider) extends Setup /** * INTERNAL API @@ -220,17 +220,17 @@ object SSLEngineProviderSetup { @InternalApi private[akka] object SecureRandomFactory { def createSecureRandom(randomNumberGenerator: String, log: MarkerLoggingAdapter): SecureRandom = { val rng = randomNumberGenerator match { - case s @ ("SHA1PRNG" | "NativePRNG") ⇒ + case s @ ("SHA1PRNG" | "NativePRNG") => log.debug("SSL random number generator set to: {}", s) // SHA1PRNG needs /dev/urandom to be the source on Linux to prevent problems with /dev/random blocking // However, this also makes the seed source insecure as the seed is reused to avoid blocking (not a problem on FreeBSD). SecureRandom.getInstance(s) - case "" | "SecureRandom" ⇒ + case "" | "SecureRandom" => log.debug("SSL random number generator set to [SecureRandom]") new SecureRandom - case unknown ⇒ + case unknown => log.warning(LogMarker.Security, "Unknown SSL random number generator [{}] falling back to SecureRandom", unknown) new SecureRandom } diff --git a/akka-remote/src/main/scala/akka/remote/routing/RemoteRouterConfig.scala b/akka-remote/src/main/scala/akka/remote/routing/RemoteRouterConfig.scala index 14f0e7a707..6b265d3d51 100644 --- a/akka-remote/src/main/scala/akka/remote/routing/RemoteRouterConfig.scala +++ b/akka-remote/src/main/scala/akka/remote/routing/RemoteRouterConfig.scala @@ -69,11 +69,11 @@ final case class RemoteRouterConfig(local: Pool, nodes: Iterable[Address]) exten override def resizer: Option[Resizer] = local.resizer override def withFallback(other: RouterConfig): RouterConfig = other match { - case RemoteRouterConfig(_: RemoteRouterConfig, _) ⇒ throw new IllegalStateException( + case RemoteRouterConfig(_: RemoteRouterConfig, _) => throw new IllegalStateException( "RemoteRouterConfig is not allowed to wrap a RemoteRouterConfig") - case RemoteRouterConfig(local: Pool, _) ⇒ + case RemoteRouterConfig(local: Pool, _) => copy(local = this.local.withFallback(local).asInstanceOf[Pool]) - case _ ⇒ copy(local = this.local.withFallback(other).asInstanceOf[Pool]) + case _ => copy(local = this.local.withFallback(other).asInstanceOf[Pool]) } } diff --git a/akka-remote/src/main/scala/akka/remote/serialization/ActorRefResolveCache.scala b/akka-remote/src/main/scala/akka/remote/serialization/ActorRefResolveCache.scala index 420a177c2a..49d0a149f9 100644 --- a/akka-remote/src/main/scala/akka/remote/serialization/ActorRefResolveCache.scala +++ b/akka-remote/src/main/scala/akka/remote/serialization/ActorRefResolveCache.scala @@ -35,8 +35,8 @@ private[akka] object ActorRefResolveThreadLocalCache private[akka] class ActorRefResolveThreadLocalCache(val system: ExtendedActorSystem) extends Extension { private val provider = system.provider match { - case r: RemoteActorRefProvider ⇒ r - case _ ⇒ throw new IllegalArgumentException( + case r: RemoteActorRefProvider => r + case _ => throw new IllegalArgumentException( "ActorRefResolveThreadLocalCache can only be used with RemoteActorRefProvider, " + s"not with ${system.provider.getClass}") } diff --git a/akka-remote/src/main/scala/akka/remote/serialization/ArteryMessageSerializer.scala b/akka-remote/src/main/scala/akka/remote/serialization/ArteryMessageSerializer.scala index 502651110b..8f7dc80784 100644 --- a/akka-remote/src/main/scala/akka/remote/serialization/ArteryMessageSerializer.scala +++ b/akka-remote/src/main/scala/akka/remote/serialization/ArteryMessageSerializer.scala @@ -44,57 +44,57 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste private lazy val serialization = SerializationExtension(system) override def manifest(o: AnyRef): String = o match { // most frequent ones first - case _: SystemMessageDelivery.SystemMessageEnvelope ⇒ SystemMessageEnvelopeManifest - case _: SystemMessageDelivery.Ack ⇒ SystemMessageDeliveryAckManifest - case _: HandshakeReq ⇒ HandshakeReqManifest - case _: HandshakeRsp ⇒ HandshakeRspManifest - case _: RemoteWatcher.ArteryHeartbeat.type ⇒ ArteryHeartbeatManifest - case _: RemoteWatcher.ArteryHeartbeatRsp ⇒ ArteryHeartbeatRspManifest - case _: SystemMessageDelivery.Nack ⇒ SystemMessageDeliveryNackManifest - case _: Quarantined ⇒ QuarantinedManifest - case _: ActorSystemTerminating ⇒ ActorSystemTerminatingManifest - case _: ActorSystemTerminatingAck ⇒ ActorSystemTerminatingAckManifest - case _: CompressionProtocol.ActorRefCompressionAdvertisement ⇒ ActorRefCompressionAdvertisementManifest - case _: CompressionProtocol.ActorRefCompressionAdvertisementAck ⇒ ActorRefCompressionAdvertisementAckManifest - case _: CompressionProtocol.ClassManifestCompressionAdvertisement ⇒ ClassManifestCompressionAdvertisementManifest - case _: CompressionProtocol.ClassManifestCompressionAdvertisementAck ⇒ ClassManifestCompressionAdvertisementAckManifest - case _ ⇒ + case _: SystemMessageDelivery.SystemMessageEnvelope => SystemMessageEnvelopeManifest + case _: SystemMessageDelivery.Ack => SystemMessageDeliveryAckManifest + case _: HandshakeReq => HandshakeReqManifest + case _: HandshakeRsp => HandshakeRspManifest + case _: RemoteWatcher.ArteryHeartbeat.type => ArteryHeartbeatManifest + case _: RemoteWatcher.ArteryHeartbeatRsp => ArteryHeartbeatRspManifest + case _: SystemMessageDelivery.Nack => SystemMessageDeliveryNackManifest + case _: Quarantined => QuarantinedManifest + case _: ActorSystemTerminating => ActorSystemTerminatingManifest + case _: ActorSystemTerminatingAck => ActorSystemTerminatingAckManifest + case _: CompressionProtocol.ActorRefCompressionAdvertisement => ActorRefCompressionAdvertisementManifest + case _: CompressionProtocol.ActorRefCompressionAdvertisementAck => ActorRefCompressionAdvertisementAckManifest + case _: CompressionProtocol.ClassManifestCompressionAdvertisement => ClassManifestCompressionAdvertisementManifest + case _: CompressionProtocol.ClassManifestCompressionAdvertisementAck => ClassManifestCompressionAdvertisementAckManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass} in [${getClass.getName}]") } override def toBinary(o: AnyRef): Array[Byte] = o match { // most frequent ones first - case env: SystemMessageDelivery.SystemMessageEnvelope ⇒ serializeSystemMessageEnvelope(env).toByteArray - case SystemMessageDelivery.Ack(seqNo, from) ⇒ serializeSystemMessageDeliveryAck(seqNo, from).toByteArray - case HandshakeReq(from, to) ⇒ serializeHandshakeReq(from, to).toByteArray - case HandshakeRsp(from) ⇒ serializeWithAddress(from).toByteArray - case RemoteWatcher.ArteryHeartbeat ⇒ Array.emptyByteArray - case RemoteWatcher.ArteryHeartbeatRsp(from) ⇒ serializeArteryHeartbeatRsp(from).toByteArray - case SystemMessageDelivery.Nack(seqNo, from) ⇒ serializeSystemMessageDeliveryAck(seqNo, from).toByteArray - case q: Quarantined ⇒ serializeQuarantined(q).toByteArray - case ActorSystemTerminating(from) ⇒ serializeWithAddress(from).toByteArray - case ActorSystemTerminatingAck(from) ⇒ serializeWithAddress(from).toByteArray - case adv: ActorRefCompressionAdvertisement ⇒ serializeActorRefCompressionAdvertisement(adv).toByteArray - case ActorRefCompressionAdvertisementAck(from, id) ⇒ serializeCompressionTableAdvertisementAck(from, id).toByteArray - case adv: ClassManifestCompressionAdvertisement ⇒ serializeCompressionAdvertisement(adv)(identity).toByteArray - case ClassManifestCompressionAdvertisementAck(from, id) ⇒ serializeCompressionTableAdvertisementAck(from, id).toByteArray + case env: SystemMessageDelivery.SystemMessageEnvelope => serializeSystemMessageEnvelope(env).toByteArray + case SystemMessageDelivery.Ack(seqNo, from) => serializeSystemMessageDeliveryAck(seqNo, from).toByteArray + case HandshakeReq(from, to) => serializeHandshakeReq(from, to).toByteArray + case HandshakeRsp(from) => serializeWithAddress(from).toByteArray + case RemoteWatcher.ArteryHeartbeat => Array.emptyByteArray + case RemoteWatcher.ArteryHeartbeatRsp(from) => serializeArteryHeartbeatRsp(from).toByteArray + case SystemMessageDelivery.Nack(seqNo, from) => serializeSystemMessageDeliveryAck(seqNo, from).toByteArray + case q: Quarantined => serializeQuarantined(q).toByteArray + case ActorSystemTerminating(from) => serializeWithAddress(from).toByteArray + case ActorSystemTerminatingAck(from) => serializeWithAddress(from).toByteArray + case adv: ActorRefCompressionAdvertisement => serializeActorRefCompressionAdvertisement(adv).toByteArray + case ActorRefCompressionAdvertisementAck(from, id) => serializeCompressionTableAdvertisementAck(from, id).toByteArray + case adv: ClassManifestCompressionAdvertisement => serializeCompressionAdvertisement(adv)(identity).toByteArray + case ClassManifestCompressionAdvertisementAck(from, id) => serializeCompressionTableAdvertisementAck(from, id).toByteArray } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { // most frequent ones first (could be made a HashMap in the future) - case SystemMessageEnvelopeManifest ⇒ deserializeSystemMessageEnvelope(bytes) - case SystemMessageDeliveryAckManifest ⇒ deserializeSystemMessageDeliveryAck(bytes, SystemMessageDelivery.Ack) - case HandshakeReqManifest ⇒ deserializeHandshakeReq(bytes, HandshakeReq) - case HandshakeRspManifest ⇒ deserializeWithFromAddress(bytes, HandshakeRsp) - case SystemMessageDeliveryNackManifest ⇒ deserializeSystemMessageDeliveryAck(bytes, SystemMessageDelivery.Nack) - case QuarantinedManifest ⇒ deserializeQuarantined(ArteryControlFormats.Quarantined.parseFrom(bytes)) - case ActorSystemTerminatingManifest ⇒ deserializeWithFromAddress(bytes, ActorSystemTerminating) - case ActorSystemTerminatingAckManifest ⇒ deserializeWithFromAddress(bytes, ActorSystemTerminatingAck) - case ActorRefCompressionAdvertisementManifest ⇒ deserializeActorRefCompressionAdvertisement(bytes) - case ActorRefCompressionAdvertisementAckManifest ⇒ deserializeCompressionTableAdvertisementAck(bytes, ActorRefCompressionAdvertisementAck) - case ClassManifestCompressionAdvertisementManifest ⇒ deserializeCompressionAdvertisement(bytes, identity, ClassManifestCompressionAdvertisement) - case ClassManifestCompressionAdvertisementAckManifest ⇒ deserializeCompressionTableAdvertisementAck(bytes, ClassManifestCompressionAdvertisementAck) - case ArteryHeartbeatManifest ⇒ RemoteWatcher.ArteryHeartbeat - case ArteryHeartbeatRspManifest ⇒ deserializeArteryHeartbeatRsp(bytes, ArteryHeartbeatRsp) - case _ ⇒ throw new NotSerializableException(s"Manifest '$manifest' not defined for ArteryControlMessageSerializer (serializer id $identifier)") + case SystemMessageEnvelopeManifest => deserializeSystemMessageEnvelope(bytes) + case SystemMessageDeliveryAckManifest => deserializeSystemMessageDeliveryAck(bytes, SystemMessageDelivery.Ack) + case HandshakeReqManifest => deserializeHandshakeReq(bytes, HandshakeReq) + case HandshakeRspManifest => deserializeWithFromAddress(bytes, HandshakeRsp) + case SystemMessageDeliveryNackManifest => deserializeSystemMessageDeliveryAck(bytes, SystemMessageDelivery.Nack) + case QuarantinedManifest => deserializeQuarantined(ArteryControlFormats.Quarantined.parseFrom(bytes)) + case ActorSystemTerminatingManifest => deserializeWithFromAddress(bytes, ActorSystemTerminating) + case ActorSystemTerminatingAckManifest => deserializeWithFromAddress(bytes, ActorSystemTerminatingAck) + case ActorRefCompressionAdvertisementManifest => deserializeActorRefCompressionAdvertisement(bytes) + case ActorRefCompressionAdvertisementAckManifest => deserializeCompressionTableAdvertisementAck(bytes, ActorRefCompressionAdvertisementAck) + case ClassManifestCompressionAdvertisementManifest => deserializeCompressionAdvertisement(bytes, identity, ClassManifestCompressionAdvertisement) + case ClassManifestCompressionAdvertisementAckManifest => deserializeCompressionTableAdvertisementAck(bytes, ClassManifestCompressionAdvertisementAck) + case ArteryHeartbeatManifest => RemoteWatcher.ArteryHeartbeat + case ArteryHeartbeatRspManifest => deserializeArteryHeartbeatRsp(bytes, ArteryHeartbeatRsp) + case _ => throw new NotSerializableException(s"Manifest '$manifest' not defined for ArteryControlMessageSerializer (serializer id $identifier)") } import scala.collection.JavaConverters._ @@ -122,7 +122,7 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste def deserializeActorRefCompressionAdvertisement(bytes: Array[Byte]): ActorRefCompressionAdvertisement = deserializeCompressionAdvertisement(bytes, deserializeActorRef, ActorRefCompressionAdvertisement) - def serializeCompressionAdvertisement[T](adv: CompressionAdvertisement[T])(keySerializer: T ⇒ String): ArteryControlFormats.CompressionTableAdvertisement = { + def serializeCompressionAdvertisement[T](adv: CompressionAdvertisement[T])(keySerializer: T => String): ArteryControlFormats.CompressionTableAdvertisement = { val builder = ArteryControlFormats.CompressionTableAdvertisement.newBuilder .setFrom(serializeUniqueAddress(adv.from)) @@ -130,7 +130,7 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste .setTableVersion(adv.table.version) adv.table.dictionary.foreach { - case (key, value) ⇒ + case (key, value) => builder .addKeys(keySerializer(key)) .addValues(value) @@ -139,7 +139,7 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste builder.build } - def deserializeCompressionAdvertisement[T, U](bytes: Array[Byte], keyDeserializer: String ⇒ T, create: (UniqueAddress, CompressionTable[T]) ⇒ U): U = { + def deserializeCompressionAdvertisement[T, U](bytes: Array[Byte], keyDeserializer: String => T, create: (UniqueAddress, CompressionTable[T]) => U): U = { val protoAdv = ArteryControlFormats.CompressionTableAdvertisement.parseFrom(bytes) val kvs = @@ -156,7 +156,7 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste .setVersion(version) .build() - def deserializeCompressionTableAdvertisementAck(bytes: Array[Byte], create: (UniqueAddress, Byte) ⇒ AnyRef): AnyRef = { + def deserializeCompressionTableAdvertisementAck(bytes: Array[Byte], create: (UniqueAddress, Byte) => AnyRef): AnyRef = { val msg = ArteryControlFormats.CompressionTableAdvertisementAck.parseFrom(bytes) create(deserializeUniqueAddress(msg.getFrom), msg.getVersion.toByte) } @@ -193,7 +193,7 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste .setFrom(serializeUniqueAddress(from)) .build - def deserializeSystemMessageDeliveryAck(bytes: Array[Byte], create: (Long, UniqueAddress) ⇒ AnyRef): AnyRef = { + def deserializeSystemMessageDeliveryAck(bytes: Array[Byte], create: (Long, UniqueAddress) => AnyRef): AnyRef = { val protoAck = ArteryControlFormats.SystemMessageDeliveryAck.parseFrom(bytes) create(protoAck.getSeqNo, deserializeUniqueAddress(protoAck.getFrom)) @@ -202,7 +202,7 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste def serializeWithAddress(from: UniqueAddress): MessageLite = ArteryControlFormats.MessageWithAddress.newBuilder.setAddress(serializeUniqueAddress(from)).build() - def deserializeWithFromAddress(bytes: Array[Byte], create: UniqueAddress ⇒ AnyRef): AnyRef = + def deserializeWithFromAddress(bytes: Array[Byte], create: UniqueAddress => AnyRef): AnyRef = create(deserializeUniqueAddress(ArteryControlFormats.MessageWithAddress.parseFrom(bytes).getAddress)) def serializeHandshakeReq(from: UniqueAddress, to: Address): MessageLite = @@ -211,7 +211,7 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste .setTo(serializeAddress(to)) .build() - def deserializeHandshakeReq(bytes: Array[Byte], create: (UniqueAddress, Address) ⇒ HandshakeReq): HandshakeReq = { + def deserializeHandshakeReq(bytes: Array[Byte], create: (UniqueAddress, Address) => HandshakeReq): HandshakeReq = { val protoEnv = ArteryControlFormats.HandshakeReq.parseFrom(bytes) create(deserializeUniqueAddress(protoEnv.getFrom), deserializeAddress(protoEnv.getTo)) } @@ -227,14 +227,14 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste def serializeAddress(address: Address): ArteryControlFormats.Address = address match { - case Address(protocol, system, Some(host), Some(port)) ⇒ + case Address(protocol, system, Some(host), Some(port)) => ArteryControlFormats.Address.newBuilder() .setProtocol(protocol) .setSystem(system) .setHostname(host) .setPort(port) .build() - case _ ⇒ throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") } def deserializeAddress(address: ArteryControlFormats.Address): Address = @@ -243,7 +243,7 @@ private[akka] final class ArteryMessageSerializer(val system: ExtendedActorSyste def serializeArteryHeartbeatRsp(uid: Long): ArteryControlFormats.ArteryHeartbeatRsp = ArteryControlFormats.ArteryHeartbeatRsp.newBuilder().setUid(uid).build() - def deserializeArteryHeartbeatRsp(bytes: Array[Byte], create: Long ⇒ ArteryHeartbeatRsp): ArteryHeartbeatRsp = { + def deserializeArteryHeartbeatRsp(bytes: Array[Byte], create: Long => ArteryHeartbeatRsp): ArteryHeartbeatRsp = { val msg = ArteryControlFormats.ArteryHeartbeatRsp.parseFrom(bytes) create(msg.getUid) } diff --git a/akka-remote/src/main/scala/akka/remote/serialization/DaemonMsgCreateSerializer.scala b/akka-remote/src/main/scala/akka/remote/serialization/DaemonMsgCreateSerializer.scala index f64dedc04a..40857541db 100644 --- a/akka-remote/src/main/scala/akka/remote/serialization/DaemonMsgCreateSerializer.scala +++ b/akka-remote/src/main/scala/akka/remote/serialization/DaemonMsgCreateSerializer.scala @@ -39,7 +39,7 @@ private[akka] final class DaemonMsgCreateSerializer(val system: ExtendedActorSys override val includeManifest: Boolean = false def toBinary(obj: AnyRef): Array[Byte] = obj match { - case DaemonMsgCreate(props, deploy, path, supervisor) ⇒ + case DaemonMsgCreate(props, deploy, path, supervisor) => def deployProto(d: Deploy): DeployData = { val builder = DeployData.newBuilder.setPath(d.path) @@ -75,7 +75,7 @@ private[akka] final class DaemonMsgCreateSerializer(val system: ExtendedActorSys val builder = PropsData.newBuilder .setClazz(props.clazz.getName) .setDeploy(deployProto(props.deploy)) - props.args.foreach { arg ⇒ + props.args.foreach { arg => val (serializerId, hasManifest, manifest, bytes) = serialize(arg) builder.addArgs(ByteString.copyFrom(bytes)) builder.addManifests(manifest) @@ -92,7 +92,7 @@ private[akka] final class DaemonMsgCreateSerializer(val system: ExtendedActorSys setSupervisor(serializeActorRef(supervisor)). build.toByteArray - case _ ⇒ + case _ => throw new IllegalArgumentException( "Can't serialize a non-DaemonMsgCreate message using DaemonMsgCreateSerializer [%s]".format(obj)) } @@ -154,7 +154,7 @@ private[akka] final class DaemonMsgCreateSerializer(val system: ExtendedActorSys // message from a newer node always contains serializer ids and possibly a string manifest for each position if (protoProps.getSerializerIdsCount > 0) { for { - idx ← (0 until protoProps.getSerializerIdsCount).toVector + idx <- (0 until protoProps.getSerializerIdsCount).toVector } yield { val manifest = if (protoProps.getHasManifest(idx)) protoProps.getManifests(idx) @@ -188,9 +188,9 @@ private[akka] final class DaemonMsgCreateSerializer(val system: ExtendedActorSys // allowing for usage of serializers with string manifests val hasManifest = serializer.includeManifest val manifest = serializer match { - case ser: SerializerWithStringManifest ⇒ + case ser: SerializerWithStringManifest => ser.manifest(m) - case _ ⇒ + case _ => // we do include class name regardless to retain wire compatibility // with older nodes who expect manifest to be the class name if (m eq null) { @@ -222,17 +222,17 @@ private[akka] final class DaemonMsgCreateSerializer(val system: ExtendedActorSys private def oldDeserialize[T: ClassTag](data: ByteString, clazz: Class[T]): T = { val bytes = data.toByteArray serialization.deserialize(bytes, clazz) match { - case Success(x: T) ⇒ x - case Success(other) ⇒ throw new IllegalArgumentException("Can't deserialize to [%s], got [%s]".format(clazz.getName, other)) - case Failure(e) ⇒ + case Success(x: T) => x + case Success(other) => throw new IllegalArgumentException("Can't deserialize to [%s], got [%s]".format(clazz.getName, other)) + case Failure(e) => // Fallback to the java serializer, because some interfaces don't implement java.io.Serializable, // but the impl instance does. This could be optimized by adding java serializers in reference.conf: // com.typesafe.config.Config // akka.routing.RouterConfig // akka.actor.Scope serialization.deserialize(bytes, classOf[java.io.Serializable]) match { - case Success(x: T) ⇒ x - case _ ⇒ throw e // the first exception + case Success(x: T) => x + case _ => throw e // the first exception } } } diff --git a/akka-remote/src/main/scala/akka/remote/serialization/MessageContainerSerializer.scala b/akka-remote/src/main/scala/akka/remote/serialization/MessageContainerSerializer.scala index e4b1ec7669..d39d970273 100644 --- a/akka-remote/src/main/scala/akka/remote/serialization/MessageContainerSerializer.scala +++ b/akka-remote/src/main/scala/akka/remote/serialization/MessageContainerSerializer.scala @@ -23,8 +23,8 @@ class MessageContainerSerializer(val system: ExtendedActorSystem) extends BaseSe def includeManifest: Boolean = false def toBinary(obj: AnyRef): Array[Byte] = obj match { - case sel: ActorSelectionMessage ⇒ serializeSelection(sel) - case _ ⇒ throw new IllegalArgumentException(s"Cannot serialize object of type [${obj.getClass.getName}]") + case sel: ActorSelectionMessage => serializeSelection(sel) + case _ => throw new IllegalArgumentException(s"Cannot serialize object of type [${obj.getClass.getName}]") } import ContainerFormats.PatternType._ @@ -42,11 +42,11 @@ class MessageContainerSerializer(val system: ExtendedActorSystem) extends BaseSe if (ms.nonEmpty) builder.setMessageManifest(ByteString.copyFromUtf8(ms)) sel.elements.foreach { - case SelectChildName(name) ⇒ + case SelectChildName(name) => builder.addPattern(buildPattern(Some(name), CHILD_NAME)) - case SelectChildPattern(patternStr) ⇒ + case SelectChildPattern(patternStr) => builder.addPattern(buildPattern(Some(patternStr), CHILD_PATTERN)) - case SelectParent ⇒ + case SelectParent => builder.addPattern(buildPattern(None, PARENT)) } @@ -68,11 +68,11 @@ class MessageContainerSerializer(val system: ExtendedActorSystem) extends BaseSe manifest).get import scala.collection.JavaConverters._ - val elements: immutable.Iterable[SelectionPathElement] = selectionEnvelope.getPatternList.asScala.iterator.map { x ⇒ + val elements: immutable.Iterable[SelectionPathElement] = selectionEnvelope.getPatternList.asScala.iterator.map { x => x.getType match { - case CHILD_NAME ⇒ SelectChildName(x.getMatcher) - case CHILD_PATTERN ⇒ SelectChildPattern(x.getMatcher) - case PARENT ⇒ SelectParent + case CHILD_NAME => SelectChildName(x.getMatcher) + case CHILD_PATTERN => SelectChildPattern(x.getMatcher) + case PARENT => SelectParent } }.to(immutable.IndexedSeq) diff --git a/akka-remote/src/main/scala/akka/remote/serialization/MiscMessageSerializer.scala b/akka-remote/src/main/scala/akka/remote/serialization/MiscMessageSerializer.scala index 9333c59632..3ddb5b2ed3 100644 --- a/akka-remote/src/main/scala/akka/remote/serialization/MiscMessageSerializer.scala +++ b/akka-remote/src/main/scala/akka/remote/serialization/MiscMessageSerializer.scala @@ -33,37 +33,37 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW private val EmptyConfig = ConfigFactory.empty() def toBinary(obj: AnyRef): Array[Byte] = obj match { - case identify: Identify ⇒ serializeIdentify(identify) - case identity: ActorIdentity ⇒ serializeActorIdentity(identity) - case Some(value) ⇒ serializeSome(value) - case None ⇒ ParameterlessSerializedMessage - case o: Optional[_] ⇒ serializeOptional(o) - case r: ActorRef ⇒ serializeActorRef(r) - case s: Status.Success ⇒ serializeStatusSuccess(s) - case f: Status.Failure ⇒ serializeStatusFailure(f) - case ex: ActorInitializationException ⇒ serializeActorInitializationException(ex) - case t: Throwable ⇒ throwableSupport.serializeThrowable(t) - case PoisonPill ⇒ ParameterlessSerializedMessage - case Kill ⇒ ParameterlessSerializedMessage - case RemoteWatcher.Heartbeat ⇒ ParameterlessSerializedMessage - case Done ⇒ ParameterlessSerializedMessage - case NotUsed ⇒ ParameterlessSerializedMessage - case hbrsp: RemoteWatcher.HeartbeatRsp ⇒ serializeHeartbeatRsp(hbrsp) - case rs: RemoteScope ⇒ serializeRemoteScope(rs) - case LocalScope ⇒ ParameterlessSerializedMessage - case a: Address ⇒ serializeAddressData(a) - case u: UniqueAddress ⇒ serializeClassicUniqueAddress(u) - case c: Config ⇒ serializeConfig(c) - case dr: DefaultResizer ⇒ serializeDefaultResizer(dr) - case fc: FromConfig ⇒ serializeFromConfig(fc) - case bp: BalancingPool ⇒ serializeBalancingPool(bp) - case bp: BroadcastPool ⇒ serializeBroadcastPool(bp) - case rp: RandomPool ⇒ serializeRandomPool(rp) - case rrp: RoundRobinPool ⇒ serializeRoundRobinPool(rrp) - case sgp: ScatterGatherFirstCompletedPool ⇒ serializeScatterGatherFirstCompletedPool(sgp) - case tp: TailChoppingPool ⇒ serializeTailChoppingPool(tp) - case rrc: RemoteRouterConfig ⇒ serializeRemoteRouterConfig(rrc) - case _ ⇒ throw new IllegalArgumentException(s"Cannot serialize object of type [${obj.getClass.getName}]") + case identify: Identify => serializeIdentify(identify) + case identity: ActorIdentity => serializeActorIdentity(identity) + case Some(value) => serializeSome(value) + case None => ParameterlessSerializedMessage + case o: Optional[_] => serializeOptional(o) + case r: ActorRef => serializeActorRef(r) + case s: Status.Success => serializeStatusSuccess(s) + case f: Status.Failure => serializeStatusFailure(f) + case ex: ActorInitializationException => serializeActorInitializationException(ex) + case t: Throwable => throwableSupport.serializeThrowable(t) + case PoisonPill => ParameterlessSerializedMessage + case Kill => ParameterlessSerializedMessage + case RemoteWatcher.Heartbeat => ParameterlessSerializedMessage + case Done => ParameterlessSerializedMessage + case NotUsed => ParameterlessSerializedMessage + case hbrsp: RemoteWatcher.HeartbeatRsp => serializeHeartbeatRsp(hbrsp) + case rs: RemoteScope => serializeRemoteScope(rs) + case LocalScope => ParameterlessSerializedMessage + case a: Address => serializeAddressData(a) + case u: UniqueAddress => serializeClassicUniqueAddress(u) + case c: Config => serializeConfig(c) + case dr: DefaultResizer => serializeDefaultResizer(dr) + case fc: FromConfig => serializeFromConfig(fc) + case bp: BalancingPool => serializeBalancingPool(bp) + case bp: BroadcastPool => serializeBroadcastPool(bp) + case rp: RandomPool => serializeRandomPool(rp) + case rrp: RoundRobinPool => serializeRoundRobinPool(rrp) + case sgp: ScatterGatherFirstCompletedPool => serializeScatterGatherFirstCompletedPool(sgp) + case tp: TailChoppingPool => serializeTailChoppingPool(tp) + case rrc: RemoteRouterConfig => serializeRemoteRouterConfig(rrc) + case _ => throw new IllegalArgumentException(s"Cannot serialize object of type [${obj.getClass.getName}]") } private def serializeIdentify(identify: Identify): Array[Byte] = @@ -77,7 +77,7 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW ContainerFormats.ActorIdentity.newBuilder() .setCorrelationId(payloadSupport.payloadBuilder(actorIdentity.correlationId)) - actorIdentity.ref.foreach { actorRef ⇒ + actorIdentity.ref.foreach { actorRef => builder.setRef(actorRefBuilder(actorRef)) } @@ -142,23 +142,23 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW private def protoForAddressData(address: Address): AddressData.Builder = address match { - case Address(protocol, actorSystem, Some(host), Some(port)) ⇒ + case Address(protocol, actorSystem, Some(host), Some(port)) => WireFormats.AddressData.newBuilder() .setSystem(actorSystem) .setHostname(host) .setPort(port) .setProtocol(protocol) - case _ ⇒ throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") } private def protoForAddress(address: Address): ArteryControlFormats.Address.Builder = address match { - case Address(protocol, actorSystem, Some(host), Some(port)) ⇒ + case Address(protocol, actorSystem, Some(host), Some(port)) => ArteryControlFormats.Address.newBuilder() .setSystem(actorSystem) .setHostname(host) .setPort(port) .setProtocol(protocol) - case _ ⇒ throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") } private def serializeAddressData(address: Address): Array[Byte] = protoForAddressData(address).build().toByteArray @@ -248,13 +248,13 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW } private def timeUnitToWire(unit: TimeUnit): WireFormats.TimeUnit = unit match { - case TimeUnit.NANOSECONDS ⇒ WireFormats.TimeUnit.NANOSECONDS - case TimeUnit.MICROSECONDS ⇒ WireFormats.TimeUnit.MICROSECONDS - case TimeUnit.MILLISECONDS ⇒ WireFormats.TimeUnit.MILLISECONDS - case TimeUnit.SECONDS ⇒ WireFormats.TimeUnit.SECONDS - case TimeUnit.MINUTES ⇒ WireFormats.TimeUnit.MINUTES - case TimeUnit.HOURS ⇒ WireFormats.TimeUnit.HOURS - case TimeUnit.DAYS ⇒ WireFormats.TimeUnit.DAYS + case TimeUnit.NANOSECONDS => WireFormats.TimeUnit.NANOSECONDS + case TimeUnit.MICROSECONDS => WireFormats.TimeUnit.MICROSECONDS + case TimeUnit.MILLISECONDS => WireFormats.TimeUnit.MILLISECONDS + case TimeUnit.SECONDS => WireFormats.TimeUnit.SECONDS + case TimeUnit.MINUTES => WireFormats.TimeUnit.MINUTES + case TimeUnit.HOURS => WireFormats.TimeUnit.HOURS + case TimeUnit.DAYS => WireFormats.TimeUnit.DAYS } private def buildFiniteDuration(duration: FiniteDuration): WireFormats.FiniteDuration = { @@ -267,14 +267,14 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW private def buildAddressData(address: Address): WireFormats.AddressData = { val builder = WireFormats.AddressData.newBuilder() address match { - case Address(protocol, system, Some(host), Some(port)) ⇒ + case Address(protocol, system, Some(host), Some(port)) => builder.setProtocol(protocol) builder.setSystem(system) builder.setHostname(host) builder.setPort(port) builder.build() - case _ ⇒ throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [$address] could not be serialized: host or port missing.") } } @@ -308,77 +308,77 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW private val TailChoppingPoolManifest = "ROTCP" private val RemoteRouterConfigManifest = "RORRC" - private val fromBinaryMap = Map[String, Array[Byte] ⇒ AnyRef]( - IdentifyManifest → deserializeIdentify, - ActorIdentityManifest → deserializeActorIdentity, - StatusSuccessManifest → deserializeStatusSuccess, - StatusFailureManifest → deserializeStatusFailure, - ThrowableManifest → throwableSupport.deserializeThrowable, - ActorRefManifest → deserializeActorRefBytes, - OptionManifest → deserializeOption, - OptionalManifest → deserializeOptional, - PoisonPillManifest → ((_) ⇒ PoisonPill), - KillManifest → ((_) ⇒ Kill), - RemoteWatcherHBManifest → ((_) ⇒ RemoteWatcher.Heartbeat), - DoneManifest → ((_) ⇒ Done), - NotUsedManifest → ((_) ⇒ NotUsed), - AddressManifest → deserializeAddressData, - UniqueAddressManifest → deserializeUniqueAddress, - RemoteWatcherHBRespManifest → deserializeHeartbeatRsp, - ActorInitializationExceptionManifest → deserializeActorInitializationException, - LocalScopeManifest → ((_) ⇒ LocalScope), - RemoteScopeManifest → deserializeRemoteScope, - ConfigManifest → deserializeConfig, - FromConfigManifest → deserializeFromConfig, - DefaultResizerManifest → deserializeDefaultResizer, - BalancingPoolManifest → deserializeBalancingPool, - BroadcastPoolManifest → deserializeBroadcastPool, - RandomPoolManifest → deserializeRandomPool, - RoundRobinPoolManifest → deserializeRoundRobinPool, - ScatterGatherPoolManifest → deserializeScatterGatherPool, - TailChoppingPoolManifest → deserializeTailChoppingPool, - RemoteRouterConfigManifest → deserializeRemoteRouterConfig + private val fromBinaryMap = Map[String, Array[Byte] => AnyRef]( + IdentifyManifest -> deserializeIdentify, + ActorIdentityManifest -> deserializeActorIdentity, + StatusSuccessManifest -> deserializeStatusSuccess, + StatusFailureManifest -> deserializeStatusFailure, + ThrowableManifest -> throwableSupport.deserializeThrowable, + ActorRefManifest -> deserializeActorRefBytes, + OptionManifest -> deserializeOption, + OptionalManifest -> deserializeOptional, + PoisonPillManifest -> ((_) => PoisonPill), + KillManifest -> ((_) => Kill), + RemoteWatcherHBManifest -> ((_) => RemoteWatcher.Heartbeat), + DoneManifest -> ((_) => Done), + NotUsedManifest -> ((_) => NotUsed), + AddressManifest -> deserializeAddressData, + UniqueAddressManifest -> deserializeUniqueAddress, + RemoteWatcherHBRespManifest -> deserializeHeartbeatRsp, + ActorInitializationExceptionManifest -> deserializeActorInitializationException, + LocalScopeManifest -> ((_) => LocalScope), + RemoteScopeManifest -> deserializeRemoteScope, + ConfigManifest -> deserializeConfig, + FromConfigManifest -> deserializeFromConfig, + DefaultResizerManifest -> deserializeDefaultResizer, + BalancingPoolManifest -> deserializeBalancingPool, + BroadcastPoolManifest -> deserializeBroadcastPool, + RandomPoolManifest -> deserializeRandomPool, + RoundRobinPoolManifest -> deserializeRoundRobinPool, + ScatterGatherPoolManifest -> deserializeScatterGatherPool, + TailChoppingPoolManifest -> deserializeTailChoppingPool, + RemoteRouterConfigManifest -> deserializeRemoteRouterConfig ) override def manifest(o: AnyRef): String = o match { - case _: Identify ⇒ IdentifyManifest - case _: ActorIdentity ⇒ ActorIdentityManifest - case _: Option[Any] ⇒ OptionManifest - case _: Optional[_] ⇒ OptionalManifest - case _: ActorRef ⇒ ActorRefManifest - case _: Status.Success ⇒ StatusSuccessManifest - case _: Status.Failure ⇒ StatusFailureManifest - case _: ActorInitializationException ⇒ ActorInitializationExceptionManifest - case _: Throwable ⇒ ThrowableManifest - case PoisonPill ⇒ PoisonPillManifest - case Kill ⇒ KillManifest - case RemoteWatcher.Heartbeat ⇒ RemoteWatcherHBManifest - case Done ⇒ DoneManifest - case NotUsed ⇒ NotUsedManifest - case _: Address ⇒ AddressManifest - case _: UniqueAddress ⇒ UniqueAddressManifest - case _: RemoteWatcher.HeartbeatRsp ⇒ RemoteWatcherHBRespManifest - case LocalScope ⇒ LocalScopeManifest - case _: RemoteScope ⇒ RemoteScopeManifest - case _: Config ⇒ ConfigManifest - case _: FromConfig ⇒ FromConfigManifest - case _: DefaultResizer ⇒ DefaultResizerManifest - case _: BalancingPool ⇒ BalancingPoolManifest - case _: BroadcastPool ⇒ BroadcastPoolManifest - case _: RandomPool ⇒ RandomPoolManifest - case _: RoundRobinPool ⇒ RoundRobinPoolManifest - case _: ScatterGatherFirstCompletedPool ⇒ ScatterGatherPoolManifest - case _: TailChoppingPool ⇒ TailChoppingPoolManifest - case _: RemoteRouterConfig ⇒ RemoteRouterConfigManifest - case _ ⇒ + case _: Identify => IdentifyManifest + case _: ActorIdentity => ActorIdentityManifest + case _: Option[Any] => OptionManifest + case _: Optional[_] => OptionalManifest + case _: ActorRef => ActorRefManifest + case _: Status.Success => StatusSuccessManifest + case _: Status.Failure => StatusFailureManifest + case _: ActorInitializationException => ActorInitializationExceptionManifest + case _: Throwable => ThrowableManifest + case PoisonPill => PoisonPillManifest + case Kill => KillManifest + case RemoteWatcher.Heartbeat => RemoteWatcherHBManifest + case Done => DoneManifest + case NotUsed => NotUsedManifest + case _: Address => AddressManifest + case _: UniqueAddress => UniqueAddressManifest + case _: RemoteWatcher.HeartbeatRsp => RemoteWatcherHBRespManifest + case LocalScope => LocalScopeManifest + case _: RemoteScope => RemoteScopeManifest + case _: Config => ConfigManifest + case _: FromConfig => FromConfigManifest + case _: DefaultResizer => DefaultResizerManifest + case _: BalancingPool => BalancingPoolManifest + case _: BroadcastPool => BroadcastPoolManifest + case _: RandomPool => RandomPoolManifest + case _: RoundRobinPool => RoundRobinPoolManifest + case _: ScatterGatherFirstCompletedPool => ScatterGatherPoolManifest + case _: TailChoppingPool => TailChoppingPoolManifest + case _: RemoteRouterConfig => RemoteRouterConfigManifest + case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${o.getClass} in [${getClass.getName}]") } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = fromBinaryMap.get(manifest) match { - case Some(deserializer) ⇒ deserializer(bytes) - case None ⇒ throw new NotSerializableException( + case Some(deserializer) => deserializer(bytes) + case None => throw new NotSerializableException( s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } @@ -594,13 +594,13 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW } private def deserializeTimeUnit(unit: WireFormats.TimeUnit): TimeUnit = unit match { - case WireFormats.TimeUnit.NANOSECONDS ⇒ TimeUnit.NANOSECONDS - case WireFormats.TimeUnit.MICROSECONDS ⇒ TimeUnit.MICROSECONDS - case WireFormats.TimeUnit.MILLISECONDS ⇒ TimeUnit.MILLISECONDS - case WireFormats.TimeUnit.SECONDS ⇒ TimeUnit.SECONDS - case WireFormats.TimeUnit.MINUTES ⇒ TimeUnit.MINUTES - case WireFormats.TimeUnit.HOURS ⇒ TimeUnit.HOURS - case WireFormats.TimeUnit.DAYS ⇒ TimeUnit.DAYS + case WireFormats.TimeUnit.NANOSECONDS => TimeUnit.NANOSECONDS + case WireFormats.TimeUnit.MICROSECONDS => TimeUnit.MICROSECONDS + case WireFormats.TimeUnit.MILLISECONDS => TimeUnit.MILLISECONDS + case WireFormats.TimeUnit.SECONDS => TimeUnit.SECONDS + case WireFormats.TimeUnit.MINUTES => TimeUnit.MINUTES + case WireFormats.TimeUnit.HOURS => TimeUnit.HOURS + case WireFormats.TimeUnit.DAYS => TimeUnit.DAYS } private def deserializeFiniteDuration(duration: WireFormats.FiniteDuration): FiniteDuration = diff --git a/akka-remote/src/main/scala/akka/remote/serialization/ProtobufSerializer.scala b/akka-remote/src/main/scala/akka/remote/serialization/ProtobufSerializer.scala index 8bde39e7d3..e7a9dad764 100644 --- a/akka-remote/src/main/scala/akka/remote/serialization/ProtobufSerializer.scala +++ b/akka-remote/src/main/scala/akka/remote/serialization/ProtobufSerializer.scala @@ -47,13 +47,13 @@ class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = { manifest match { - case Some(clazz) ⇒ + case Some(clazz) => @tailrec def parsingMethod(method: Method = null): Method = { val parsingMethodBinding = parsingMethodBindingRef.get() parsingMethodBinding.get(clazz) match { - case Some(cachedParsingMethod) ⇒ cachedParsingMethod - case None ⇒ + case Some(cachedParsingMethod) => cachedParsingMethod + case None => val unCachedParsingMethod = if (method eq null) clazz.getDeclaredMethod("parseFrom", ProtobufSerializer.ARRAY_OF_BYTE_ARRAY: _*) else method @@ -65,7 +65,7 @@ class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer } parsingMethod().invoke(null, bytes) - case None ⇒ throw new IllegalArgumentException("Need a protobuf message class to be able to serialize bytes using protobuf") + case None => throw new IllegalArgumentException("Need a protobuf message class to be able to serialize bytes using protobuf") } } @@ -75,8 +75,8 @@ class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer def toByteArrayMethod(method: Method = null): Method = { val toByteArrayMethodBinding = toByteArrayMethodBindingRef.get() toByteArrayMethodBinding.get(clazz) match { - case Some(cachedtoByteArrayMethod) ⇒ cachedtoByteArrayMethod - case None ⇒ + case Some(cachedtoByteArrayMethod) => cachedtoByteArrayMethod + case None => val unCachedtoByteArrayMethod = if (method eq null) clazz.getMethod("toByteArray") else method diff --git a/akka-remote/src/main/scala/akka/remote/serialization/SystemMessageSerializer.scala b/akka-remote/src/main/scala/akka/remote/serialization/SystemMessageSerializer.scala index ca3e27bb58..e10bfb21b3 100644 --- a/akka-remote/src/main/scala/akka/remote/serialization/SystemMessageSerializer.scala +++ b/akka-remote/src/main/scala/akka/remote/serialization/SystemMessageSerializer.scala @@ -22,49 +22,49 @@ class SystemMessageSerializer(val system: ExtendedActorSystem) extends BaseSeria val builder = SystemMessageFormats.SystemMessage.newBuilder() o.asInstanceOf[SystemMessage] match { - case Create(failure) ⇒ + case Create(failure) => builder.setType(CREATE) failure match { - case Some(throwable) ⇒ builder.setCauseData(serializeThrowable(throwable)) - case None ⇒ // Nothing to set + case Some(throwable) => builder.setCauseData(serializeThrowable(throwable)) + case None => // Nothing to set } - case Recreate(cause) ⇒ + case Recreate(cause) => builder.setType(RECREATE) builder.setCauseData(serializeThrowable(cause)) - case Suspend() ⇒ + case Suspend() => builder.setType(SUSPEND) - case Resume(cause) ⇒ + case Resume(cause) => builder.setType(RESUME) builder.setCauseData(serializeThrowable(cause)) - case Terminate() ⇒ + case Terminate() => builder.setType(TERMINATE) - case Supervise(child, async) ⇒ + case Supervise(child, async) => builder.setType(SUPERVISE) val superviseData = SystemMessageFormats.SuperviseData.newBuilder() .setChild(serializeActorRef(child)) .setAsync(async) builder.setSuperviseData(superviseData) - case Watch(watchee, watcher) ⇒ + case Watch(watchee, watcher) => builder.setType(WATCH) val watchData = SystemMessageFormats.WatchData.newBuilder() .setWatchee(serializeActorRef(watchee)) .setWatcher(serializeActorRef(watcher)) builder.setWatchData(watchData) - case Unwatch(watchee, watcher) ⇒ + case Unwatch(watchee, watcher) => builder.setType(UNWATCH) val watchData = SystemMessageFormats.WatchData.newBuilder() .setWatchee(serializeActorRef(watchee)) .setWatcher(serializeActorRef(watcher)) builder.setWatchData(watchData) - case Failed(child, cause, uid) ⇒ + case Failed(child, cause, uid) => builder.setType(FAILED) val failedData = SystemMessageFormats.FailedData.newBuilder() .setChild(serializeActorRef(child)) @@ -72,7 +72,7 @@ class SystemMessageSerializer(val system: ExtendedActorSystem) extends BaseSeria builder.setCauseData(serializeThrowable(cause)) builder.setFailedData(failedData) - case DeathWatchNotification(actor, existenceConfirmed, addressTerminated) ⇒ + case DeathWatchNotification(actor, existenceConfirmed, addressTerminated) => builder.setType(DEATHWATCH_NOTIFICATION) val deathWatchNotificationData = SystemMessageFormats.DeathWatchNotificationData.newBuilder() .setActor(serializeActorRef(actor)) @@ -80,7 +80,7 @@ class SystemMessageSerializer(val system: ExtendedActorSystem) extends BaseSeria .setAddressTerminated(addressTerminated) builder.setDwNotificationData(deathWatchNotificationData) - case NoMessage ⇒ + case NoMessage => throw new IllegalArgumentException("NoMessage should never be serialized or deserialized") } @@ -93,7 +93,7 @@ class SystemMessageSerializer(val system: ExtendedActorSystem) extends BaseSeria private def deserializeSystemMessage(sysmsg: SystemMessageFormats.SystemMessage): SystemMessage = sysmsg.getType match { - case CREATE ⇒ + case CREATE => val cause = if (sysmsg.hasCauseData) Some(getCauseThrowable(sysmsg).asInstanceOf[ActorInitializationException]) @@ -102,40 +102,40 @@ class SystemMessageSerializer(val system: ExtendedActorSystem) extends BaseSeria Create(cause) - case RECREATE ⇒ + case RECREATE => Recreate(getCauseThrowable(sysmsg)) - case SUSPEND ⇒ + case SUSPEND => // WARNING!! Must always create a new instance! Suspend() - case RESUME ⇒ + case RESUME => Resume(getCauseThrowable(sysmsg)) - case TERMINATE ⇒ + case TERMINATE => // WARNING!! Must always create a new instance! Terminate() - case SUPERVISE ⇒ + case SUPERVISE => Supervise(deserializeActorRef(sysmsg.getSuperviseData.getChild), sysmsg.getSuperviseData.getAsync) - case WATCH ⇒ + case WATCH => Watch( deserializeActorRef(sysmsg.getWatchData.getWatchee).asInstanceOf[InternalActorRef], deserializeActorRef(sysmsg.getWatchData.getWatcher).asInstanceOf[InternalActorRef]) - case UNWATCH ⇒ + case UNWATCH => Unwatch( deserializeActorRef(sysmsg.getWatchData.getWatchee).asInstanceOf[InternalActorRef], deserializeActorRef(sysmsg.getWatchData.getWatcher).asInstanceOf[InternalActorRef]) - case FAILED ⇒ + case FAILED => Failed( deserializeActorRef(sysmsg.getFailedData.getChild), getCauseThrowable(sysmsg), sysmsg.getFailedData.getUid.toInt) - case DEATHWATCH_NOTIFICATION ⇒ + case DEATHWATCH_NOTIFICATION => DeathWatchNotification( deserializeActorRef(sysmsg.getDwNotificationData.getActor), sysmsg.getDwNotificationData.getExistenceConfirmed, diff --git a/akka-remote/src/main/scala/akka/remote/serialization/ThrowableSupport.scala b/akka-remote/src/main/scala/akka/remote/serialization/ThrowableSupport.scala index ba114a73c5..a8c23c13f2 100644 --- a/akka-remote/src/main/scala/akka/remote/serialization/ThrowableSupport.scala +++ b/akka-remote/src/main/scala/akka/remote/serialization/ThrowableSupport.scala @@ -58,7 +58,7 @@ private[akka] class ThrowableSupport(system: ExtendedActorSystem) { val cause = payloadSupport.deserializePayload(protoT.getCause).asInstanceOf[Throwable] system.dynamicAccess.createInstanceFor[Throwable]( protoT.getClassName, - List(classOf[String] → protoT.getMessage, classOf[Throwable] → cause)).get + List(classOf[String] -> protoT.getMessage, classOf[Throwable] -> cause)).get } else { // Important security note: before creating an instance of from the class name we // check that the class is a Throwable and that it has a configured serializer. @@ -67,12 +67,12 @@ private[akka] class ThrowableSupport(system: ExtendedActorSystem) { system.dynamicAccess.createInstanceFor[Throwable]( clazz, - List(classOf[String] → protoT.getMessage)).get + List(classOf[String] -> protoT.getMessage)).get } import scala.collection.JavaConverters._ val stackTrace = - protoT.getStackTraceList.asScala.map { elem ⇒ + protoT.getStackTraceList.asScala.map { elem => val fileName = elem.getFileName new StackTraceElement(elem.getClassName, elem.getMethodName, if (fileName.length > 0) fileName else null, elem.getLineNumber) diff --git a/akka-remote/src/main/scala/akka/remote/transport/AbstractTransportAdapter.scala b/akka-remote/src/main/scala/akka/remote/transport/AbstractTransportAdapter.scala index 9645f66e80..a66dc16fba 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/AbstractTransportAdapter.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/AbstractTransportAdapter.scala @@ -27,15 +27,15 @@ trait TransportAdapterProvider { class TransportAdapters(system: ExtendedActorSystem) extends Extension { val settings = RARP(system).provider.remoteSettings - private val adaptersTable: Map[String, TransportAdapterProvider] = for ((name, fqn) ← settings.Adapters) yield { - name → system.dynamicAccess.createInstanceFor[TransportAdapterProvider](fqn, immutable.Seq.empty).recover({ - case e ⇒ throw new IllegalArgumentException(s"Cannot instantiate transport adapter [${fqn}]", e) + private val adaptersTable: Map[String, TransportAdapterProvider] = for ((name, fqn) <- settings.Adapters) yield { + name -> system.dynamicAccess.createInstanceFor[TransportAdapterProvider](fqn, immutable.Seq.empty).recover({ + case e => throw new IllegalArgumentException(s"Cannot instantiate transport adapter [${fqn}]", e) }).get } def getAdapterProvider(name: String): TransportAdapterProvider = adaptersTable.get(name) match { - case Some(provider) ⇒ provider - case None ⇒ throw new IllegalArgumentException(s"There is no registered transport adapter provider with name: [${name}]") + case Some(provider) => provider + case None => throw new IllegalArgumentException(s"There is no registered transport adapter provider with name: [${name}]") } } @@ -85,10 +85,10 @@ abstract class AbstractTransportAdapter(protected val wrappedTransport: Transpor val upstreamListenerPromise: Promise[AssociationEventListener] = Promise() for { - (listenAddress, listenerPromise) ← wrappedTransport.listen + (listenAddress, listenerPromise) <- wrappedTransport.listen // Enforce ordering between the signalling of "listen ready" to upstream // and initialization happening in interceptListen - _ ← listenerPromise.tryCompleteWith(interceptListen(listenAddress, upstreamListenerPromise.future)).future + _ <- listenerPromise.tryCompleteWith(interceptListen(listenAddress, upstreamListenerPromise.future)).future } yield (augmentScheme(listenAddress), upstreamListenerPromise) } @@ -99,10 +99,10 @@ abstract class AbstractTransportAdapter(protected val wrappedTransport: Transpor */ private[akka] def boundAddress: Address = wrappedTransport match { // Need to do like this in the backport of #15007 to 2.3.x for binary compatibility reasons - case t: AbstractTransportAdapter ⇒ t.boundAddress - case t: netty.NettyTransport ⇒ t.boundAddress - case t: TestTransport ⇒ t.boundAddress - case _ ⇒ null + case t: AbstractTransportAdapter => t.boundAddress + case t: netty.NettyTransport => t.boundAddress + case t: TestTransport => t.boundAddress + case _ => null } override def associate(remoteAddress: Address): Future[AssociationHandle] = { @@ -167,7 +167,7 @@ abstract class ActorTransportAdapter(wrappedTransport: Transport, system: ActorS override def interceptListen( listenAddress: Address, listenerPromise: Future[AssociationEventListener]): Future[AssociationEventListener] = { - registerManager().map { mgr ⇒ + registerManager().map { mgr => // Side effecting: storing the manager instance in volatile var // This is done only once: during the initialization of the protocol stack. The variable manager is not read // before listen is called. @@ -182,8 +182,8 @@ abstract class ActorTransportAdapter(wrappedTransport: Transport, system: ActorS override def shutdown(): Future[Boolean] = for { - stopResult ← gracefulStop(manager, RARP(system).provider.remoteSettings.FlushWait) - wrappedStopResult ← wrappedTransport.shutdown() + stopResult <- gracefulStop(manager, RARP(system).provider.remoteSettings.FlushWait) + wrappedStopResult <- wrappedTransport.shutdown() } yield stopResult && wrappedStopResult } @@ -205,11 +205,11 @@ abstract class ActorTransportAdapterManager extends Actor import context.dispatcher def receive: Receive = { - case ListenUnderlying(listenAddress, upstreamListenerFuture) ⇒ + case ListenUnderlying(listenAddress, upstreamListenerFuture) => localAddress = listenAddress upstreamListenerFuture.future.map { ListenerRegistered(_) } pipeTo self - case ListenerRegistered(listener) ⇒ + case ListenerRegistered(listener) => associationListener = listener delayedEvents foreach { self.tell(_, Actor.noSender) } delayedEvents = immutable.Queue.empty[Any] @@ -219,7 +219,7 @@ abstract class ActorTransportAdapterManager extends Actor * queue. The difference is that these messages will not survive a restart -- which is not needed here. * These messages will be processed in the ready state. */ - case otherEvent ⇒ delayedEvents = delayedEvents enqueue otherEvent + case otherEvent => delayedEvents = delayedEvents enqueue otherEvent } diff --git a/akka-remote/src/main/scala/akka/remote/transport/AkkaPduCodec.scala b/akka-remote/src/main/scala/akka/remote/transport/AkkaPduCodec.scala index e98fdfd01a..697444d7dd 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/AkkaPduCodec.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/AkkaPduCodec.scala @@ -10,7 +10,7 @@ import akka.remote.WireFormats._ import akka.remote._ import akka.util.ByteString import akka.protobuf.InvalidProtocolBufferException -import akka.protobuf.{ ByteString ⇒ PByteString } +import akka.protobuf.{ ByteString => PByteString } import akka.util.OptionVal /** @@ -79,10 +79,10 @@ private[remote] trait AkkaPduCodec { * Encoded form as raw bytes */ def encodePdu(pdu: AkkaPdu): ByteString = pdu match { - case Associate(info) ⇒ constructAssociate(info) - case Payload(bytes) ⇒ constructPayload(bytes) - case Disassociate(reason) ⇒ constructDisassociate(reason) - case Heartbeat ⇒ constructHeartbeat + case Associate(info) => constructAssociate(info) + case Payload(bytes) => constructPayload(bytes) + case Disassociate(reason) => constructDisassociate(reason) + case Heartbeat => constructHeartbeat } def constructPayload(payload: ByteString): ByteString @@ -115,7 +115,7 @@ private[remote] object AkkaPduProtobufCodec extends AkkaPduCodec { private def ackBuilder(ack: Ack): AcknowledgementInfo.Builder = { val ackBuilder = AcknowledgementInfo.newBuilder() ackBuilder.setCumulativeAck(ack.cumulativeAck.rawValue) - ack.nacks foreach { nack ⇒ ackBuilder.addNacks(nack.rawValue) } + ack.nacks foreach { nack => ackBuilder.addNacks(nack.rawValue) } ackBuilder } @@ -133,12 +133,12 @@ private[remote] object AkkaPduProtobufCodec extends AkkaPduCodec { envelopeBuilder.setRecipient(serializeActorRef(recipient.path.address, recipient)) senderOption match { - case OptionVal.Some(sender) ⇒ envelopeBuilder.setSender(serializeActorRef(localAddress, sender)) - case OptionVal.None ⇒ + case OptionVal.Some(sender) => envelopeBuilder.setSender(serializeActorRef(localAddress, sender)) + case OptionVal.None => } - seqOption foreach { seq ⇒ envelopeBuilder.setSeq(seq.rawValue) } - ackOption foreach { ack ⇒ ackAndEnvelopeBuilder.setAck(ackBuilder(ack)) } + seqOption foreach { seq => envelopeBuilder.setSeq(seq.rawValue) } + ackOption foreach { ack => ackAndEnvelopeBuilder.setAck(ackBuilder(ack)) } envelopeBuilder.setMessage(serializedMessage) ackAndEnvelopeBuilder.setEnvelope(envelopeBuilder) @@ -162,9 +162,9 @@ private[remote] object AkkaPduProtobufCodec extends AkkaPduCodec { private val DISASSOCIATE_QUARANTINED = constructControlMessagePdu(WireFormats.CommandType.DISASSOCIATE_QUARANTINED, None) override def constructDisassociate(info: AssociationHandle.DisassociateInfo): ByteString = info match { - case AssociationHandle.Unknown ⇒ DISASSOCIATE - case AssociationHandle.Shutdown ⇒ DISASSOCIATE_SHUTTING_DOWN - case AssociationHandle.Quarantined ⇒ DISASSOCIATE_QUARANTINED + case AssociationHandle.Unknown => DISASSOCIATE + case AssociationHandle.Shutdown => DISASSOCIATE_SHUTTING_DOWN + case AssociationHandle.Quarantined => DISASSOCIATE_QUARANTINED } override val constructHeartbeat: ByteString = @@ -177,7 +177,7 @@ private[remote] object AkkaPduProtobufCodec extends AkkaPduCodec { else if (pdu.hasInstruction) decodeControlPdu(pdu.getInstruction) else throw new PduCodecException("Error decoding Akka PDU: Neither message nor control message were contained", null) } catch { - case e: InvalidProtocolBufferException ⇒ throw new PduCodecException("Decoding PDU failed.", e) + case e: InvalidProtocolBufferException => throw new PduCodecException("Decoding PDU failed.", e) } } @@ -211,7 +211,7 @@ private[remote] object AkkaPduProtobufCodec extends AkkaPduCodec { private def decodeControlPdu(controlPdu: AkkaControlMessage): AkkaPdu = { controlPdu.getCommandType match { - case CommandType.ASSOCIATE if controlPdu.hasHandshakeInfo ⇒ + case CommandType.ASSOCIATE if controlPdu.hasHandshakeInfo => val handshakeInfo = controlPdu.getHandshakeInfo val cookie = if (handshakeInfo.hasCookie) Some(handshakeInfo.getCookie) else None Associate( @@ -219,11 +219,11 @@ private[remote] object AkkaPduProtobufCodec extends AkkaPduCodec { decodeAddress(handshakeInfo.getOrigin), handshakeInfo.getUid.toInt, // 64 bits are allocated in the wire formats, but we use only 32 for now cookie)) - case CommandType.DISASSOCIATE ⇒ Disassociate(AssociationHandle.Unknown) - case CommandType.DISASSOCIATE_SHUTTING_DOWN ⇒ Disassociate(AssociationHandle.Shutdown) - case CommandType.DISASSOCIATE_QUARANTINED ⇒ Disassociate(AssociationHandle.Quarantined) - case CommandType.HEARTBEAT ⇒ Heartbeat - case x ⇒ + case CommandType.DISASSOCIATE => Disassociate(AssociationHandle.Unknown) + case CommandType.DISASSOCIATE_SHUTTING_DOWN => Disassociate(AssociationHandle.Shutdown) + case CommandType.DISASSOCIATE_QUARANTINED => Disassociate(AssociationHandle.Quarantined) + case CommandType.HEARTBEAT => Heartbeat + case x => throw new PduCodecException(s"Decoding of control PDU failed, invalid format, unexpected: [${x}]", null) } } @@ -248,14 +248,14 @@ private[remote] object AkkaPduProtobufCodec extends AkkaPduCodec { } private def serializeAddress(address: Address): AddressData = address match { - case Address(protocol, system, Some(host), Some(port)) ⇒ + case Address(protocol, system, Some(host), Some(port)) => AddressData.newBuilder .setHostname(host) .setPort(port) .setSystem(system) .setProtocol(protocol) .build() - case _ ⇒ throw new IllegalArgumentException(s"Address [${address}] could not be serialized: host or port missing.") + case _ => throw new IllegalArgumentException(s"Address [${address}] could not be serialized: host or port missing.") } } diff --git a/akka-remote/src/main/scala/akka/remote/transport/AkkaProtocolTransport.scala b/akka-remote/src/main/scala/akka/remote/transport/AkkaProtocolTransport.scala index 3d53c49ec4..6fb8e389eb 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/AkkaProtocolTransport.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/AkkaProtocolTransport.scala @@ -133,14 +133,14 @@ private[transport] class AkkaProtocolManager( // The AkkaProtocolTransport does not handle the recovery of associations, this task is implemented in the // remoting itself. Hence the strategy Stop. override val supervisorStrategy = OneForOneStrategy() { - case NonFatal(_) ⇒ Stop + case NonFatal(_) => Stop } private def actorNameFor(remoteAddress: Address): String = "akkaProtocol-" + AddressUrlEncoder(remoteAddress) + "-" + nextId() override def ready: Receive = { - case InboundAssociation(handle) ⇒ + case InboundAssociation(handle) => val stateActorLocalAddress = localAddress val stateActorAssociationHandler = associationListener val stateActorSettings = settings @@ -153,9 +153,9 @@ private[transport] class AkkaProtocolManager( AkkaPduProtobufCodec, failureDetector)), actorNameFor(handle.remoteAddress)) - case AssociateUnderlying(remoteAddress, statusPromise) ⇒ + case AssociateUnderlying(remoteAddress, statusPromise) => createOutboundStateActor(remoteAddress, statusPromise, None) - case AssociateUnderlyingRefuseUid(remoteAddress, statusPromise, refuseUid) ⇒ + case AssociateUnderlyingRefuseUid(remoteAddress, statusPromise, refuseUid) => createOutboundStateActor(remoteAddress, statusPromise, refuseUid) } @@ -326,11 +326,11 @@ private[transport] class ProtocolStateActor( val handshakeTimerKey = "handshake-timer" initialData match { - case d: OutboundUnassociated ⇒ + case d: OutboundUnassociated => d.transport.associate(d.remoteAddress).map(Handle(_)) pipeTo self startWith(Closed, d) - case d: InboundUnassociated ⇒ + case d: InboundUnassociated => d.wrappedHandle.readHandlerPromise.success(ActorHandleEventListener(self)) initHandshakeTimer() startWith(WaitHandshake, d) @@ -341,11 +341,11 @@ private[transport] class ProtocolStateActor( when(Closed) { // Transport layer events for outbound associations - case Event(Status.Failure(e), OutboundUnassociated(_, statusPromise, _)) ⇒ + case Event(Status.Failure(e), OutboundUnassociated(_, statusPromise, _)) => statusPromise.failure(e) stop() - case Event(Handle(wrappedHandle), OutboundUnassociated(_, statusPromise, _)) ⇒ + case Event(Handle(wrappedHandle), OutboundUnassociated(_, statusPromise, _)) => wrappedHandle.readHandlerPromise.trySuccess(ActorHandleEventListener(self)) if (sendAssociate(wrappedHandle, localHandshakeInfo)) { failureDetector.heartbeat() @@ -358,31 +358,31 @@ private[transport] class ProtocolStateActor( stay() } - case Event(DisassociateUnderlying(_), _) ⇒ + case Event(DisassociateUnderlying(_), _) => stop() - case Event(HandshakeTimer, OutboundUnassociated(_, statusPromise, _)) ⇒ + case Event(HandshakeTimer, OutboundUnassociated(_, statusPromise, _)) => val errMsg = "No response from remote for outbound association. Associate timed out after " + s"[${settings.HandshakeTimeout.toMillis} ms]." statusPromise.failure(new TimeoutException(errMsg)) stop(FSM.Failure(TimeoutReason(errMsg))) - case _ ⇒ stay() + case _ => stay() } // Timeout of this state is handled by the HandshakeTimer when(WaitHandshake) { - case Event(Disassociated(info), _) ⇒ + case Event(Disassociated(info), _) => stop(FSM.Failure(info)) - case Event(InboundPayload(p), OutboundUnderlyingAssociated(statusPromise, wrappedHandle)) ⇒ + case Event(InboundPayload(p), OutboundUnderlyingAssociated(statusPromise, wrappedHandle)) => decodePdu(p) match { - case Associate(handshakeInfo) if refuseUid.exists(_ == handshakeInfo.uid) ⇒ + case Associate(handshakeInfo) if refuseUid.exists(_ == handshakeInfo.uid) => sendDisassociate(wrappedHandle, Quarantined) stop(FSM.Failure(ForbiddenUidReason)) - case Associate(handshakeInfo) ⇒ + case Associate(handshakeInfo) => failureDetector.heartbeat() cancelTimer(handshakeTimerKey) goto(Open) using AssociatedWaitHandler( @@ -390,11 +390,11 @@ private[transport] class ProtocolStateActor( wrappedHandle, immutable.Queue.empty) - case Disassociate(info) ⇒ + case Disassociate(info) => // After receiving Disassociate we MUST NOT send back a Disassociate (loop) stop(FSM.Failure(info)) - case msg ⇒ + case msg => // Expected handshake to be finished, dropping connection if (log.isDebugEnabled) log.debug( @@ -405,16 +405,16 @@ private[transport] class ProtocolStateActor( } - case Event(HeartbeatTimer, OutboundUnderlyingAssociated(_, wrappedHandle)) ⇒ handleTimers(wrappedHandle) + case Event(HeartbeatTimer, OutboundUnderlyingAssociated(_, wrappedHandle)) => handleTimers(wrappedHandle) // Events for inbound associations - case Event(InboundPayload(p), InboundUnassociated(associationHandler, wrappedHandle)) ⇒ + case Event(InboundPayload(p), InboundUnassociated(associationHandler, wrappedHandle)) => decodePdu(p) match { // After receiving Disassociate we MUST NOT send back a Disassociate (loop) - case Disassociate(info) ⇒ stop(FSM.Failure(info)) + case Disassociate(info) => stop(FSM.Failure(info)) // Incoming association -- implicitly ACK by a heartbeat - case Associate(info) ⇒ + case Associate(info) => if (!settings.RequireCookie || info.cookie == settings.SecureCookie) { sendAssociate(wrappedHandle, localHandshakeInfo) failureDetector.heartbeat() @@ -435,7 +435,7 @@ private[transport] class ProtocolStateActor( } // Got a stray message -- explicitly reset the association (force remote endpoint to reassociate) - case msg ⇒ + case msg => if (log.isDebugEnabled) log.debug( "Sending disassociate to [{}] because unexpected message of type [{}] was received while unassociated", @@ -445,7 +445,7 @@ private[transport] class ProtocolStateActor( } - case Event(HandshakeTimer, OutboundUnderlyingAssociated(_, wrappedHandle)) ⇒ + case Event(HandshakeTimer, OutboundUnderlyingAssociated(_, wrappedHandle)) => if (log.isDebugEnabled) log.debug( "Sending disassociate to [{}] because handshake timed out for outbound association after [{}] ms.", @@ -455,7 +455,7 @@ private[transport] class ProtocolStateActor( stop(FSM.Failure(TimeoutReason("No response from remote for outbound association. Handshake timed out after " + s"[${settings.HandshakeTimeout.toMillis} ms]."))) - case Event(HandshakeTimer, InboundUnassociated(_, wrappedHandle)) ⇒ + case Event(HandshakeTimer, InboundUnassociated(_, wrappedHandle)) => if (log.isDebugEnabled) log.debug( "Sending disassociate to [{}] because handshake timed out for inbound association after [{}] ms.", @@ -468,43 +468,43 @@ private[transport] class ProtocolStateActor( } when(Open) { - case Event(Disassociated(info), _) ⇒ + case Event(Disassociated(info), _) => stop(FSM.Failure(info)) - case Event(InboundPayload(p), _) ⇒ + case Event(InboundPayload(p), _) => decodePdu(p) match { - case Disassociate(info) ⇒ + case Disassociate(info) => stop(FSM.Failure(info)) - case Heartbeat ⇒ + case Heartbeat => failureDetector.heartbeat() stay() - case Payload(payload) ⇒ + case Payload(payload) => // use incoming ordinary message as alive sign failureDetector.heartbeat() stateData match { - case AssociatedWaitHandler(handlerFuture, wrappedHandle, queue) ⇒ + case AssociatedWaitHandler(handlerFuture, wrappedHandle, queue) => // Queue message until handler is registered stay() using AssociatedWaitHandler(handlerFuture, wrappedHandle, queue :+ payload) - case ListenerReady(listener, _) ⇒ + case ListenerReady(listener, _) => listener notify InboundPayload(payload) stay() - case msg ⇒ + case msg => throw new AkkaProtocolException(s"unhandled message in state Open(InboundPayload) with type [${safeClassName(msg)}]") } - case _ ⇒ stay() + case _ => stay() } - case Event(HeartbeatTimer, AssociatedWaitHandler(_, wrappedHandle, _)) ⇒ handleTimers(wrappedHandle) - case Event(HeartbeatTimer, ListenerReady(_, wrappedHandle)) ⇒ handleTimers(wrappedHandle) + case Event(HeartbeatTimer, AssociatedWaitHandler(_, wrappedHandle, _)) => handleTimers(wrappedHandle) + case Event(HeartbeatTimer, ListenerReady(_, wrappedHandle)) => handleTimers(wrappedHandle) - case Event(DisassociateUnderlying(info: DisassociateInfo), _) ⇒ + case Event(DisassociateUnderlying(info: DisassociateInfo), _) => val handle = stateData match { - case ListenerReady(_, wrappedHandle) ⇒ wrappedHandle - case AssociatedWaitHandler(_, wrappedHandle, _) ⇒ wrappedHandle - case msg ⇒ + case ListenerReady(_, wrappedHandle) => wrappedHandle + case AssociatedWaitHandler(_, wrappedHandle, _) => wrappedHandle + case msg => throw new AkkaProtocolException(s"unhandled message in state Open(DisassociateUnderlying) with type [${safeClassName(msg)}]") } // No debug logging here as sending DisassociateUnderlying(Unknown) should have been logged from where @@ -513,7 +513,7 @@ private[transport] class ProtocolStateActor( sendDisassociate(handle, info) stop() - case Event(HandleListenerRegistered(listener), AssociatedWaitHandler(_, wrappedHandle, queue)) ⇒ + case Event(HandleListenerRegistered(listener), AssociatedWaitHandler(_, wrappedHandle, queue)) => queue.foreach { listener notify InboundPayload(_) } stay() using ListenerReady(listener, wrappedHandle) } @@ -544,8 +544,8 @@ private[transport] class ProtocolStateActor( } private def safeClassName(obj: AnyRef): String = obj match { - case null ⇒ "null" - case _ ⇒ obj.getClass.getName + case null => "null" + case _ => obj.getClass.getName } override def postStop(): Unit = { @@ -554,64 +554,64 @@ private[transport] class ProtocolStateActor( } onTermination { - case StopEvent(reason, _, OutboundUnassociated(_, statusPromise, _)) ⇒ + case StopEvent(reason, _, OutboundUnassociated(_, statusPromise, _)) => statusPromise.tryFailure(reason match { - case FSM.Failure(info: DisassociateInfo) ⇒ disassociateException(info) - case _ ⇒ new AkkaProtocolException("Transport disassociated before handshake finished") + case FSM.Failure(info: DisassociateInfo) => disassociateException(info) + case _ => new AkkaProtocolException("Transport disassociated before handshake finished") }) - case StopEvent(reason, _, OutboundUnderlyingAssociated(statusPromise, wrappedHandle)) ⇒ + case StopEvent(reason, _, OutboundUnderlyingAssociated(statusPromise, wrappedHandle)) => statusPromise.tryFailure(reason match { - case FSM.Failure(TimeoutReason(errorMessage)) ⇒ + case FSM.Failure(TimeoutReason(errorMessage)) => new AkkaProtocolException(errorMessage) - case FSM.Failure(info: DisassociateInfo) ⇒ + case FSM.Failure(info: DisassociateInfo) => disassociateException(info) - case FSM.Failure(ForbiddenUidReason) ⇒ + case FSM.Failure(ForbiddenUidReason) => InvalidAssociationException("The remote system has a UID that has been quarantined. Association aborted.") - case _ ⇒ + case _ => new AkkaProtocolException("Transport disassociated before handshake finished") }) wrappedHandle.disassociate(disassociationReason(reason), log) - case StopEvent(reason, _, AssociatedWaitHandler(handlerFuture, wrappedHandle, _)) ⇒ + case StopEvent(reason, _, AssociatedWaitHandler(handlerFuture, wrappedHandle, _)) => // Invalidate exposed but still unfinished promise. The underlying association disappeared, so after // registration immediately signal a disassociate val disassociateNotification = reason match { - case FSM.Failure(info: DisassociateInfo) ⇒ Disassociated(info) - case _ ⇒ Disassociated(Unknown) + case FSM.Failure(info: DisassociateInfo) => Disassociated(info) + case _ => Disassociated(Unknown) } handlerFuture foreach { _ notify disassociateNotification } wrappedHandle.disassociate(disassociationReason(reason), log) - case StopEvent(reason, _, ListenerReady(handler, wrappedHandle)) ⇒ + case StopEvent(reason, _, ListenerReady(handler, wrappedHandle)) => val disassociateNotification = reason match { - case FSM.Failure(info: DisassociateInfo) ⇒ Disassociated(info) - case _ ⇒ Disassociated(Unknown) + case FSM.Failure(info: DisassociateInfo) => Disassociated(info) + case _ => Disassociated(Unknown) } handler notify disassociateNotification wrappedHandle.disassociate(disassociationReason(reason), log) - case StopEvent(reason, _, InboundUnassociated(_, wrappedHandle)) ⇒ + case StopEvent(reason, _, InboundUnassociated(_, wrappedHandle)) => wrappedHandle.disassociate(disassociationReason(reason), log) } private def disassociateException(info: DisassociateInfo): Exception = info match { - case Unknown ⇒ + case Unknown => new AkkaProtocolException("The remote system explicitly disassociated (reason unknown).") - case Shutdown ⇒ + case Shutdown => InvalidAssociationException("The remote system refused the association because it is shutting down.") - case Quarantined ⇒ + case Quarantined => InvalidAssociationException("The remote system has quarantined this system. No further associations to the remote " + "system are possible until this system is restarted.") } override protected def logTermination(reason: FSM.Reason): Unit = reason match { - case FSM.Failure(_: DisassociateInfo) ⇒ // no logging - case FSM.Failure(ForbiddenUidReason) ⇒ // no logging - case FSM.Failure(TimeoutReason(errorMessage)) ⇒ + case FSM.Failure(_: DisassociateInfo) => // no logging + case FSM.Failure(ForbiddenUidReason) => // no logging + case FSM.Failure(TimeoutReason(errorMessage)) => log.info(errorMessage) - case _ ⇒ super.logTermination(reason) + case _ => super.logTermination(reason) } private def listenForListenerRegistration(readHandlerPromise: Promise[HandleEventListener]): Unit = @@ -656,30 +656,30 @@ private[transport] class ProtocolStateActor( } private def decodePdu(pdu: ByteString): AkkaPdu = try codec.decodePdu(pdu) catch { - case NonFatal(e) ⇒ throw new AkkaProtocolException("Error while decoding incoming Akka PDU of length: " + pdu.length, e) + case NonFatal(e) => throw new AkkaProtocolException("Error while decoding incoming Akka PDU of length: " + pdu.length, e) } // Neither heartbeats neither disassociate cares about backing off if write fails: // - Missing heartbeats are not critical // - Disassociate messages are not guaranteed anyway private def sendHeartbeat(wrappedHandle: AssociationHandle): Boolean = try wrappedHandle.write(codec.constructHeartbeat) catch { - case NonFatal(e) ⇒ throw new AkkaProtocolException("Error writing HEARTBEAT to transport", e) + case NonFatal(e) => throw new AkkaProtocolException("Error writing HEARTBEAT to transport", e) } private def sendDisassociate(wrappedHandle: AssociationHandle, info: DisassociateInfo): Unit = try wrappedHandle.write(codec.constructDisassociate(info)) catch { - case NonFatal(e) ⇒ throw new AkkaProtocolException("Error writing DISASSOCIATE to transport", e) + case NonFatal(e) => throw new AkkaProtocolException("Error writing DISASSOCIATE to transport", e) } private def sendAssociate(wrappedHandle: AssociationHandle, info: HandshakeInfo): Boolean = try { wrappedHandle.write(codec.constructAssociate(info)) } catch { - case NonFatal(e) ⇒ throw new AkkaProtocolException("Error writing ASSOCIATE to transport", e) + case NonFatal(e) => throw new AkkaProtocolException("Error writing ASSOCIATE to transport", e) } private def disassociationReason(reason: FSM.Reason): String = reason match { - case FSM.Normal ⇒ "the ProtocolStateActor was stopped normally" - case FSM.Shutdown ⇒ "the ProtocolStateActor was shutdown" - case FSM.Failure(ex) ⇒ s"the ProtocolStateActor failed: $ex" + case FSM.Normal => "the ProtocolStateActor was stopped normally" + case FSM.Shutdown => "the ProtocolStateActor was shutdown" + case FSM.Failure(ex) => s"the ProtocolStateActor failed: $ex" } } diff --git a/akka-remote/src/main/scala/akka/remote/transport/FailureInjectorTransportAdapter.scala b/akka-remote/src/main/scala/akka/remote/transport/FailureInjectorTransportAdapter.scala index dc048758f2..39f2c9f886 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/FailureInjectorTransportAdapter.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/FailureInjectorTransportAdapter.scala @@ -69,14 +69,14 @@ private[remote] class FailureInjectorTransportAdapter(wrappedTransport: Transpor protected def maximumOverhead = 0 override def managementCommand(cmd: Any): Future[Boolean] = cmd match { - case All(mode) ⇒ + case All(mode) => allMode = mode Future.successful(true) - case One(address, mode) ⇒ + case One(address, mode) => // don't care about the protocol part - we are injected in the stack anyway! addressChaosTable.put(address.copy(protocol = "", system = ""), mode) Future.successful(true) - case _ ⇒ wrappedTransport.managementCommand(cmd) + case _ => wrappedTransport.managementCommand(cmd) } protected def interceptListen( @@ -87,7 +87,7 @@ private[remote] class FailureInjectorTransportAdapter(wrappedTransport: Transpor // Side effecting: As this class is not an actor, the only way to safely modify state is through volatile vars. // Listen is called only during the initialization of the stack, and upstreamListener is not read before this // finishes. - listener ⇒ upstreamListener = Some(listener) + listener => upstreamListener = Some(listener) } Future.successful(this) } @@ -97,28 +97,28 @@ private[remote] class FailureInjectorTransportAdapter(wrappedTransport: Transpor if (shouldDropInbound(remoteAddress, Unit, "interceptAssociate") || shouldDropOutbound(remoteAddress, Unit, "interceptAssociate")) statusPromise.failure(new FailureInjectorException("Simulated failure of association to " + remoteAddress)) else - statusPromise.completeWith(wrappedTransport.associate(remoteAddress).map { handle ⇒ + statusPromise.completeWith(wrappedTransport.associate(remoteAddress).map { handle => addressChaosTable.putIfAbsent(handle.remoteAddress.copy(protocol = "", system = ""), PassThru) new FailureInjectorHandle(handle, this) }) } def notify(ev: AssociationEvent): Unit = ev match { - case InboundAssociation(handle) if shouldDropInbound(handle.remoteAddress, ev, "notify") ⇒ //Ignore - case _ ⇒ upstreamListener match { - case Some(listener) ⇒ listener notify interceptInboundAssociation(ev) - case None ⇒ + case InboundAssociation(handle) if shouldDropInbound(handle.remoteAddress, ev, "notify") => //Ignore + case _ => upstreamListener match { + case Some(listener) => listener notify interceptInboundAssociation(ev) + case None => } } def interceptInboundAssociation(ev: AssociationEvent): AssociationEvent = ev match { - case InboundAssociation(handle) ⇒ InboundAssociation(FailureInjectorHandle(handle, this)) - case _ ⇒ ev + case InboundAssociation(handle) => InboundAssociation(FailureInjectorHandle(handle, this)) + case _ => ev } def shouldDropInbound(remoteAddress: Address, instance: Any, debugMessage: String): Boolean = chaosMode(remoteAddress) match { - case PassThru ⇒ false - case Drop(_, inboundDropP) ⇒ + case PassThru => false + case Drop(_, inboundDropP) => if (rng.nextDouble() <= inboundDropP) { if (shouldDebugLog) log.debug("Dropping inbound [{}] for [{}] {}", instance.getClass, remoteAddress, debugMessage) true @@ -126,8 +126,8 @@ private[remote] class FailureInjectorTransportAdapter(wrappedTransport: Transpor } def shouldDropOutbound(remoteAddress: Address, instance: Any, debugMessage: String): Boolean = chaosMode(remoteAddress) match { - case PassThru ⇒ false - case Drop(outboundDropP, _) ⇒ + case PassThru => false + case Drop(outboundDropP, _) => if (rng.nextDouble() <= outboundDropP) { if (shouldDebugLog) log.debug("Dropping outbound [{}] for [{}] {}", instance.getClass, remoteAddress, debugMessage) true @@ -154,7 +154,7 @@ private[remote] final case class FailureInjectorHandle( override val readHandlerPromise: Promise[HandleEventListener] = Promise() readHandlerPromise.future.foreach { - listener ⇒ + listener => upstreamListener = listener wrappedHandle.readHandlerPromise.success(this) } diff --git a/akka-remote/src/main/scala/akka/remote/transport/TestTransport.scala b/akka-remote/src/main/scala/akka/remote/transport/TestTransport.scala index c5cef1fdd4..fb34301ecf 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/TestTransport.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/TestTransport.scala @@ -51,31 +51,31 @@ class TestTransport( private def defaultAssociate(remoteAddress: Address): Future[AssociationHandle] = { registry.transportFor(remoteAddress) match { - case Some((remoteTransport, remoteListenerFuture)) ⇒ + case Some((remoteTransport, remoteListenerFuture)) => val (localHandle, remoteHandle) = createHandlePair(remoteTransport, remoteAddress) localHandle.writable = false remoteHandle.writable = false // Pass a non-writable handle to remote first remoteListenerFuture flatMap { - case listener ⇒ + case listener => listener notify InboundAssociation(remoteHandle) val remoteHandlerFuture = remoteHandle.readHandlerPromise.future // Registration of reader at local finishes the registration and enables communication for { - remoteListener ← remoteHandlerFuture - localListener ← localHandle.readHandlerPromise.future + remoteListener <- remoteHandlerFuture + localListener <- localHandle.readHandlerPromise.future } { registry.registerListenerPair(localHandle.key, (localListener, remoteListener)) localHandle.writable = true remoteHandle.writable = true } - remoteHandlerFuture.map { _ ⇒ localHandle } + remoteHandlerFuture.map { _ => localHandle } } - case None ⇒ + case None => Future.failed(new InvalidAssociationException(s"No registered transport: $remoteAddress", null)) } } @@ -93,22 +93,22 @@ class TestTransport( * The [[akka.remote.transport.TestTransport.SwitchableLoggedBehavior]] for the listen() method. */ val listenBehavior = new SwitchableLoggedBehavior[Unit, (Address, Promise[AssociationEventListener])]( - (_) ⇒ defaultListen, - (_) ⇒ registry.logActivity(ListenAttempt(localAddress))) + (_) => defaultListen, + (_) => registry.logActivity(ListenAttempt(localAddress))) /** * The [[akka.remote.transport.TestTransport.SwitchableLoggedBehavior]] for the associate() method. */ val associateBehavior = new SwitchableLoggedBehavior[Address, AssociationHandle]( defaultAssociate _, - (remoteAddress) ⇒ registry.logActivity(AssociateAttempt(localAddress, remoteAddress))) + (remoteAddress) => registry.logActivity(AssociateAttempt(localAddress, remoteAddress))) /** * The [[akka.remote.transport.TestTransport.SwitchableLoggedBehavior]] for the shutdown() method. */ val shutdownBehavior = new SwitchableLoggedBehavior[Unit, Boolean]( - (_) ⇒ defaultShutdown, - (_) ⇒ registry.logActivity(ShutdownAttempt(localAddress))) + (_) => defaultShutdown, + (_) => registry.logActivity(ShutdownAttempt(localAddress))) override def listen: Future[(Address, Promise[AssociationEventListener])] = listenBehavior(()) // Need to do like this for binary compatibility reasons @@ -118,10 +118,10 @@ class TestTransport( private def defaultWrite(params: (TestAssociationHandle, ByteString)): Future[Boolean] = { registry.getRemoteReadHandlerFor(params._1) match { - case Some(listener) ⇒ + case Some(listener) => listener notify InboundPayload(params._2) Future.successful(true) - case None ⇒ + case None => Future.failed(new IllegalStateException("No association present")) } } @@ -144,7 +144,7 @@ class TestTransport( defaultWrite _ }, logCallback = { - case (handle, payload) ⇒ + case (handle, payload) => registry.logActivity(WriteAttempt(handle.localAddress, handle.remoteAddress, payload)) }) @@ -157,7 +157,7 @@ class TestTransport( defaultDisassociate _ }, logCallback = { - (handle) ⇒ + (handle) => registry.logActivity(DisassociateAttempt(handle.localAddress, handle.remoteAddress)) }) @@ -172,7 +172,7 @@ class TestTransport( object TestTransport { - type Behavior[A, B] = (A) ⇒ Future[B] + type Behavior[A, B] = (A) => Future[B] /** * Test utility to make behavior of functions that return some Future[B] controllable from tests. This tool is able @@ -195,7 +195,7 @@ object TestTransport { * type parameter B: * - Type parameter of the future that the original function returns. */ - class SwitchableLoggedBehavior[A, B](defaultBehavior: Behavior[A, B], logCallback: (A) ⇒ Unit) extends Behavior[A, B] { + class SwitchableLoggedBehavior[A, B](defaultBehavior: Behavior[A, B], logCallback: (A) => Unit) extends Behavior[A, B] { private val behaviorStack = new CopyOnWriteArrayList[Behavior[A, B]]() behaviorStack.add(0, defaultBehavior) @@ -217,7 +217,7 @@ object TestTransport { * The constant the future will be completed with. */ def pushConstant(c: B): Unit = push { - _ ⇒ Future.successful(c) + _ => Future.successful(c) } /** @@ -227,7 +227,7 @@ object TestTransport { * The throwable the failed future will contain. */ def pushError(e: Throwable): Unit = push { - _ ⇒ Future.failed(e) + _ => Future.failed(e) } /** @@ -242,7 +242,7 @@ object TestTransport { val originalBehavior = currentBehavior push( - (params: A) ⇒ controlPromise.future.flatMap(_ ⇒ originalBehavior(params))) + (params: A) => controlPromise.future.flatMap(_ => originalBehavior(params))) controlPromise } @@ -303,7 +303,7 @@ object TestTransport { handle: TestAssociationHandle, listenerPair: (HandleEventListener, HandleEventListener)): HandleEventListener = { listenerPair match { - case (initiator, receiver) ⇒ if (handle.inbound) initiator else receiver + case (initiator, receiver) => if (handle.inbound) initiator else receiver } } diff --git a/akka-remote/src/main/scala/akka/remote/transport/ThrottlerTransportAdapter.scala b/akka-remote/src/main/scala/akka/remote/transport/ThrottlerTransportAdapter.scala index 6d393ee351..458e9f420c 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/ThrottlerTransportAdapter.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/ThrottlerTransportAdapter.scala @@ -47,8 +47,8 @@ object ThrottlerTransportAdapter { @SerialVersionUID(1L) case object Send extends Direction { override def includes(other: Direction): Boolean = other match { - case Send ⇒ true - case _ ⇒ false + case Send => true + case _ => false } /** @@ -60,8 +60,8 @@ object ThrottlerTransportAdapter { @SerialVersionUID(1L) case object Receive extends Direction { override def includes(other: Direction): Boolean = other match { - case Receive ⇒ true - case _ ⇒ false + case Receive => true + case _ => false } /** @@ -205,10 +205,10 @@ class ThrottlerTransportAdapter(_wrappedTransport: Transport, _system: ExtendedA override def managementCommand(cmd: Any): Future[Boolean] = { import ActorTransportAdapter.AskTimeout cmd match { - case s: SetThrottle ⇒ manager ? s map { case SetThrottleAck ⇒ true } - case f: ForceDisassociate ⇒ manager ? f map { case ForceDisassociateAck ⇒ true } - case f: ForceDisassociateExplicitly ⇒ manager ? f map { case ForceDisassociateAck ⇒ true } - case _ ⇒ wrappedTransport.managementCommand(cmd) + case s: SetThrottle => manager ? s map { case SetThrottleAck => true } + case f: ForceDisassociate => manager ? f map { case ForceDisassociateAck => true } + case f: ForceDisassociateExplicitly => manager ? f map { case ForceDisassociateAck => true } + case _ => wrappedTransport.managementCommand(cmd) } } } @@ -244,72 +244,72 @@ private[transport] class ThrottlerManager(wrappedTransport: Transport) private def nakedAddress(address: Address): Address = address.copy(protocol = "", system = "") override def ready: Receive = { - case InboundAssociation(handle) ⇒ + case InboundAssociation(handle) => val wrappedHandle = wrapHandle(handle, associationListener, inbound = true) wrappedHandle.throttlerActor ! Handle(wrappedHandle) - case AssociateUnderlying(remoteAddress, statusPromise) ⇒ + case AssociateUnderlying(remoteAddress, statusPromise) => wrappedTransport.associate(remoteAddress) onComplete { // Slight modification of pipe, only success is sent, failure is propagated to a separate future - case Success(handle) ⇒ self ! AssociateResult(handle, statusPromise) - case Failure(e) ⇒ statusPromise.failure(e) + case Success(handle) => self ! AssociateResult(handle, statusPromise) + case Failure(e) => statusPromise.failure(e) } // Finished outbound association and got back the handle - case AssociateResult(handle, statusPromise) ⇒ + case AssociateResult(handle, statusPromise) => val wrappedHandle = wrapHandle(handle, associationListener, inbound = false) val naked = nakedAddress(handle.remoteAddress) val inMode = getInboundMode(naked) wrappedHandle.outboundThrottleMode.set(getOutboundMode(naked)) wrappedHandle.readHandlerPromise.future map { ListenerAndMode(_, inMode) } pipeTo wrappedHandle.throttlerActor - handleTable ::= naked → wrappedHandle + handleTable ::= naked -> wrappedHandle statusPromise.success(wrappedHandle) - case SetThrottle(address, direction, mode) ⇒ + case SetThrottle(address, direction, mode) => val naked = nakedAddress(address) throttlingModes = throttlingModes.updated(naked, (mode, direction)) val ok = Future.successful(SetThrottleAck) Future.sequence(handleTable map { - case (`naked`, handle) ⇒ setMode(handle, mode, direction) - case _ ⇒ ok - }).map(_ ⇒ SetThrottleAck) pipeTo sender() - case ForceDisassociate(address) ⇒ + case (`naked`, handle) => setMode(handle, mode, direction) + case _ => ok + }).map(_ => SetThrottleAck) pipeTo sender() + case ForceDisassociate(address) => val naked = nakedAddress(address) handleTable foreach { - case (`naked`, handle) ⇒ handle.disassociate(s"the disassociation was forced by ${sender()}", log) - case _ ⇒ + case (`naked`, handle) => handle.disassociate(s"the disassociation was forced by ${sender()}", log) + case _ => } sender() ! ForceDisassociateAck - case ForceDisassociateExplicitly(address, reason) ⇒ + case ForceDisassociateExplicitly(address, reason) => val naked = nakedAddress(address) handleTable foreach { - case (`naked`, handle) ⇒ handle.disassociateWithFailure(reason) - case _ ⇒ + case (`naked`, handle) => handle.disassociateWithFailure(reason) + case _ => } sender() ! ForceDisassociateAck - case Checkin(origin, handle) ⇒ + case Checkin(origin, handle) => val naked: Address = nakedAddress(origin) - handleTable ::= naked → handle + handleTable ::= naked -> handle setMode(naked, handle) } private def getInboundMode(nakedAddress: Address): ThrottleMode = { throttlingModes.get(nakedAddress) match { - case Some((mode, direction)) if direction.includes(Direction.Receive) ⇒ mode - case _ ⇒ Unthrottled + case Some((mode, direction)) if direction.includes(Direction.Receive) => mode + case _ => Unthrottled } } private def getOutboundMode(nakedAddress: Address): ThrottleMode = { throttlingModes.get(nakedAddress) match { - case Some((mode, direction)) if direction.includes(Direction.Send) ⇒ mode - case _ ⇒ Unthrottled + case Some((mode, direction)) if direction.includes(Direction.Send) => mode + case _ => Unthrottled } } private def setMode(nakedAddress: Address, handle: ThrottlerHandle): Future[SetThrottleAck.type] = { throttlingModes.get(nakedAddress) match { - case Some((mode, direction)) ⇒ setMode(handle, mode, direction) - case None ⇒ setMode(handle, Unthrottled, Direction.Both) + case Some((mode, direction)) => setMode(handle, mode, direction) + case None => setMode(handle, Unthrottled, Direction.Both) } } @@ -330,9 +330,9 @@ private[transport] class ThrottlerManager(wrappedTransport: Transport) internalTarget.sendSystemMessage(Watch(internalTarget, ref)) target.tell(mode, ref) ref.result.future.transform({ - case Terminated(t) if t.path == target.path ⇒ SetThrottleAck - case SetThrottleAck ⇒ { internalTarget.sendSystemMessage(Unwatch(target, ref)); SetThrottleAck } - }, t ⇒ { internalTarget.sendSystemMessage(Unwatch(target, ref)); t })(ref.internalCallingThreadExecutionContext) + case Terminated(t) if t.path == target.path => SetThrottleAck + case SetThrottleAck => { internalTarget.sendSystemMessage(Unwatch(target, ref)); SetThrottleAck } + }, t => { internalTarget.sendSystemMessage(Unwatch(target, ref)); t })(ref.internalCallingThreadExecutionContext) } } @@ -409,28 +409,28 @@ private[transport] class ThrottledAssociation( } when(WaitExposedHandle) { - case Event(Handle(handle), Uninitialized) ⇒ + case Event(Handle(handle), Uninitialized) => // register to downstream layer and wait for origin originalHandle.readHandlerPromise.success(ActorHandleEventListener(self)) goto(WaitOrigin) using ExposedHandle(handle) } when(WaitOrigin) { - case Event(InboundPayload(p), ExposedHandle(exposedHandle)) ⇒ + case Event(InboundPayload(p), ExposedHandle(exposedHandle)) => throttledMessages = throttledMessages enqueue p peekOrigin(p) match { - case Some(origin) ⇒ + case Some(origin) => manager ! Checkin(origin, exposedHandle) goto(WaitMode) - case None ⇒ stay() + case None => stay() } } when(WaitMode) { - case Event(InboundPayload(p), _) ⇒ + case Event(InboundPayload(p), _) => throttledMessages = throttledMessages enqueue p stay() - case Event(mode: ThrottleMode, ExposedHandle(exposedHandle)) ⇒ + case Event(mode: ThrottleMode, ExposedHandle(exposedHandle)) => inboundThrottleMode = mode try if (mode == Blackhole) { throttledMessages = Queue.empty[ByteString] @@ -444,28 +444,28 @@ private[transport] class ThrottledAssociation( } when(WaitUpstreamListener) { - case Event(InboundPayload(p), _) ⇒ + case Event(InboundPayload(p), _) => throttledMessages = throttledMessages enqueue p stay() - case Event(Listener(listener), _) ⇒ + case Event(Listener(listener), _) => upstreamListener = listener self ! Dequeue goto(Throttling) } when(WaitModeAndUpstreamListener) { - case Event(ListenerAndMode(listener: HandleEventListener, mode: ThrottleMode), _) ⇒ + case Event(ListenerAndMode(listener: HandleEventListener, mode: ThrottleMode), _) => upstreamListener = listener inboundThrottleMode = mode self ! Dequeue goto(Throttling) - case Event(InboundPayload(p), _) ⇒ + case Event(InboundPayload(p), _) => throttledMessages = throttledMessages enqueue p stay() } when(Throttling) { - case Event(mode: ThrottleMode, _) ⇒ + case Event(mode: ThrottleMode, _) => inboundThrottleMode = mode if (mode == Blackhole) throttledMessages = Queue.empty[ByteString] cancelTimer(DequeueTimerName) @@ -473,11 +473,11 @@ private[transport] class ThrottledAssociation( scheduleDequeue(inboundThrottleMode.timeToAvailable(System.nanoTime(), throttledMessages.head.length)) sender() ! SetThrottleAck stay() - case Event(InboundPayload(p), _) ⇒ + case Event(InboundPayload(p), _) => forwardOrDelay(p) stay() - case Event(Dequeue, _) ⇒ + case Event(Dequeue, _) => if (throttledMessages.nonEmpty) { val (payload, newqueue) = throttledMessages.dequeue upstreamListener notify InboundPayload(payload) @@ -492,13 +492,13 @@ private[transport] class ThrottledAssociation( whenUnhandled { // we should always set the throttling mode - case Event(mode: ThrottleMode, _) ⇒ + case Event(mode: ThrottleMode, _) => inboundThrottleMode = mode sender() ! SetThrottleAck stay() - case Event(Disassociated(_), _) ⇒ + case Event(Disassociated(_), _) => stop() // not notifying the upstream handler is intentional: we are relying on heartbeating - case Event(FailWith(reason), _) ⇒ + case Event(FailWith(reason), _) => if (upstreamListener ne null) upstreamListener notify Disassociated(reason) stop() } @@ -507,13 +507,13 @@ private[transport] class ThrottledAssociation( private def peekOrigin(b: ByteString): Option[Address] = { try { AkkaPduProtobufCodec.decodePdu(b) match { - case Associate(info) ⇒ Some(info.origin) - case _ ⇒ None + case Associate(info) => Some(info.origin) + case _ => None } } catch { // This layer should not care about malformed packets. Also, this also useful for testing, because // arbitrary payload could be passed in - case NonFatal(_) ⇒ None + case NonFatal(_) => None } } @@ -538,9 +538,9 @@ private[transport] class ThrottledAssociation( } def scheduleDequeue(delay: FiniteDuration): Unit = inboundThrottleMode match { - case Blackhole ⇒ // Do nothing - case _ if delay <= Duration.Zero ⇒ self ! Dequeue - case _ ⇒ setTimer(DequeueTimerName, Dequeue, delay, repeat = false) + case Blackhole => // Do nothing + case _ if delay <= Duration.Zero => self ! Dequeue + case _ => setTimer(DequeueTimerName, Dequeue, delay, repeat = false) } } @@ -568,8 +568,8 @@ private[transport] final case class ThrottlerHandle(_wrappedHandle: AssociationH } outboundThrottleMode.get match { - case Blackhole ⇒ true - case bucket @ _ ⇒ + case Blackhole => true + case bucket @ _ => val success = tryConsume(outboundThrottleMode.get()) if (success) wrappedHandle.write(payload) else false // FIXME: this depletes the token bucket even when no write happened!! See #2825 diff --git a/akka-remote/src/main/scala/akka/remote/transport/netty/NettyHelpers.scala b/akka-remote/src/main/scala/akka/remote/transport/netty/NettyHelpers.scala index 5b35e384c6..283e487ed2 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/netty/NettyHelpers.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/netty/NettyHelpers.scala @@ -30,9 +30,9 @@ private[netty] trait NettyHelpers { final protected def transformException(@unused ctx: ChannelHandlerContext, ev: ExceptionEvent): Unit = { val cause = if (ev.getCause ne null) ev.getCause else new AkkaException("Unknown cause") cause match { - case _: ClosedChannelException ⇒ // Ignore - case null | NonFatal(_) ⇒ onException(ctx, ev) - case e: Throwable ⇒ throw e // Rethrow fatals + case _: ClosedChannelException => // Ignore + case null | NonFatal(_) => onException(ctx, ev) + case e: Throwable => throw e // Rethrow fatals } } } diff --git a/akka-remote/src/main/scala/akka/remote/transport/netty/NettyTransport.scala b/akka-remote/src/main/scala/akka/remote/transport/netty/NettyTransport.scala index aea7a87133..181a59893e 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/netty/NettyTransport.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/netty/NettyTransport.scala @@ -85,8 +85,8 @@ object NettyFutureBridge { def operationComplete(future: ChannelGroupFuture): Unit = p complete Try( if (future.isCompleteSuccess) future.getGroup else throw future.iterator.asScala.collectFirst { - case f if f.isCancelled ⇒ new CancellationException - case f if !f.isSuccess ⇒ f.getCause + case f if f.isCancelled => new CancellationException + case f if !f.isSuccess => f.getCause } getOrElse new IllegalStateException("Error reported in ChannelGroupFuture, but no error found in individual futures.")) }) p.future @@ -109,9 +109,9 @@ class NettyTransportSettings(config: Config) { import config._ val TransportMode: Mode = getString("transport-protocol") match { - case "tcp" ⇒ Tcp - case "udp" ⇒ Udp - case unknown ⇒ throw new ConfigurationException(s"Unknown transport: [$unknown]") + case "tcp" => Tcp + case "udp" => Udp + case unknown => throw new ConfigurationException(s"Unknown transport: [$unknown]") } val EnableSsl: Boolean = getBoolean("enable-ssl") requiring (!_ || TransportMode == Tcp, s"$TransportMode does not support SSL") @@ -119,14 +119,14 @@ class NettyTransportSettings(config: Config) { val SSLEngineProviderClassName: String = if (EnableSsl) getString("ssl-engine-provider") else "" val UseDispatcherForIo: Option[String] = getString("use-dispatcher-for-io") match { - case "" | null ⇒ None - case dispatcher ⇒ Some(dispatcher) + case "" | null => None + case dispatcher => Some(dispatcher) } private[this] def optionSize(s: String): Option[Int] = getBytes(s).toInt match { - case 0 ⇒ None - case x if x < 0 ⇒ throw new ConfigurationException(s"Setting '$s' must be 0 or positive (and fit in an Int)") - case other ⇒ Some(other) + case 0 => None + case x if x < 0 => throw new ConfigurationException(s"Setting '$s' must be 0 or positive (and fit in an Int)") + case other => Some(other) } val ConnectionTimeout: FiniteDuration = config.getMillisDuration("connection-timeout") @@ -137,7 +137,7 @@ class NettyTransportSettings(config: Config) { val SendBufferSize: Option[Int] = optionSize("send-buffer-size") - val ReceiveBufferSize: Option[Int] = optionSize("receive-buffer-size") requiring (s ⇒ + val ReceiveBufferSize: Option[Int] = optionSize("receive-buffer-size") requiring (s => s.isDefined || TransportMode != Udp, "receive-buffer-size must be specified for UDP") val MaxFrameSize: Int = getBytes("maximum-frame-size").toInt requiring ( @@ -151,18 +151,18 @@ class NettyTransportSettings(config: Config) { val TcpKeepalive: Boolean = getBoolean("tcp-keepalive") val TcpReuseAddr: Boolean = getString("tcp-reuse-addr") match { - case "off-for-windows" ⇒ !Helpers.isWindows - case _ ⇒ getBoolean("tcp-reuse-addr") + case "off-for-windows" => !Helpers.isWindows + case _ => getBoolean("tcp-reuse-addr") } val Hostname: String = getString("hostname") match { - case "" ⇒ InetAddress.getLocalHost.getHostAddress - case value ⇒ value + case "" => InetAddress.getLocalHost.getHostAddress + case value => value } val BindHostname: String = getString("bind-hostname") match { - case "" ⇒ Hostname - case value ⇒ value + case "" => Hostname + case value => value } @deprecated("WARNING: This should only be used by professionals.", "2.0") @@ -170,8 +170,8 @@ class NettyTransportSettings(config: Config) { @deprecated("WARNING: This should only be used by professionals.", "2.4") val BindPortSelector: Int = getString("bind-port") match { - case "" ⇒ PortSelector - case value ⇒ value.toInt + case "" => PortSelector + case value => value.toInt } val SslSettings: Option[SSLSettings] = if (EnableSsl) Some(new SSLSettings(config.getConfig("security"))) else None @@ -200,7 +200,7 @@ class NettyTransportSettings(config: Config) { if (segments.length < 3 || segments(0).toInt != 3 || segments(1).toInt != 10 || segments(2).toInt < 6) throwInvalidNettyVersion() } catch { - case _: NumberFormatException ⇒ + case _: NumberFormatException => throwInvalidNettyVersion() } } @@ -224,19 +224,19 @@ private[netty] trait CommonHandlers extends NettyHelpers { remoteSocketAddress: InetSocketAddress): Unit final protected def init(channel: Channel, remoteSocketAddress: SocketAddress, remoteAddress: Address, msg: ChannelBuffer)( - op: (AssociationHandle ⇒ Any)): Unit = { + op: (AssociationHandle => Any)): Unit = { import transport._ NettyTransport.addressFromSocketAddress(channel.getLocalAddress, schemeIdentifier, system.name, Some(settings.Hostname), None) match { - case Some(localAddress) ⇒ + case Some(localAddress) => val handle = createHandle(channel, localAddress, remoteAddress) handle.readHandlerPromise.future.foreach { - listener ⇒ + listener => registerListener(channel, listener, msg, remoteSocketAddress.asInstanceOf[InetSocketAddress]) channel.setReadable(true) } op(handle) - case _ ⇒ NettyTransport.gracefulClose(channel) + case _ => NettyTransport.gracefulClose(channel) } } } @@ -254,7 +254,7 @@ private[netty] abstract class ServerHandler( final protected def initInbound(channel: Channel, remoteSocketAddress: SocketAddress, msg: ChannelBuffer): Unit = { channel.setReadable(false) associationListenerFuture.foreach { - listener ⇒ + listener => val remoteAddress = NettyTransport.addressFromSocketAddress(remoteSocketAddress, transport.schemeIdentifier, transport.system.name, hostName = None, port = None).getOrElse( throw new NettyTransportException(s"Unknown inbound remote address type [${remoteSocketAddress.getClass.getName}]")) @@ -285,10 +285,10 @@ private[transport] object NettyTransport { // 4 bytes will be used to represent the frame length. Used by netty LengthFieldPrepender downstream handler. val FrameLengthFieldLength = 4 def gracefulClose(channel: Channel)(implicit ec: ExecutionContext): Unit = { - def always(c: ChannelFuture) = NettyFutureBridge(c) recover { case _ ⇒ c.getChannel } + def always(c: ChannelFuture) = NettyFutureBridge(c) recover { case _ => c.getChannel } for { - _ ← always { channel.write(ChannelBuffers.buffer(0)) } // Force flush by waiting on a final dummy write - _ ← always { channel.disconnect() } + _ <- always { channel.write(ChannelBuffers.buffer(0)) } // Force flush by waiting on a final dummy write + _ <- always { channel.disconnect() } } channel.close() } @@ -296,9 +296,9 @@ private[transport] object NettyTransport { def addressFromSocketAddress(addr: SocketAddress, schemeIdentifier: String, systemName: String, hostName: Option[String], port: Option[Int]): Option[Address] = addr match { - case sa: InetSocketAddress ⇒ Some(Address(schemeIdentifier, systemName, + case sa: InetSocketAddress => Some(Address(schemeIdentifier, systemName, hostName.getOrElse(sa.getHostString), port.getOrElse(sa.getPort))) - case _ ⇒ None + case _ => None } // Need to do like this for binary compatibility reasons @@ -317,8 +317,8 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA implicit val executionContext: ExecutionContext = settings.UseDispatcherForIo.orElse(RARP(system).provider.remoteSettings.Dispatcher match { - case "" ⇒ None - case dispatcherName ⇒ Some(dispatcherName) + case "" => None + case dispatcherName => Some(dispatcherName) }).map(system.dispatchers.lookup).getOrElse(system.dispatcher) override val schemeIdentifier: String = (if (EnableSsl) "ssl." else "") + TransportMode @@ -350,23 +350,23 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA uniqueIdCounter.getAndIncrement) private val clientChannelFactory: ChannelFactory = TransportMode match { - case Tcp ⇒ + case Tcp => val boss, worker = createExecutorService() // We need to create a HashedWheelTimer here since Netty creates one with a thread that // doesn't respect the akka.daemonic setting new NioClientSocketChannelFactory(boss, 1, new NioWorkerPool(worker, ClientSocketWorkerPoolSize), new HashedWheelTimer(system.threadFactory)) - case Udp ⇒ + case Udp => // This does not create a HashedWheelTimer internally new NioDatagramChannelFactory(createExecutorService(), ClientSocketWorkerPoolSize) } private val serverChannelFactory: ChannelFactory = TransportMode match { - case Tcp ⇒ + case Tcp => val boss, worker = createExecutorService() // This does not create a HashedWheelTimer internally new NioServerSocketChannelFactory(boss, worker, ServerSocketWorkerPoolSize) - case Udp ⇒ + case Udp => // This does not create a HashedWheelTimer internally new NioDatagramChannelFactory(createExecutorService(), ServerSocketWorkerPoolSize) } @@ -395,18 +395,18 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA OptionVal.Some(system.dynamicAccess.createInstanceFor[SSLEngineProvider]( settings.SSLEngineProviderClassName, List((classOf[ActorSystem], system))).recover { - case e ⇒ throw new ConfigurationException( + case e => throw new ConfigurationException( s"Could not create SSLEngineProvider [${settings.SSLEngineProviderClassName}]", e) }.get) } else OptionVal.None private def sslHandler(isClient: Boolean): SslHandler = { sslEngineProvider match { - case OptionVal.Some(sslProvider) ⇒ + case OptionVal.Some(sslProvider) => val handler = NettySSLSupport(sslProvider, isClient) handler.setCloseOnSSLException(true) handler - case OptionVal.None ⇒ + case OptionVal.None => throw new IllegalStateException("Expected enable-ssl=on") } @@ -442,16 +442,16 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA bootstrap.setOption("child.keepAlive", settings.TcpKeepalive) bootstrap.setOption("reuseAddress", settings.TcpReuseAddr) if (isDatagram) bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(ReceiveBufferSize.get)) - settings.ReceiveBufferSize.foreach(sz ⇒ bootstrap.setOption("receiveBufferSize", sz)) - settings.SendBufferSize.foreach(sz ⇒ bootstrap.setOption("sendBufferSize", sz)) - settings.WriteBufferHighWaterMark.foreach(sz ⇒ bootstrap.setOption("writeBufferHighWaterMark", sz)) - settings.WriteBufferLowWaterMark.foreach(sz ⇒ bootstrap.setOption("writeBufferLowWaterMark", sz)) + settings.ReceiveBufferSize.foreach(sz => bootstrap.setOption("receiveBufferSize", sz)) + settings.SendBufferSize.foreach(sz => bootstrap.setOption("sendBufferSize", sz)) + settings.WriteBufferHighWaterMark.foreach(sz => bootstrap.setOption("writeBufferHighWaterMark", sz)) + settings.WriteBufferLowWaterMark.foreach(sz => bootstrap.setOption("writeBufferLowWaterMark", sz)) bootstrap } private val inboundBootstrap: Bootstrap = settings.TransportMode match { - case Tcp ⇒ setupBootstrap(new ServerBootstrap(serverChannelFactory), serverPipelineFactory) - case Udp ⇒ setupBootstrap(new ConnectionlessBootstrap(serverChannelFactory), serverPipelineFactory) + case Tcp => setupBootstrap(new ServerBootstrap(serverChannelFactory), serverPipelineFactory) + case Udp => setupBootstrap(new ConnectionlessBootstrap(serverChannelFactory), serverPipelineFactory) } private def outboundBootstrap(remoteAddress: Address): ClientBootstrap = { @@ -459,10 +459,10 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA bootstrap.setOption("connectTimeoutMillis", settings.ConnectionTimeout.toMillis) bootstrap.setOption("tcpNoDelay", settings.TcpNodelay) bootstrap.setOption("keepAlive", settings.TcpKeepalive) - settings.ReceiveBufferSize.foreach(sz ⇒ bootstrap.setOption("receiveBufferSize", sz)) - settings.SendBufferSize.foreach(sz ⇒ bootstrap.setOption("sendBufferSize", sz)) - settings.WriteBufferHighWaterMark.foreach(sz ⇒ bootstrap.setOption("writeBufferHighWaterMark", sz)) - settings.WriteBufferLowWaterMark.foreach(sz ⇒ bootstrap.setOption("writeBufferLowWaterMark", sz)) + settings.ReceiveBufferSize.foreach(sz => bootstrap.setOption("receiveBufferSize", sz)) + settings.SendBufferSize.foreach(sz => bootstrap.setOption("sendBufferSize", sz)) + settings.WriteBufferHighWaterMark.foreach(sz => bootstrap.setOption("writeBufferHighWaterMark", sz)) + settings.WriteBufferLowWaterMark.foreach(sz => bootstrap.setOption("writeBufferLowWaterMark", sz)) bootstrap } @@ -470,18 +470,18 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA // TODO: This should be factored out to an async (or thread-isolated) name lookup service #2960 def addressToSocketAddress(addr: Address): Future[InetSocketAddress] = addr match { - case Address(_, _, Some(host), Some(port)) ⇒ Future { blocking { new InetSocketAddress(InetAddress.getByName(host), port) } } - case _ ⇒ Future.failed(new IllegalArgumentException(s"Address [$addr] does not contain host or port information.")) + case Address(_, _, Some(host), Some(port)) => Future { blocking { new InetSocketAddress(InetAddress.getByName(host), port) } } + case _ => Future.failed(new IllegalArgumentException(s"Address [$addr] does not contain host or port information.")) } override def listen: Future[(Address, Promise[AssociationEventListener])] = { for { - address ← addressToSocketAddress(Address("", "", settings.BindHostname, settings.BindPortSelector)) + address <- addressToSocketAddress(Address("", "", settings.BindHostname, settings.BindPortSelector)) } yield { try { val newServerChannel = inboundBootstrap match { - case b: ServerBootstrap ⇒ b.bind(address) - case b: ConnectionlessBootstrap ⇒ b.bind(address) + case b: ServerBootstrap => b.bind(address) + case b: ConnectionlessBootstrap => b.bind(address) } // Block reads until a handler actor is registered @@ -492,20 +492,20 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA addressFromSocketAddress(newServerChannel.getLocalAddress, schemeIdentifier, system.name, Some(settings.Hostname), if (settings.PortSelector == 0) None else Some(settings.PortSelector)) match { - case Some(address) ⇒ + case Some(address) => addressFromSocketAddress(newServerChannel.getLocalAddress, schemeIdentifier, system.name, None, None) match { - case Some(address) ⇒ boundTo = address - case None ⇒ throw new NettyTransportException(s"Unknown local address type [${newServerChannel.getLocalAddress.getClass.getName}]") + case Some(address) => boundTo = address + case None => throw new NettyTransportException(s"Unknown local address type [${newServerChannel.getLocalAddress.getClass.getName}]") } localAddress = address - associationListenerPromise.future.foreach { _ ⇒ newServerChannel.setReadable(true) } + associationListenerPromise.future.foreach { _ => newServerChannel.setReadable(true) } (address, associationListenerPromise) - case None ⇒ throw new NettyTransportException(s"Unknown local address type [${newServerChannel.getLocalAddress.getClass.getName}]") + case None => throw new NettyTransportException(s"Unknown local address type [${newServerChannel.getLocalAddress.getClass.getName}]") } } catch { - case NonFatal(e) ⇒ { + case NonFatal(e) => { log.error("failed to bind to {}, shutting down Netty transport", address) - try { shutdown() } catch { case NonFatal(_) ⇒ } // ignore possible exception during shutdown + try { shutdown() } catch { case NonFatal(_) => } // ignore possible exception during shutdown throw e } } @@ -521,9 +521,9 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA val bootstrap: ClientBootstrap = outboundBootstrap(remoteAddress) (for { - socketAddress ← addressToSocketAddress(remoteAddress) - readyChannel ← NettyFutureBridge(bootstrap.connect(socketAddress)) map { - channel ⇒ + socketAddress <- addressToSocketAddress(remoteAddress) + readyChannel <- NettyFutureBridge(bootstrap.connect(socketAddress)) map { + channel => if (EnableSsl) blocking { channel.getPipeline.get(classOf[SslHandler]).handshake().awaitUninterruptibly() @@ -531,23 +531,23 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA if (!isDatagram) channel.setReadable(false) channel } - handle ← if (isDatagram) + handle <- if (isDatagram) Future { readyChannel.getRemoteAddress match { - case address: InetSocketAddress ⇒ + case address: InetSocketAddress => val handle = new UdpAssociationHandle(localAddress, remoteAddress, readyChannel, NettyTransport.this) handle.readHandlerPromise.future.foreach { - listener ⇒ udpConnectionTable.put(address, listener) + listener => udpConnectionTable.put(address, listener) } handle - case unknown ⇒ throw new NettyTransportException(s"Unknown outbound remote address type [${unknown.getClass.getName}]") + case unknown => throw new NettyTransportException(s"Unknown outbound remote address type [${unknown.getClass.getName}]") } } else readyChannel.getPipeline.get(classOf[ClientHandler]).statusFuture } yield handle) recover { - case _: CancellationException ⇒ throw new NettyTransportExceptionNoStack("Connection was cancelled") - case NonFatal(t) ⇒ + case _: CancellationException => throw new NettyTransportExceptionNoStack("Connection was cancelled") + case NonFatal(t) => val msg = if (t.getCause == null) t.getMessage @@ -561,13 +561,13 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA } override def shutdown(): Future[Boolean] = { - def always(c: ChannelGroupFuture) = NettyFutureBridge(c).map(_ ⇒ true) recover { case _ ⇒ false } + def always(c: ChannelGroupFuture) = NettyFutureBridge(c).map(_ => true) recover { case _ => false } for { // Force flush by trying to write an empty buffer and wait for success - unbindStatus ← always(channelGroup.unbind()) - lastWriteStatus ← always(channelGroup.write(ChannelBuffers.buffer(0))) - disconnectStatus ← always(channelGroup.disconnect()) - closeStatus ← always(channelGroup.close()) + unbindStatus <- always(channelGroup.unbind()) + lastWriteStatus <- always(channelGroup.write(ChannelBuffers.buffer(0))) + disconnectStatus <- always(channelGroup.disconnect()) + closeStatus <- always(channelGroup.close()) } yield { // Release the selectors, but don't try to kill the dispatcher if (UseDispatcherForIo.isDefined) { diff --git a/akka-remote/src/main/scala/akka/remote/transport/netty/SSLEngineProvider.scala b/akka-remote/src/main/scala/akka/remote/transport/netty/SSLEngineProvider.scala index 8fb80cdd6b..d68de8b26a 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/netty/SSLEngineProvider.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/netty/SSLEngineProvider.scala @@ -59,9 +59,9 @@ import javax.net.ssl.TrustManagerFactory ctx.init(keyManagers, trustManagers, rng) ctx } catch { - case e: FileNotFoundException ⇒ throw new RemoteTransportException("Server SSL connection could not be established because key store could not be loaded", e) - case e: IOException ⇒ throw new RemoteTransportException("Server SSL connection could not be established because: " + e.getMessage, e) - case e: GeneralSecurityException ⇒ throw new RemoteTransportException("Server SSL connection could not be established because SSL context could not be constructed", e) + case e: FileNotFoundException => throw new RemoteTransportException("Server SSL connection could not be established because key store could not be loaded", e) + case e: IOException => throw new RemoteTransportException("Server SSL connection could not be established because: " + e.getMessage, e) + case e: GeneralSecurityException => throw new RemoteTransportException("Server SSL connection could not be established because SSL context could not be constructed", e) } } diff --git a/akka-remote/src/main/scala/akka/remote/transport/netty/UdpSupport.scala b/akka-remote/src/main/scala/akka/remote/transport/netty/UdpSupport.scala index ff02a37d19..aef73390c1 100644 --- a/akka-remote/src/main/scala/akka/remote/transport/netty/UdpSupport.scala +++ b/akka-remote/src/main/scala/akka/remote/transport/netty/UdpSupport.scala @@ -29,15 +29,15 @@ private[remote] trait UdpHandlers extends CommonHandlers { msg: ChannelBuffer, remoteSocketAddress: InetSocketAddress): Unit = { transport.udpConnectionTable.putIfAbsent(remoteSocketAddress, listener) match { - case null ⇒ listener notify InboundPayload(ByteString(msg.array())) - case oldReader ⇒ + case null => listener notify InboundPayload(ByteString(msg.array())) + case oldReader => throw new NettyTransportException( s"Listener $listener attempted to register for remote address $remoteSocketAddress but $oldReader was already registered.") } } override def onMessage(ctx: ChannelHandlerContext, e: MessageEvent): Unit = e.getRemoteAddress match { - case inetSocketAddress: InetSocketAddress ⇒ + case inetSocketAddress: InetSocketAddress => if (!transport.udpConnectionTable.containsKey(inetSocketAddress)) { e.getChannel.setReadable(false) initUdp(e.getChannel, e.getRemoteAddress, e.getMessage.asInstanceOf[ChannelBuffer]) @@ -46,7 +46,7 @@ private[remote] trait UdpHandlers extends CommonHandlers { val bytes: Array[Byte] = e.getMessage.asInstanceOf[ChannelBuffer].array() if (bytes.length > 0) listener notify InboundPayload(ByteString(bytes)) } - case _ ⇒ + case _ => } def initUdp(channel: Channel, remoteSocketAddress: SocketAddress, msg: ChannelBuffer): Unit diff --git a/akka-remote/src/test/scala/akka/remote/AccrualFailureDetectorSpec.scala b/akka-remote/src/test/scala/akka/remote/AccrualFailureDetectorSpec.scala index cf2a3f74e7..850f682284 100644 --- a/akka-remote/src/test/scala/akka/remote/AccrualFailureDetectorSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/AccrualFailureDetectorSpec.scala @@ -14,7 +14,7 @@ class AccrualFailureDetectorSpec extends AkkaSpec("akka.loglevel = INFO") { "An AccrualFailureDetector" must { def fakeTimeGenerator(timeIntervals: Seq[Long]): Clock = new Clock { - @volatile var times = timeIntervals.tail.foldLeft(List[Long](timeIntervals.head))((acc, c) ⇒ acc ::: List[Long](acc.last + c)) + @volatile var times = timeIntervals.tail.foldLeft(List[Long](timeIntervals.head))((acc, c) => acc ::: List[Long](acc.last + c)) override def apply(): Long = { val currentTime = times.head times = times.tail @@ -48,7 +48,7 @@ class AccrualFailureDetectorSpec extends AkkaSpec("akka.loglevel = INFO") { cdf(fd.phi(35L, 0, 10)) should ===(0.99977 +- (0.001)) cdf(fd.phi(40L, 0, 10)) should ===(0.99997 +- (0.0001)) - for (x :: y :: Nil ← (0 to 40).toList.sliding(2)) { + for (x :: y :: Nil <- (0 to 40).toList.sliding(2)) { fd.phi(x, 0, 10) should be < (fd.phi(y, 0, 10)) } @@ -63,8 +63,8 @@ class AccrualFailureDetectorSpec extends AkkaSpec("akka.loglevel = INFO") { "return realistic phi values" in { val fd = createFailureDetector() - val test = TreeMap(0 → 0.0, 500 → 0.1, 1000 → 0.3, 1200 → 1.6, 1400 → 4.7, 1600 → 10.8, 1700 → 15.3) - for ((timeDiff, expectedPhi) ← test) { + val test = TreeMap(0 -> 0.0, 500 -> 0.1, 1000 -> 0.3, 1200 -> 1.6, 1400 -> 4.7, 1600 -> 10.8, 1700 -> 15.3) + for ((timeDiff, expectedPhi) <- test) { fd.phi(timeDiff = timeDiff, mean = 1000.0, stdDeviation = 100.0) should ===(expectedPhi +- (0.1)) } @@ -132,7 +132,7 @@ class AccrualFailureDetectorSpec extends AkkaSpec("akka.loglevel = INFO") { val timeIntervals = regularIntervals :+ (5 * 60 * 1000L) :+ 100L :+ 900L :+ 100L :+ 7000L :+ 100L :+ 900L :+ 100L :+ 900L val fd = createFailureDetector(threshold = 8, acceptableLostDuration = 3.seconds, clock = fakeTimeGenerator(timeIntervals)) - for (_ ← 0 until 1000) fd.heartbeat() + for (_ <- 0 until 1000) fd.heartbeat() fd.isAvailable should ===(false) // after the long pause fd.heartbeat() fd.isAvailable should ===(true) @@ -198,7 +198,7 @@ class AccrualFailureDetectorSpec extends AkkaSpec("akka.loglevel = INFO") { "calculate correct mean and variance" in { val samples = Seq(100, 200, 125, 340, 130) val stats = samples.foldLeft(HeartbeatHistory(maxSampleSize = 20)) { - (stats, value) ⇒ stats :+ value + (stats, value) => stats :+ value } stats.mean should ===(179.0 +- 0.00001) stats.variance should ===(7584.0 +- 0.00001) diff --git a/akka-remote/src/test/scala/akka/remote/AckedDeliverySpec.scala b/akka-remote/src/test/scala/akka/remote/AckedDeliverySpec.scala index e4b3240f69..8e6d751a47 100644 --- a/akka-remote/src/test/scala/akka/remote/AckedDeliverySpec.scala +++ b/akka-remote/src/test/scala/akka/remote/AckedDeliverySpec.scala @@ -272,7 +272,7 @@ class AckedDeliverySpec extends AkkaSpec { "correctly cooperate with each other" in { val MsgCount = 1000 val DeliveryProbability = 0.5 - val referenceList: Seq[Sequenced] = (0 until MsgCount).toSeq map { i ⇒ msg(i.toLong) } + val referenceList: Seq[Sequenced] = (0 until MsgCount).toSeq map { i => msg(i.toLong) } var toSend = referenceList var received = Seq.empty[Sequenced] @@ -292,7 +292,7 @@ class AckedDeliverySpec extends AkkaSpec { tmp } else Seq.empty[Sequenced] - (resends ++ sends) foreach { msg ⇒ + (resends ++ sends) foreach { msg => if (sends.contains(msg)) sndBuf = sndBuf.buffer(msg) if (happened(p)) { val (updatedRcvBuf, delivers, ack) = rcvBuf.receive(msg).extractDeliverable @@ -325,7 +325,7 @@ class AckedDeliverySpec extends AkkaSpec { info("Entering reliable phase") // Finalizing phase - for (_ ← 1 to MsgCount) { + for (_ <- 1 to MsgCount) { senderSteps(1, 1.0) receiverStep(1.0) } diff --git a/akka-remote/src/test/scala/akka/remote/ActorsLeakSpec.scala b/akka-remote/src/test/scala/akka/remote/ActorsLeakSpec.scala index e058ed238a..ad24c2780f 100644 --- a/akka-remote/src/test/scala/akka/remote/ActorsLeakSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/ActorsLeakSpec.scala @@ -35,16 +35,16 @@ object ActorsLeakSpec { def recurse(node: ActorRef): List[ActorRef] = { val children: List[ActorRef] = node match { - case wc: ActorRefWithCell ⇒ + case wc: ActorRefWithCell => val cell = wc.underlying cell.childrenRefs match { - case ChildrenContainer.TerminatingChildrenContainer(_, toDie, reason) ⇒ Nil - case x @ (ChildrenContainer.TerminatedChildrenContainer | ChildrenContainer.EmptyChildrenContainer) ⇒ Nil - case n: ChildrenContainer.NormalChildrenContainer ⇒ cell.childrenRefs.children.toList - case x ⇒ Nil + case ChildrenContainer.TerminatingChildrenContainer(_, toDie, reason) => Nil + case x @ (ChildrenContainer.TerminatedChildrenContainer | ChildrenContainer.EmptyChildrenContainer) => Nil + case n: ChildrenContainer.NormalChildrenContainer => cell.childrenRefs.children.toList + case x => Nil } - case _ ⇒ Nil + case _ => Nil } node :: children.flatMap(recurse) @@ -55,7 +55,7 @@ object ActorsLeakSpec { class StoppableActor extends Actor { override def receive = { - case "stop" ⇒ context.stop(self) + case "stop" => context.stop(self) } } @@ -70,7 +70,7 @@ class ActorsLeakSpec extends AkkaSpec(ActorsLeakSpec.config) with ImplicitSender val ref = system.actorOf(Props[EchoActor], "echo") val echoPath = RootActorPath(RARP(system).provider.getDefaultAddress) / "user" / "echo" - val targets = List("/system/endpointManager", "/system/transports").map { path ⇒ + val targets = List("/system/endpointManager", "/system/transports").map { path => system.actorSelection(path) ! Identify(0) expectMsgType[ActorIdentity].getRef } @@ -78,7 +78,7 @@ class ActorsLeakSpec extends AkkaSpec(ActorsLeakSpec.config) with ImplicitSender val initialActors = targets.flatMap(collectLiveActors).toSet //Clean shutdown case - for (_ ← 1 to 3) { + for (_ <- 1 to 3) { val remoteSystem = ActorSystem( "remote", @@ -99,7 +99,7 @@ class ActorsLeakSpec extends AkkaSpec(ActorsLeakSpec.config) with ImplicitSender } // Quarantine an old incarnation case - for (_ ← 1 to 3) { + for (_ <- 1 to 3) { //always use the same address val remoteSystem = ActorSystem( "remote", @@ -138,7 +138,7 @@ class ActorsLeakSpec extends AkkaSpec(ActorsLeakSpec.config) with ImplicitSender } // Missing SHUTDOWN case - for (_ ← 1 to 3) { + for (_ <- 1 to 3) { val remoteSystem = ActorSystem( "remote", diff --git a/akka-remote/src/test/scala/akka/remote/DaemonicSpec.scala b/akka-remote/src/test/scala/akka/remote/DaemonicSpec.scala index 9daedbb4b1..af18bcdbb6 100644 --- a/akka-remote/src/test/scala/akka/remote/DaemonicSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/DaemonicSpec.scala @@ -37,7 +37,7 @@ class DaemonicSpec extends AkkaSpec { // get new non daemonic threads running awaitAssert({ val newNonDaemons: Set[Thread] = Thread.getAllStackTraces.keySet().asScala.seq. - filter(t ⇒ !origThreads(t) && !t.isDaemon).to(Set) + filter(t => !origThreads(t) && !t.isDaemon).to(Set) newNonDaemons should ===(Set.empty[Thread]) }, 4.seconds) diff --git a/akka-remote/src/test/scala/akka/remote/DeadlineFailureDetectorSpec.scala b/akka-remote/src/test/scala/akka/remote/DeadlineFailureDetectorSpec.scala index bd78e832ce..838708c666 100644 --- a/akka-remote/src/test/scala/akka/remote/DeadlineFailureDetectorSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/DeadlineFailureDetectorSpec.scala @@ -13,7 +13,7 @@ class DeadlineFailureDetectorSpec extends AkkaSpec { "A DeadlineFailureDetector" must { def fakeTimeGenerator(timeIntervals: Seq[Long]): Clock = new Clock { - @volatile var times = timeIntervals.tail.foldLeft(List[Long](timeIntervals.head))((acc, c) ⇒ acc ::: List[Long](acc.last + c)) + @volatile var times = timeIntervals.tail.foldLeft(List[Long](timeIntervals.head))((acc, c) => acc ::: List[Long](acc.last + c)) override def apply(): Long = { val currentTime = times.head times = times.tail @@ -57,7 +57,7 @@ class DeadlineFailureDetectorSpec extends AkkaSpec { val timeIntervals = regularIntervals :+ (5 * 60 * 1000L) :+ 100L :+ 900L :+ 100L :+ 7000L :+ 100L :+ 900L :+ 100L :+ 900L val fd = createFailureDetector(acceptableLostDuration = 4.seconds, clock = fakeTimeGenerator(timeIntervals)) - for (_ ← 0 until 1000) fd.heartbeat() + for (_ <- 0 until 1000) fd.heartbeat() fd.isAvailable should ===(false) // after the long pause fd.heartbeat() fd.isAvailable should ===(true) diff --git a/akka-remote/src/test/scala/akka/remote/FailureDetectorRegistrySpec.scala b/akka-remote/src/test/scala/akka/remote/FailureDetectorRegistrySpec.scala index db157d7b88..e80656d702 100644 --- a/akka-remote/src/test/scala/akka/remote/FailureDetectorRegistrySpec.scala +++ b/akka-remote/src/test/scala/akka/remote/FailureDetectorRegistrySpec.scala @@ -11,7 +11,7 @@ import akka.testkit.AkkaSpec class FailureDetectorRegistrySpec extends AkkaSpec("akka.loglevel = INFO") { def fakeTimeGenerator(timeIntervals: Seq[Long]): Clock = new Clock { - @volatile var times = timeIntervals.tail.foldLeft(List[Long](timeIntervals.head))((acc, c) ⇒ acc ::: List[Long](acc.last + c)) + @volatile var times = timeIntervals.tail.foldLeft(List[Long](timeIntervals.head))((acc, c) => acc ::: List[Long](acc.last + c)) override def apply(): Long = { val currentTime = times.head times = times.tail @@ -40,7 +40,7 @@ class FailureDetectorRegistrySpec extends AkkaSpec("akka.loglevel = INFO") { acceptableLostDuration: FiniteDuration = Duration.Zero, firstHeartbeatEstimate: FiniteDuration = 1.second, clock: Clock = FailureDetector.defaultClock): FailureDetectorRegistry[String] = { - new DefaultFailureDetectorRegistry[String](() ⇒ createFailureDetector( + new DefaultFailureDetectorRegistry[String](() => createFailureDetector( threshold, maxSampleSize, minStdDeviation, diff --git a/akka-remote/src/test/scala/akka/remote/LogSourceSpec.scala b/akka-remote/src/test/scala/akka/remote/LogSourceSpec.scala index 272f2ff62b..ea18a491ef 100644 --- a/akka-remote/src/test/scala/akka/remote/LogSourceSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/LogSourceSpec.scala @@ -17,7 +17,7 @@ import akka.actor.ExtendedActorSystem object LogSourceSpec { class Reporter extends Actor with ActorLogging { def receive = { - case s: String ⇒ + case s: String => log.info(s) } } @@ -36,8 +36,8 @@ class LogSourceSpec extends AkkaSpec( val logProbe = TestProbe() system.eventStream.subscribe(system.actorOf(Props(new Actor { def receive = { - case i @ Info(_, _, msg: String) if msg contains "hello" ⇒ logProbe.ref ! i - case _ ⇒ + case i @ Info(_, _, msg: String) if msg contains "hello" => logProbe.ref ! i + case _ => } }).withDeploy(Deploy.local), "logSniffer"), classOf[Logging.Info]) diff --git a/akka-remote/src/test/scala/akka/remote/MessageLoggingSpec.scala b/akka-remote/src/test/scala/akka/remote/MessageLoggingSpec.scala index ad2a526207..28e7bbd2a9 100644 --- a/akka-remote/src/test/scala/akka/remote/MessageLoggingSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/MessageLoggingSpec.scala @@ -41,7 +41,7 @@ object MessageLoggingSpec { class BadActor extends Actor { override def receive = { - case _ ⇒ + case _ => sender() ! BadMsg("hah") } } diff --git a/akka-remote/src/test/scala/akka/remote/NetworkFailureSpec.scala b/akka-remote/src/test/scala/akka/remote/NetworkFailureSpec.scala index 6c94c14ba9..0783955529 100644 --- a/akka-remote/src/test/scala/akka/remote/NetworkFailureSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/NetworkFailureSpec.scala @@ -10,7 +10,7 @@ import akka.testkit.DefaultTimeout import java.util.concurrent.atomic.AtomicBoolean import scala.concurrent.{ Future } -trait NetworkFailureSpec extends DefaultTimeout { self: AkkaSpec ⇒ +trait NetworkFailureSpec extends DefaultTimeout { self: AkkaSpec => import scala.concurrent.duration.Duration import system.dispatcher @@ -27,7 +27,7 @@ trait NetworkFailureSpec extends DefaultTimeout { self: AkkaSpec ⇒ Thread.sleep(duration.toMillis) restoreIP } catch { - case e: Throwable ⇒ + case e: Throwable => dead.set(true) e.printStackTrace } @@ -42,7 +42,7 @@ trait NetworkFailureSpec extends DefaultTimeout { self: AkkaSpec ⇒ Thread.sleep(duration.toMillis) restoreIP } catch { - case e: Throwable ⇒ + case e: Throwable => dead.set(true) e.printStackTrace } @@ -57,7 +57,7 @@ trait NetworkFailureSpec extends DefaultTimeout { self: AkkaSpec ⇒ Thread.sleep(duration.toMillis) restoreIP } catch { - case e: Throwable ⇒ + case e: Throwable => dead.set(true) e.printStackTrace } diff --git a/akka-remote/src/test/scala/akka/remote/RemoteConfigSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteConfigSpec.scala index dfbe212555..40064d9cd2 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteConfigSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteConfigSpec.scala @@ -47,8 +47,8 @@ class RemoteConfigSpec extends AkkaSpec( Transports.head._1 should ===(classOf[akka.remote.transport.netty.NettyTransport].getName) Transports.head._2 should ===(Nil) Adapters should ===(Map( - "gremlin" → classOf[akka.remote.transport.FailureInjectorProvider].getName, - "trttl" → classOf[akka.remote.transport.ThrottlerProvider].getName)) + "gremlin" -> classOf[akka.remote.transport.FailureInjectorProvider].getName, + "trttl" -> classOf[akka.remote.transport.ThrottlerProvider].getName)) WatchFailureDetectorImplementationClass should ===(classOf[PhiAccrualFailureDetector].getName) WatchHeartBeatInterval should ===(1 seconds) diff --git a/akka-remote/src/test/scala/akka/remote/RemoteConsistentHashingRouterSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteConsistentHashingRouterSpec.scala index 62b0d6ad44..f20fcdca69 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteConsistentHashingRouterSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteConsistentHashingRouterSpec.scala @@ -27,8 +27,8 @@ class RemoteConsistentHashingRouterSpec extends AkkaSpec(""" val consistentHash1 = ConsistentHash(nodes1, 10) val consistentHash2 = ConsistentHash(nodes2, 10) val keys = List("A", "B", "C", "D", "E", "F", "G") - val result1 = keys collect { case k ⇒ consistentHash1.nodeFor(k).routee } - val result2 = keys collect { case k ⇒ consistentHash2.nodeFor(k).routee } + val result1 = keys collect { case k => consistentHash1.nodeFor(k).routee } + val result2 = keys collect { case k => consistentHash2.nodeFor(k).routee } result1 should ===(result2) } diff --git a/akka-remote/src/test/scala/akka/remote/RemoteDeathWatchSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteDeathWatchSpec.scala index 03e0b95d8b..ab3559300f 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteDeathWatchSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteDeathWatchSpec.scala @@ -58,7 +58,7 @@ akka { system.actorOf(Props(new Actor { context.watch(ref) def receive = { - case Terminated(r) ⇒ testActor ! r + case Terminated(r) => testActor ! r } }).withDeploy(Deploy.local)) @@ -76,7 +76,7 @@ akka { system.actorOf(Props(new Actor { context.watch(context.actorFor(path)) def receive = { - case t: Terminated ⇒ testActor ! t.actor.path + case t: Terminated => testActor ! t.actor.path } }).withDeploy(Deploy.local), name = "observer2") diff --git a/akka-remote/src/test/scala/akka/remote/RemoteDeployerSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteDeployerSpec.scala index 24ef693cdb..c7a3462d63 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteDeployerSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteDeployerSpec.scala @@ -25,7 +25,7 @@ object RemoteDeployerSpec { """, ConfigParseOptions.defaults) class RecipeActor extends Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } } } diff --git a/akka-remote/src/test/scala/akka/remote/RemoteDeploymentWhitelistSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteDeploymentWhitelistSpec.scala index 650cdb0d5a..1f0dcfcc1d 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteDeploymentWhitelistSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteDeploymentWhitelistSpec.scala @@ -17,8 +17,8 @@ object RemoteDeploymentWhitelistSpec { var target: ActorRef = context.system.deadLetters def receive = { - case ex: Exception ⇒ throw ex - case x ⇒ target = sender(); sender() ! x + case ex: Exception => throw ex + case x => target = sender(); sender() ! x } override def preStart(): Unit = {} @@ -35,8 +35,8 @@ object RemoteDeploymentWhitelistSpec { var target: ActorRef = context.system.deadLetters def receive = { - case ex: Exception ⇒ throw ex - case x ⇒ target = sender(); sender() ! x + case ex: Exception => throw ex + case x => target = sender(); sender() ! x } override def preStart(): Unit = {} diff --git a/akka-remote/src/test/scala/akka/remote/RemoteInitErrorSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteInitErrorSpec.scala index fbcc303d78..3a1cd31854 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteInitErrorSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteInitErrorSpec.scala @@ -39,7 +39,7 @@ class RemoteInitErrorSpec extends WordSpec with Matchers { def currentThreadIds(): Set[Long] = { val threads = Thread.getAllStackTraces().keySet() - threads.asScala.collect({ case t: Thread if (!t.isDaemon()) ⇒ t.getId() }) + threads.asScala.collect({ case t: Thread if (!t.isDaemon()) => t.getId() }) } "Remoting" must { @@ -49,7 +49,7 @@ class RemoteInitErrorSpec extends WordSpec with Matchers { ActorSystem("duplicate", ConfigFactory.parseString("akka.loglevel=OFF").withFallback(conf)) fail("initialization should fail due to invalid IP address") } catch { - case NonFatal(e) ⇒ { + case NonFatal(e) => { eventually(timeout(30 seconds), interval(800 milliseconds)) { val current = currentThreadIds() // no new threads should remain compared to the start state diff --git a/akka-remote/src/test/scala/akka/remote/RemoteRouterSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteRouterSpec.scala index 61fa9a9f5a..64c0055fac 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteRouterSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteRouterSpec.scala @@ -15,7 +15,7 @@ import akka.testkit.TestActors.echoActorProps object RemoteRouterSpec { class Parent extends Actor { def receive = { - case (p: Props, name: String) ⇒ + case (p: Props, name: String) => sender() ! context.actorOf(p, name) } } @@ -94,7 +94,7 @@ class RemoteRouterSpec extends AkkaSpec(s""" } def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = { - for (i ← 1 to n) yield { + for (i <- 1 to n) yield { val msg = i.toString router.tell(msg, probe.ref) probe.expectMsg(msg) @@ -216,7 +216,7 @@ class RemoteRouterSpec extends AkkaSpec(s""" "set supplied supervisorStrategy" in { val probe = TestProbe()(masterSystem) val escalator = OneForOneStrategy() { - case e ⇒ probe.ref ! e; SupervisorStrategy.Escalate + case e => probe.ref ! e; SupervisorStrategy.Escalate } val router = masterSystem.actorOf(new RemoteRouterConfig( RoundRobinPool(1, supervisorStrategy = escalator), diff --git a/akka-remote/src/test/scala/akka/remote/RemoteWatcherSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteWatcherSpec.scala index 3e7d3f050a..a6bc82b8b9 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteWatcherSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteWatcherSpec.scala @@ -13,7 +13,7 @@ object RemoteWatcherSpec { class TestActorProxy(testActor: ActorRef) extends Actor { def receive = { - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } @@ -33,7 +33,7 @@ object RemoteWatcherSpec { acceptableHeartbeatPause = 3.seconds, firstHeartbeatEstimate = 1.second) - new DefaultFailureDetectorRegistry(() ⇒ createFailureDetector()) + new DefaultFailureDetectorRegistry(() => createFailureDetector()) } object TestRemoteWatcher { diff --git a/akka-remote/src/test/scala/akka/remote/RemotingSpec.scala b/akka-remote/src/test/scala/akka/remote/RemotingSpec.scala index e1504fb291..95e96743d0 100644 --- a/akka-remote/src/test/scala/akka/remote/RemotingSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemotingSpec.scala @@ -31,11 +31,11 @@ object RemotingSpec { var target: ActorRef = context.system.deadLetters def receive = { - case (p: Props, n: String) ⇒ sender() ! context.actorOf(Props[Echo1], n) - case ex: Exception ⇒ throw ex - case ActorForReq(s) ⇒ sender() ! context.actorFor(s) - case ActorSelReq(s) ⇒ sender() ! context.actorSelection(s) - case x ⇒ target = sender(); sender() ! x + case (p: Props, n: String) => sender() ! context.actorOf(Props[Echo1], n) + case ex: Exception => throw ex + case ActorForReq(s) => sender() ! context.actorFor(s) + case ActorSelReq(s) => sender() ! context.actorSelection(s) + case x => target = sender(); sender() ! x } override def preStart(): Unit = {} @@ -50,17 +50,17 @@ object RemotingSpec { class Echo2 extends Actor { def receive = { - case "ping" ⇒ sender() ! (("pong", sender())) - case a: ActorRef ⇒ a ! (("ping", sender())) - case ("ping", a: ActorRef) ⇒ sender() ! (("pong", a)) - case ("pong", a: ActorRef) ⇒ a ! (("pong", sender().path.toSerializationFormat)) + case "ping" => sender() ! (("pong", sender())) + case a: ActorRef => a ! (("ping", sender())) + case ("ping", a: ActorRef) => sender() ! (("pong", a)) + case ("pong", a: ActorRef) => a ! (("pong", sender().path.toSerializationFormat)) } } class Proxy(val one: ActorRef, val another: ActorRef) extends Actor { def receive = { - case s if sender().path == one.path ⇒ another ! s - case s if sender().path == another.path ⇒ one ! s + case s if sender().path == one.path => another ! s + case s if sender().path == another.path => one ! s } } @@ -142,10 +142,10 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D val remoteSystem = ActorSystem("remote-sys", conf) for ( - (name, proto) ← Seq( - "/gonk" → "tcp", - "/zagzag" → "udp", - "/roghtaar" → "ssl.tcp") + (name, proto) <- Seq( + "/gonk" -> "tcp", + "/zagzag" -> "udp", + "/roghtaar" -> "ssl.tcp") ) deploy(system, Deploy(name, scope = RemoteScope(getOtherAddress(remoteSystem, proto)))) def getOtherAddress(sys: ActorSystem, proto: String) = @@ -159,19 +159,19 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D val here = system.actorFor("akka.test://remote-sys@localhost:12346/user/echo") - private def verifySend(msg: Any)(afterSend: ⇒ Unit): Unit = { + private def verifySend(msg: Any)(afterSend: => Unit): Unit = { val bigBounceId = s"bigBounce-${ThreadLocalRandom.current.nextInt()}" val bigBounceOther = remoteSystem.actorOf(Props(new Actor { def receive = { - case x: Int ⇒ sender() ! byteStringOfSize(x) - case x ⇒ sender() ! x + case x: Int => sender() ! byteStringOfSize(x) + case x => sender() ! x } }).withDeploy(Deploy.local), bigBounceId) val bigBounceHere = system.actorFor(s"akka.test://remote-sys@localhost:12346/user/$bigBounceId") val eventForwarder = system.actorOf(Props(new Actor { def receive = { - case x ⇒ testActor ! x + case x => testActor ! x } }).withDeploy(Deploy.local)) system.eventStream.subscribe(eventForwarder, classOf[AssociationErrorEvent]) @@ -220,8 +220,8 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D "support ask" in { Await.result(here ? "ping", timeout.duration) match { - case ("pong", s: akka.pattern.PromiseActorRef) ⇒ // good - case m ⇒ fail(m + " was not (pong, AskActorRef)") + case ("pong", s: akka.pattern.PromiseActorRef) => // good + case m => fail(m + " was not (pong, AskActorRef)") } } @@ -235,39 +235,39 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D val tcpOnlyConfig = ConfigFactory.parseString("""akka.remote.enabled-transports = ["akka.remote.netty.tcp"]"""). withFallback(remoteSystem.settings.config) val moreSystems = Vector.fill(5)(ActorSystem(remoteSystem.name, tcpOnlyConfig)) - moreSystems foreach { sys ⇒ + moreSystems foreach { sys => sys.eventStream.publish(TestEvent.Mute( EventFilter[EndpointDisassociatedException](), EventFilter.warning(pattern = "received dead letter.*"))) sys.actorOf(Props[Echo2], name = "echo") } - val moreRefs = moreSystems map (sys ⇒ system.actorSelection(RootActorPath(getOtherAddress(sys, "tcp")) / "user" / "echo")) + val moreRefs = moreSystems map (sys => system.actorSelection(RootActorPath(getOtherAddress(sys, "tcp")) / "user" / "echo")) val aliveEcho = system.actorSelection(RootActorPath(getOtherAddress(remoteSystem, "tcp")) / "user" / "echo") val n = 100 // first everything is up and running - 1 to n foreach { x ⇒ + 1 to n foreach { x => aliveEcho ! "ping" moreRefs(x % moreSystems.size) ! "ping" } within(5.seconds) { - receiveN(n * 2) foreach { reply ⇒ reply should ===(("pong", testActor)) } + receiveN(n * 2) foreach { reply => reply should ===(("pong", testActor)) } } // then we shutdown all but one system to simulate broken connections - moreSystems foreach { sys ⇒ + moreSystems foreach { sys => shutdown(sys) } - 1 to n foreach { x ⇒ + 1 to n foreach { x => aliveEcho ! "ping" moreRefs(x % moreSystems.size) ! "ping" } // ping messages to aliveEcho should go through even though we use many different broken connections within(5.seconds) { - receiveN(n) foreach { reply ⇒ reply should ===(("pong", testActor)) } + receiveN(n) foreach { reply => reply should ===(("pong", testActor)) } } } @@ -319,8 +319,8 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D "look-up actors across node boundaries" in { val l = system.actorOf(Props(new Actor { def receive = { - case (p: Props, n: String) ⇒ sender() ! context.actorOf(p, n) - case ActorForReq(s) ⇒ sender() ! context.actorFor(s) + case (p: Props, n: String) => sender() ! context.actorOf(p, n) + case ActorForReq(s) => sender() ! context.actorFor(s) } }), "looker1") // child is configured to be deployed on remote-sys (remoteSystem) @@ -362,8 +362,8 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D "select actors across node boundaries" in { val l = system.actorOf(Props(new Actor { def receive = { - case (p: Props, n: String) ⇒ sender() ! context.actorOf(p, n) - case ActorSelReq(s) ⇒ sender() ! context.actorSelection(s) + case (p: Props, n: String) => sender() ! context.actorOf(p, n) + case ActorSelReq(s) => sender() ! context.actorSelection(s) } }), "looker2") // child is configured to be deployed on remoteSystem @@ -455,7 +455,7 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D "not fail ask across node boundaries" in within(5.seconds) { import system.dispatcher - val f = for (_ ← 1 to 1000) yield here ? "ping" mapTo manifest[(String, ActorRef)] + val f = for (_ <- 1 to 1000) yield here ? "ping" mapTo manifest[(String, ActorRef)] Await.result(Future.sequence(f), timeout.duration).map(_._1).toSet should ===(Set("pong")) } @@ -606,8 +606,8 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D awaitCond(registry.transportsReady(rawLocalAddress)) awaitCond { registry.transportFor(rawLocalAddress) match { - case None ⇒ false - case Some((testTransport, _)) ⇒ + case None => false + case Some((testTransport, _)) => testTransport.associateBehavior.pushError(new InvalidAssociationException("Test connection error")) true } diff --git a/akka-remote/src/test/scala/akka/remote/Ticket1978CommunicationSpec.scala b/akka-remote/src/test/scala/akka/remote/Ticket1978CommunicationSpec.scala index 754ec86844..df0611bc32 100644 --- a/akka-remote/src/test/scala/akka/remote/Ticket1978CommunicationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/Ticket1978CommunicationSpec.scala @@ -85,7 +85,7 @@ object Configuration { CipherConfig(true, config, cipher, localPort, remotePort, Some(sslEngineProvider)) } catch { - case _: IllegalArgumentException | _: NoSuchAlgorithmException ⇒ + case _: IllegalArgumentException | _: NoSuchAlgorithmException => CipherConfig(false, AkkaSpec.testConf, cipher, localPort, remotePort, None) // Cannot match against the message since the message might be localized :S } } @@ -117,7 +117,7 @@ abstract class Ticket1978CommunicationSpec(val cipherConfig: CipherConfig) exten ("-") must { if (cipherConfig.runTest && preCondition) { - val ignoreMe = other.actorOf(Props(new Actor { def receive = { case ("ping", x) ⇒ sender() ! ((("pong", x), sender())) } }), "echo") + val ignoreMe = other.actorOf(Props(new Actor { def receive = { case ("ping", x) => sender() ! ((("pong", x), sender())) } }), "echo") val otherAddress = other.asInstanceOf[ExtendedActorSystem].provider.asInstanceOf[RemoteActorRefProvider].transport.defaultAddress "generate random" in { @@ -125,7 +125,7 @@ abstract class Ticket1978CommunicationSpec(val cipherConfig: CipherConfig) exten val bytes = Array.ofDim[Byte](16) // awaitAssert just in case we are very unlucky to get same sequence more than once awaitAssert { - val randomBytes = (1 to 10).map { n ⇒ + val randomBytes = (1 to 10).map { n => rng.nextBytes(bytes) bytes.toVector }.toSet @@ -158,8 +158,8 @@ abstract class Ticket1978CommunicationSpec(val cipherConfig: CipherConfig) exten expectMsgType[ActorIdentity].ref.get } - for (i ← 1 to 1000) here ! (("ping", i)) - for (i ← 1 to 1000) expectMsgPF() { case (("pong", i), `testActor`) ⇒ true } + for (i <- 1 to 1000) here ! (("ping", i)) + for (i <- 1 to 1000) expectMsgPF() { case (("pong", i), `testActor`) => true } } "support ask" in within(timeout.duration) { @@ -169,7 +169,7 @@ abstract class Ticket1978CommunicationSpec(val cipherConfig: CipherConfig) exten expectMsgType[ActorIdentity].ref.get } - val f = for (i ← 1 to 1000) yield here ? (("ping", i)) mapTo classTag[((String, Int), ActorRef)] + val f = for (i <- 1 to 1000) yield here ? (("ping", i)) mapTo classTag[((String, Int), ActorRef)] Await.result(Future.sequence(f), remaining).map(_._1._1).toSet should ===(Set("pong")) } diff --git a/akka-remote/src/test/scala/akka/remote/TransientSerializationErrorSpec.scala b/akka-remote/src/test/scala/akka/remote/TransientSerializationErrorSpec.scala index cf9b490fd9..9efd417520 100644 --- a/akka-remote/src/test/scala/akka/remote/TransientSerializationErrorSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/TransientSerializationErrorSpec.scala @@ -22,22 +22,22 @@ object TransientSerializationErrorSpec { class TestSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest { def identifier: Int = 666 def manifest(o: AnyRef): String = o match { - case ManifestNotSerializable ⇒ throw new NotSerializableException() - case ManifestIllegal ⇒ throw new IllegalArgumentException() - case ToBinaryNotSerializable ⇒ "TBNS" - case ToBinaryIllegal ⇒ "TI" - case NotDeserializable ⇒ "ND" - case IllegalOnDeserialize ⇒ "IOD" + case ManifestNotSerializable => throw new NotSerializableException() + case ManifestIllegal => throw new IllegalArgumentException() + case ToBinaryNotSerializable => "TBNS" + case ToBinaryIllegal => "TI" + case NotDeserializable => "ND" + case IllegalOnDeserialize => "IOD" } def toBinary(o: AnyRef): Array[Byte] = o match { - case ToBinaryNotSerializable ⇒ throw new NotSerializableException() - case ToBinaryIllegal ⇒ throw new IllegalArgumentException() - case _ ⇒ Array.emptyByteArray + case ToBinaryNotSerializable => throw new NotSerializableException() + case ToBinaryIllegal => throw new IllegalArgumentException() + case _ => Array.emptyByteArray } def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { manifest match { - case "ND" ⇒ throw new NotSerializableException() // Not sure this applies here - case "IOD" ⇒ throw new IllegalArgumentException() + case "ND" => throw new NotSerializableException() // Not sure this applies here + case "IOD" => throw new IllegalArgumentException() } } } @@ -96,7 +96,7 @@ abstract class AbstractTransientSerializationErrorSpec(config: Config) extends A ToBinaryNotSerializable, NotDeserializable, IllegalOnDeserialize - ).foreach(msg ⇒ + ).foreach(msg => selection.tell(msg, this.testActor) ) diff --git a/akka-remote/src/test/scala/akka/remote/TypedActorRemoteDeploySpec.scala b/akka-remote/src/test/scala/akka/remote/TypedActorRemoteDeploySpec.scala index ecf987127e..9a4159dd40 100644 --- a/akka-remote/src/test/scala/akka/remote/TypedActorRemoteDeploySpec.scala +++ b/akka-remote/src/test/scala/akka/remote/TypedActorRemoteDeploySpec.scala @@ -35,7 +35,7 @@ class TypedActorRemoteDeploySpec extends AkkaSpec(conf) { val remoteSystem = ActorSystem(remoteName, conf) val remoteAddress = RARP(remoteSystem).provider.getDefaultAddress - def verify[T](f: RemoteNameService ⇒ Future[T], expected: T) = { + def verify[T](f: RemoteNameService => Future[T], expected: T) = { val ts = TypedActor(system) val echoService: RemoteNameService = ts.typedActorOf( TypedProps[RemoteNameServiceImpl].withDeploy(Deploy(scope = RemoteScope(remoteAddress)))) diff --git a/akka-remote/src/test/scala/akka/remote/UntrustedSpec.scala b/akka-remote/src/test/scala/akka/remote/UntrustedSpec.scala index 7c28bbc249..eee349e1ec 100644 --- a/akka-remote/src/test/scala/akka/remote/UntrustedSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/UntrustedSpec.scala @@ -35,9 +35,9 @@ object UntrustedSpec { context.actorOf(Props(classOf[FakeUser], testActor), "user") def receive = { - case IdentifyReq(path) ⇒ context.actorSelection(path).tell(Identify(None), sender()) - case StopChild(name) ⇒ context.child(name) foreach context.stop - case msg ⇒ testActor forward msg + case IdentifyReq(path) => context.actorSelection(path).tell(Identify(None), sender()) + case StopChild(name) => context.child(name) foreach context.stop + case msg => testActor forward msg } } @@ -46,14 +46,14 @@ object UntrustedSpec { testActor ! s"${self.path.name} stopped" } def receive = { - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } class FakeUser(testActor: ActorRef) extends Actor { context.actorOf(Props(classOf[Child], testActor), "receptionist") def receive = { - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } @@ -113,8 +113,8 @@ akka.loglevel = DEBUG # test verifies debug system.eventStream.subscribe(system.actorOf(Props(new Actor { import Logging._ def receive = { - case d @ Debug(_, _, msg: String) if msg contains "dropping" ⇒ logProbe.ref ! d - case _ ⇒ + case d @ Debug(_, _, msg: String) if msg contains "dropping" => logProbe.ref ! d + case _ => } }).withDeploy(Deploy.local), "debugSniffer"), classOf[Logging.Debug]) @@ -134,7 +134,7 @@ akka.loglevel = DEBUG # test verifies debug client.actorOf(Props(new Actor { context.watch(target2) def receive = { - case x ⇒ testActor forward x + case x => testActor forward x } }).withDeploy(Deploy.local)) receptionist ! StopChild("child2") diff --git a/akka-remote/src/test/scala/akka/remote/artery/ArteryMultiNodeSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/ArteryMultiNodeSpec.scala index 682944ba9e..7a234aac82 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/ArteryMultiNodeSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/ArteryMultiNodeSpec.scala @@ -30,8 +30,8 @@ abstract class ArteryMultiNodeSpec(config: Config) extends AkkaSpec(config.withF def freePort(): Int = { val udp = ArteryMultiNodeSpec.arteryUdpEnabled(system.settings.config) (address(system).host match { - case Some(host) ⇒ SocketUtil.temporaryServerAddress(host, udp) - case None ⇒ SocketUtil.temporaryServerAddress(udp = udp) + case Some(host) => SocketUtil.temporaryServerAddress(host, udp) + case None => SocketUtil.temporaryServerAddress(udp = udp) }).getPort } @@ -49,13 +49,13 @@ abstract class ArteryMultiNodeSpec(config: Config) extends AkkaSpec(config.withF ArterySpecSupport.newFlightRecorderConfig.withFallback(extraConfig.fold( localSystem.settings.config )( - str ⇒ ConfigFactory.parseString(str).withFallback(localSystem.settings.config) + str => ConfigFactory.parseString(str).withFallback(localSystem.settings.config) )) val sysName = name.getOrElse(nextGeneratedSystemName) val remoteSystem = setup match { - case None ⇒ ActorSystem(sysName, config) - case Some(s) ⇒ ActorSystem(sysName, s.and(BootstrapSetup.apply(config))) + case None => ActorSystem(sysName, config) + case Some(s) => ActorSystem(sysName, s.and(BootstrapSetup.apply(config))) } remoteSystems = remoteSystems :+ remoteSystem @@ -64,7 +64,7 @@ abstract class ArteryMultiNodeSpec(config: Config) extends AkkaSpec(config.withF } override def afterTermination(): Unit = { - remoteSystems.foreach(sys ⇒ shutdown(sys)) + remoteSystems.foreach(sys => shutdown(sys)) (system +: remoteSystems).foreach(handleFlightRecorderFile) remoteSystems = Vector.empty super.afterTermination() diff --git a/akka-remote/src/test/scala/akka/remote/artery/ArterySpecSupport.scala b/akka-remote/src/test/scala/akka/remote/artery/ArterySpecSupport.scala index 281885f229..247ccae16a 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/ArterySpecSupport.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/ArterySpecSupport.scala @@ -76,7 +76,7 @@ object ArterySpecSupport { * afterTermination and call handleFlightRecorderFile manually in the spec or else it will not be dumped * on failure but also leak the afr file */ -trait FlightRecorderSpecIntegration { self: AkkaSpec ⇒ +trait FlightRecorderSpecIntegration { self: AkkaSpec => def system: ActorSystem diff --git a/akka-remote/src/test/scala/akka/remote/artery/BindCanonicalAddressSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/BindCanonicalAddressSpec.scala index fea6b946d7..672738b71d 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/BindCanonicalAddressSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/BindCanonicalAddressSpec.scala @@ -17,7 +17,7 @@ import akka.testkit.SocketUtil import java.net.InetAddress trait BindCanonicalAddressBehaviors { - this: WordSpec with Matchers ⇒ + this: WordSpec with Matchers => def arteryConnectionTest(transport: String, isUDP: Boolean): Unit = { val commonConfig = BindCanonicalAddressSpec.commonConfig(transport) @@ -47,7 +47,7 @@ trait BindCanonicalAddressBehaviors { getExternal should ===(address.toAkkaAddress("akka")) // May have selected the same random port - bind another in that case while the other still has the canonical port - val internals = if (getInternal.collect { case Address(_, _, _, Some(port)) ⇒ port }.toSeq.contains(address.getPort)) { + val internals = if (getInternal.collect { case Address(_, _, _, Some(port)) => port }.toSeq.contains(address.getPort)) { val sys2 = ActorSystem("sys", config.withFallback(commonConfig)) val secondInternals = getInternal()(sys2) Await.result(sys2.terminate(), Duration.Inf) diff --git a/akka-remote/src/test/scala/akka/remote/artery/DuplicateHandshakeSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/DuplicateHandshakeSpec.scala index d810fb47fb..6d0e0e3b1f 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/DuplicateHandshakeSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/DuplicateHandshakeSpec.scala @@ -35,13 +35,13 @@ class DuplicateHandshakeSpec extends AkkaSpec with ImplicitSender { private def setupStream(inboundContext: InboundContext, timeout: FiniteDuration = 5.seconds): (TestPublisher.Probe[AnyRef], TestSubscriber.Probe[Any]) = { TestSource.probe[AnyRef] - .map { msg ⇒ + .map { msg => val association = inboundContext.association(addressA.uid) val ser = serialization.serializerFor(msg.getClass) val serializerId = ser.identifier val manifest = ser match { - case s: SerializerWithStringManifest ⇒ s.manifest(msg) - case _ ⇒ "" + case s: SerializerWithStringManifest => s.manifest(msg) + case _ => "" } val env = new ReusableInboundEnvelope @@ -51,7 +51,7 @@ class DuplicateHandshakeSpec extends AkkaSpec with ImplicitSender { env } .via(new DuplicateHandshakeReq(numberOfLanes = 3, inboundContext, system.asInstanceOf[ExtendedActorSystem], pool)) - .map { case env: InboundEnvelope ⇒ (env.message -> env.lane) } + .map { case env: InboundEnvelope => (env.message -> env.lane) } .toMat(TestSink.probe[Any])(Keep.both) .run() } diff --git a/akka-remote/src/test/scala/akka/remote/artery/EnvelopeBufferSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/EnvelopeBufferSpec.scala index e6009f1760..64e620e95e 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/EnvelopeBufferSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/EnvelopeBufferSpec.scala @@ -17,19 +17,19 @@ class EnvelopeBufferSpec extends AkkaSpec { object TestCompressor extends InboundCompressions { val refToIdx: Map[ActorRef, Int] = Map( - minimalRef("compressable0") → 0, - minimalRef("compressable1") → 1, - minimalRef("reallylongcompressablestring") → 2) + minimalRef("compressable0") -> 0, + minimalRef("compressable1") -> 1, + minimalRef("reallylongcompressablestring") -> 2) val idxToRef: Map[Int, ActorRef] = refToIdx.map(_.swap) val serializerToIdx = Map( - "serializer0" → 0, - "serializer1" → 1) + "serializer0" -> 0, + "serializer1" -> 1) val idxToSer = serializerToIdx.map(_.swap) val manifestToIdx = Map( - "manifest0" → 0, - "manifest1" → 1) + "manifest0" -> 0, + "manifest1" -> 1) val idxToManifest = manifestToIdx.map(_.swap) val outboundActorRefTable: CompressionTable[ActorRef] = diff --git a/akka-remote/src/test/scala/akka/remote/artery/FlightRecorderSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/FlightRecorderSpec.scala index 50bf6de208..cdc52901e6 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/FlightRecorderSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/FlightRecorderSpec.scala @@ -19,7 +19,7 @@ class FlightRecorderSpec extends AkkaSpec { "Flight Recorder" must { - "properly initialize AFR file when created" in withFlightRecorder { (_, reader, channel) ⇒ + "properly initialize AFR file when created" in withFlightRecorder { (_, reader, channel) => channel.force(false) // otherwise isAfter assertion below can randomly fail @@ -58,13 +58,13 @@ class FlightRecorderSpec extends AkkaSpec { checkLogInitialized(reader.structure.hiFreqLog) } - "properly rotate logs when snapshotting" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly rotate logs when snapshotting" in withFlightRecorder { (recorder, reader, channel) => recorder.snapshot() channel.force(false) reader.rereadStructure() def checkLogRotated(log: reader.RollingLog, states: Seq[LogState]): Unit = - log.logs.zip(states).foreach { case (log, state) ⇒ log.state should ===(state) } + log.logs.zip(states).foreach { case (log, state) => log.state should ===(state) } checkLogRotated(reader.structure.alertLog, List(Snapshot, Live, Empty, Empty)) checkLogRotated(reader.structure.loFreqLog, List(Snapshot, Live, Empty, Empty)) @@ -86,7 +86,7 @@ class FlightRecorderSpec extends AkkaSpec { checkLogRotated(reader.structure.hiFreqLog, List(Live, Snapshot, Snapshot, Snapshot)) } - "properly report zero low frequency events" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly report zero low frequency events" in withFlightRecorder { (recorder, reader, channel) => channel.force(false) reader.rereadStructure() @@ -95,7 +95,7 @@ class FlightRecorderSpec extends AkkaSpec { entries.isEmpty should be(true) } - "properly report zero high frequency events" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly report zero high frequency events" in withFlightRecorder { (recorder, reader, channel) => channel.force(false) reader.rereadStructure() @@ -104,7 +104,7 @@ class FlightRecorderSpec extends AkkaSpec { entries.isEmpty should be(true) } - "properly store one low frequency event" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store one low frequency event" in withFlightRecorder { (recorder, reader, channel) => val sink = recorder.createEventSink() val helloBytes = "Hello".getBytes("US-ASCII") @@ -118,7 +118,7 @@ class FlightRecorderSpec extends AkkaSpec { entries.map(_.code.toInt) should ===(List(42)) } - "properly store one high frequency event" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store one high frequency event" in withFlightRecorder { (recorder, reader, channel) => val sink = recorder.createEventSink() sink.hiFreq(42, 64) @@ -133,11 +133,11 @@ class FlightRecorderSpec extends AkkaSpec { entries.map(_.param.toInt) should ===(List(64)) } - "properly store low frequency events" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store low frequency events" in withFlightRecorder { (recorder, reader, channel) => val sink = recorder.createEventSink() val helloBytes = "Hello".getBytes("US-ASCII") - for (i ← 0 until FlightRecorder.LoFreqWindow) + for (i <- 0 until FlightRecorder.LoFreqWindow) sink.loFreq(i, helloBytes) channel.force(false) @@ -147,13 +147,13 @@ class FlightRecorderSpec extends AkkaSpec { entries.exists(_.dirty) should be(false) entries.map(_.code.toInt) should ===(0 until FlightRecorder.LoFreqWindow) - entries.forall(entry ⇒ Arrays.equals(entry.metadata, helloBytes)) should be(true) + entries.forall(entry => Arrays.equals(entry.metadata, helloBytes)) should be(true) // Timestamps are monotonic entries.sortBy(_.code) should ===(entries.sortBy(_.timeStamp)) } - "properly truncate low frequency event metadata if necessary" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly truncate low frequency event metadata if necessary" in withFlightRecorder { (recorder, reader, channel) => val sink = recorder.createEventSink() val longMetadata = new Array[Byte](1024) @@ -168,11 +168,11 @@ class FlightRecorderSpec extends AkkaSpec { } - "properly store high frequency events" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store high frequency events" in withFlightRecorder { (recorder, reader, channel) => val EffectiveHighFreqWindow = FlightRecorder.HiFreqWindow * FlightRecorder.HiFreqBatchSize val sink = recorder.createEventSink() - for (i ← 0 until EffectiveHighFreqWindow) + for (i <- 0 until EffectiveHighFreqWindow) sink.hiFreq(i, 42) sink.flushHiFreqBatch() @@ -183,17 +183,17 @@ class FlightRecorderSpec extends AkkaSpec { entries.exists(_.dirty) should be(false) entries.map(_.code.toInt) should ===(0 until EffectiveHighFreqWindow) - entries.forall(entry ⇒ entry.param == 42) should be(true) + entries.forall(entry => entry.param == 42) should be(true) // Timestamps are monotonic entries.sortBy(_.code) should ===(entries.sortBy(_.timeStamp)) } - "properly store and rotate low frequency events" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store and rotate low frequency events" in withFlightRecorder { (recorder, reader, channel) => val sink = recorder.createEventSink() val helloBytes = "Hello".getBytes("US-ASCII") - for (i ← 0 until FlightRecorder.LoFreqWindow + 100) + for (i <- 0 until FlightRecorder.LoFreqWindow + 100) sink.loFreq(i, helloBytes) channel.force(false) @@ -203,17 +203,17 @@ class FlightRecorderSpec extends AkkaSpec { entries.exists(_.dirty) should be(false) entries.map(_.code.toInt).sorted should ===(100 until (FlightRecorder.LoFreqWindow + 100)) - entries.forall(entry ⇒ Arrays.equals(entry.metadata, helloBytes)) should be(true) + entries.forall(entry => Arrays.equals(entry.metadata, helloBytes)) should be(true) // Timestamps are monotonic entries.sortBy(_.code) should ===(entries.sortBy(_.timeStamp)) } - "properly store and rotate high frequency events" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store and rotate high frequency events" in withFlightRecorder { (recorder, reader, channel) => val EffectiveHighFreqWindow = FlightRecorder.HiFreqWindow * FlightRecorder.HiFreqBatchSize val sink = recorder.createEventSink() - for (i ← 0 until EffectiveHighFreqWindow + 100) + for (i <- 0 until EffectiveHighFreqWindow + 100) sink.hiFreq(i, 42) sink.flushHiFreqBatch() @@ -226,23 +226,23 @@ class FlightRecorderSpec extends AkkaSpec { // Note the (2 * FlightRecorder.HiFreqBatchSize) initial sequence number. // This is because the overflow by 100 events rotates out two records, not just 100. entries.map(_.code.toInt).sorted should ===((2 * FlightRecorder.HiFreqBatchSize) until (EffectiveHighFreqWindow + 100)) - entries.forall(entry ⇒ entry.param == 42) should be(true) + entries.forall(entry => entry.param == 42) should be(true) // Timestamps are monotonic entries.sortBy(_.code) should ===(entries.sortBy(_.timeStamp)) } - "properly store low frequency events after snapshot" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store low frequency events after snapshot" in withFlightRecorder { (recorder, reader, channel) => val sink = recorder.createEventSink() val helloBytes = "Hello".getBytes("US-ASCII") val hello2Bytes = "Hello2".getBytes("US-ASCII") - for (i ← 0 until 100) + for (i <- 0 until 100) sink.loFreq(i, helloBytes) recorder.snapshot() - for (i ← 0 until 50) + for (i <- 0 until 50) sink.loFreq(i, hello2Bytes) reader.rereadStructure() @@ -255,29 +255,29 @@ class FlightRecorderSpec extends AkkaSpec { snapshotEntries.exists(_.dirty) should be(false) snapshotEntries.map(_.code.toInt) should ===(0 until 100) - snapshotEntries.forall(entry ⇒ Arrays.equals(entry.metadata, helloBytes)) should be(true) + snapshotEntries.forall(entry => Arrays.equals(entry.metadata, helloBytes)) should be(true) // Timestamps are monotonic snapshotEntries.sortBy(_.code) should ===(snapshotEntries.sortBy(_.timeStamp)) liveEntries.exists(_.dirty) should be(false) liveEntries.map(_.code.toInt) should ===(0 until 50) - liveEntries.forall(entry ⇒ Arrays.equals(entry.metadata, hello2Bytes)) should be(true) + liveEntries.forall(entry => Arrays.equals(entry.metadata, hello2Bytes)) should be(true) // Timestamps are monotonic liveEntries.sortBy(_.code) should ===(liveEntries.sortBy(_.timeStamp)) } - "properly store high frequency events after snapshot" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store high frequency events after snapshot" in withFlightRecorder { (recorder, reader, channel) => val sink = recorder.createEventSink() - for (i ← 0 until 100) + for (i <- 0 until 100) sink.hiFreq(i, 0) sink.flushHiFreqBatch() recorder.snapshot() - for (i ← 0 until 50) + for (i <- 0 until 50) sink.hiFreq(i, 1) sink.flushHiFreqBatch() @@ -305,12 +305,12 @@ class FlightRecorderSpec extends AkkaSpec { liveEntries.sortBy(_.code) should ===(liveEntries.sortBy(_.timeStamp)) } - "properly store alerts and make a snapshot" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store alerts and make a snapshot" in withFlightRecorder { (recorder, reader, channel) => val sink = recorder.createEventSink() val helloBytes = "Hello".getBytes("US-ASCII") val alertBytes = "An alert".getBytes("US-ASCII") - for (i ← 0 until 100) { + for (i <- 0 until 100) { sink.hiFreq(i, 1) sink.loFreq(i, helloBytes) } @@ -335,23 +335,23 @@ class FlightRecorderSpec extends AkkaSpec { hiFreqEntries.map(_.code.toInt) should ===(0 until 100) hiFreqEntries.forall(_.param == 1) should be(true) loFreqEntries.map(_.code.toInt) should ===(0 until 100) - loFreqEntries.forall(entry ⇒ Arrays.equals(entry.metadata, helloBytes)) should be(true) + loFreqEntries.forall(entry => Arrays.equals(entry.metadata, helloBytes)) should be(true) alertEntries.map(_.code.toInt) should ===(List(42)) Arrays.equals(alertEntries.head.metadata, alertBytes) should be(true) } - "properly store events from multiple threads" in withFlightRecorder { (recorder, reader, channel) ⇒ + "properly store events from multiple threads" in withFlightRecorder { (recorder, reader, channel) => val Threads = 4 val startLatch = new CountDownLatch(1) val finishLatch = new CountDownLatch(Threads) - for (i ← 1 to Threads) { + for (i <- 1 to Threads) { new Thread { override def run(): Unit = { val sink = recorder.createEventSink() startLatch.await(3, TimeUnit.SECONDS) - for (j ← 0 until 100) sink.loFreq(code = i, Array(j.toByte)) + for (j <- 0 until 100) sink.loFreq(code = i, Array(j.toByte)) finishLatch.countDown() } }.start() @@ -364,7 +364,7 @@ class FlightRecorderSpec extends AkkaSpec { reader.structure.loFreqLog.logs.head.richEntries.size should ===(FlightRecorder.LoFreqWindow) - for (i ← 1 to Threads) { + for (i <- 1 to Threads) { val entries = reader.structure.loFreqLog.logs.head.richEntries.filter(_.code == i).toSeq entries.exists(_.dirty) should be(false) @@ -407,7 +407,7 @@ class FlightRecorderSpec extends AkkaSpec { } - private def withFlightRecorder(body: (FlightRecorder, FlightRecorderReader, FileChannel) ⇒ Unit): Unit = { + private def withFlightRecorder(body: (FlightRecorder, FlightRecorderReader, FileChannel) => Unit): Unit = { val file = File.createTempFile("artery", ".afr") file.deleteOnExit() @@ -433,7 +433,7 @@ class FlightRecorderSpec extends AkkaSpec { if (reader ne null) reader.close() if (channel ne null) channel.close() file.delete() - } catch { case e: IOException ⇒ e.printStackTrace() } + } catch { case e: IOException => e.printStackTrace() } } } diff --git a/akka-remote/src/test/scala/akka/remote/artery/FlushOnShutdownSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/FlushOnShutdownSpec.scala index a85511ca19..23d2c7f0f8 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/FlushOnShutdownSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/FlushOnShutdownSpec.scala @@ -23,16 +23,16 @@ class FlushOnShutdownSpec extends ArteryMultiNodeSpec(ArterySpecSupport.defaultC localSystem.actorOf(Props(new Actor { def receive = { - case msg ⇒ probeRef ! msg + case msg => probeRef ! msg } }), "receiver") val actorOnSystemB = remoteSystem.actorOf(Props(new Actor { def receive = { - case "start" ⇒ + case "start" => context.actorSelection(rootActorPath(localSystem) / "user" / "receiver") ! Identify(None) - case ActorIdentity(_, Some(receiverRef)) ⇒ + case ActorIdentity(_, Some(receiverRef)) => receiverRef ! "msg1" receiverRef ! "msg2" receiverRef ! "msg3" diff --git a/akka-remote/src/test/scala/akka/remote/artery/ImmutableLongMapSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/ImmutableLongMapSpec.scala index 7edc799b39..add84ac8db 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/ImmutableLongMapSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/ImmutableLongMapSpec.scala @@ -122,20 +122,20 @@ class ImmutableLongMapSpec extends WordSpec with Matchers { var reference = Map.empty[Long, String] def verify(): Unit = { - val m = longMap.keysIterator.map(key ⇒ key → longMap.get(key).get).toMap + val m = longMap.keysIterator.map(key => key -> longMap.get(key).get).toMap m should be(reference) } - (1 to 1000).foreach { i ⇒ + (1 to 1000).foreach { i => withClue(s"seed=$seed, iteration=$i") { val key = rnd.nextInt(100) val value = String.valueOf(rnd.nextPrintableChar()) rnd.nextInt(3) match { - case 0 | 1 ⇒ + case 0 | 1 => longMap = longMap.updated(key, value) reference = reference.updated(key, value) - case 2 ⇒ + case 2 => longMap = longMap.remove(key) reference = reference - key } diff --git a/akka-remote/src/test/scala/akka/remote/artery/InboundControlJunctionSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/InboundControlJunctionSpec.scala index 3e1109c173..a5c9f04f02 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/InboundControlJunctionSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/InboundControlJunctionSpec.scala @@ -50,9 +50,9 @@ class InboundControlJunctionSpec val recipient = OptionVal.None // not used val ((upstream, controlSubject), downstream) = TestSource.probe[AnyRef] - .map(msg ⇒ InboundEnvelope(recipient, msg, OptionVal.None, addressA.uid, OptionVal.None)) + .map(msg => InboundEnvelope(recipient, msg, OptionVal.None, addressA.uid, OptionVal.None)) .viaMat(new InboundControlJunction)(Keep.both) - .map { case env: InboundEnvelope ⇒ env.message } + .map { case env: InboundEnvelope => env.message } .toMat(TestSink.probe[Any])(Keep.both) .run() diff --git a/akka-remote/src/test/scala/akka/remote/artery/InboundHandshakeSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/InboundHandshakeSpec.scala index eca5fe3dbc..142461bb7d 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/InboundHandshakeSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/InboundHandshakeSpec.scala @@ -39,10 +39,10 @@ class InboundHandshakeSpec extends AkkaSpec with ImplicitSender { private def setupStream(inboundContext: InboundContext, timeout: FiniteDuration = 5.seconds): (TestPublisher.Probe[AnyRef], TestSubscriber.Probe[Any]) = { val recipient = OptionVal.None // not used TestSource.probe[AnyRef] - .map(msg ⇒ InboundEnvelope(recipient, msg, OptionVal.None, addressA.uid, + .map(msg => InboundEnvelope(recipient, msg, OptionVal.None, addressA.uid, inboundContext.association(addressA.uid))) .via(new InboundHandshake(inboundContext, inControlStream = true)) - .map { case env: InboundEnvelope ⇒ env.message } + .map { case env: InboundEnvelope => env.message } .toMat(TestSink.probe[Any])(Keep.both) .run() } diff --git a/akka-remote/src/test/scala/akka/remote/artery/LargeMessagesStreamSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/LargeMessagesStreamSpec.scala index a44e952734..b8bad241b2 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/LargeMessagesStreamSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/LargeMessagesStreamSpec.scala @@ -19,7 +19,7 @@ object LargeMessagesStreamSpec { class EchoSize extends Actor { def receive = { - case Ping(bytes) ⇒ sender() ! Pong(bytes.size) + case Ping(bytes) => sender() ! Pong(bytes.size) } } } diff --git a/akka-remote/src/test/scala/akka/remote/artery/LruBoundedCacheSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/LruBoundedCacheSpec.scala index 270ad7879a..f2a39768c0 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/LruBoundedCacheSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/LruBoundedCacheSpec.scala @@ -66,7 +66,7 @@ class LruBoundedCacheSpec extends AkkaSpec { } "evict oldest when full" in { - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { val seed = Random.nextInt(1024) info(s"Variant $seed") val cache = new TestCache(4, 4, seed.toString) @@ -146,7 +146,7 @@ class LruBoundedCacheSpec extends AkkaSpec { } "work with a lower age threshold" in { - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { val seed = Random.nextInt(1024) info(s"Variant $seed") val cache = new TestCache(4, 2, seed.toString) @@ -203,14 +203,14 @@ class LruBoundedCacheSpec extends AkkaSpec { } "maintain a good average probe distance" in { - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { val seed = Random.nextInt(1024) info(s"Variant $seed") // Cache emulating 60% fill rate val cache = new TestCache(1024, 600, seed.toString) // Fill up cache - for (_ ← 1 to 10000) cache.getOrCompute(Random.nextString(32)) + for (_ <- 1 to 10000) cache.getOrCompute(Random.nextString(32)) val stats = cache.stats // Have not seen lower than 890 diff --git a/akka-remote/src/test/scala/akka/remote/artery/MetadataCarryingSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/MetadataCarryingSpec.scala index 7d493d1728..5f5af729b2 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/MetadataCarryingSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/MetadataCarryingSpec.scala @@ -43,19 +43,19 @@ class TestInstrument(system: ExtendedActorSystem) extends RemoteInstrument { override def remoteWriteMetadata(recipient: ActorRef, message: Object, sender: ActorRef, buffer: ByteBuffer): Unit = message match { - case _: MetadataCarryingSpec.Ping | ActorSelectionMessage(_: MetadataCarryingSpec.Ping, _, _) ⇒ + case _: MetadataCarryingSpec.Ping | ActorSelectionMessage(_: MetadataCarryingSpec.Ping, _, _) => val metadata = "!!!" buffer.putInt(metadata.length) encoder.encode(CharBuffer.wrap(metadata), buffer, true) encoder.flush(buffer) encoder.reset() MetadataCarryingSpy(system).ref.foreach(_ ! RemoteWriteMetadata(recipient, message, sender)) - case _ ⇒ + case _ => } override def remoteReadMetadata(recipient: ActorRef, message: Object, sender: ActorRef, buffer: ByteBuffer): Unit = message match { - case _: MetadataCarryingSpec.Ping | ActorSelectionMessage(_: MetadataCarryingSpec.Ping, _, _) ⇒ + case _: MetadataCarryingSpec.Ping | ActorSelectionMessage(_: MetadataCarryingSpec.Ping, _, _) => val size = buffer.getInt val charBuffer = CharBuffer.allocate(size) decoder.decode(buffer, charBuffer, false) @@ -63,21 +63,21 @@ class TestInstrument(system: ExtendedActorSystem) extends RemoteInstrument { charBuffer.flip() val metadata = charBuffer.toString MetadataCarryingSpy(system).ref.foreach(_ ! RemoteReadMetadata(recipient, message, sender, metadata)) - case _ ⇒ + case _ => } override def remoteMessageSent(recipient: ActorRef, message: Object, sender: ActorRef, size: Int, time: Long): Unit = message match { - case _: MetadataCarryingSpec.Ping | ActorSelectionMessage(_: MetadataCarryingSpec.Ping, _, _) ⇒ + case _: MetadataCarryingSpec.Ping | ActorSelectionMessage(_: MetadataCarryingSpec.Ping, _, _) => MetadataCarryingSpy(system).ref.foreach(_ ! RemoteMessageSent(recipient, message, sender, size, time)) - case _ ⇒ + case _ => } override def remoteMessageReceived(recipient: ActorRef, message: Object, sender: ActorRef, size: Int, time: Long): Unit = message match { - case _: MetadataCarryingSpec.Ping | ActorSelectionMessage(_: MetadataCarryingSpec.Ping, _, _) ⇒ + case _: MetadataCarryingSpec.Ping | ActorSelectionMessage(_: MetadataCarryingSpec.Ping, _, _) => MetadataCarryingSpy(system).ref.foreach(_ ! RemoteMessageReceived(recipient, message, sender, size, time)) - case _ ⇒ + case _ => } } @@ -87,8 +87,8 @@ object MetadataCarryingSpec { class ProxyActor(local: ActorRef, remotePath: ActorPath) extends Actor { val remote = context.system.actorSelection(remotePath) override def receive = { - case message if sender() == local ⇒ remote ! message - case message ⇒ local ! message + case message if sender() == local => remote ! message + case message => local ! message } } } diff --git a/akka-remote/src/test/scala/akka/remote/artery/OutboundControlJunctionSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/OutboundControlJunctionSpec.scala index 05b0d553fb..2093656f10 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/OutboundControlJunctionSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/OutboundControlJunctionSpec.scala @@ -36,9 +36,9 @@ class OutboundControlJunctionSpec extends AkkaSpec with ImplicitSender { val outboundContext = inboundContext.association(addressB.address) val ((upstream, controlIngress), downstream) = TestSource.probe[String] - .map(msg ⇒ outboundEnvelopePool.acquire().init(OptionVal.None, msg, OptionVal.None)) + .map(msg => outboundEnvelopePool.acquire().init(OptionVal.None, msg, OptionVal.None)) .viaMat(new OutboundControlJunction(outboundContext, outboundEnvelopePool))(Keep.both) - .map(env ⇒ env.message) + .map(env => env.message) .toMat(TestSink.probe[Any])(Keep.both) .run() diff --git a/akka-remote/src/test/scala/akka/remote/artery/OutboundHandshakeSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/OutboundHandshakeSpec.scala index 0cde987952..d410aa140b 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/OutboundHandshakeSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/OutboundHandshakeSpec.scala @@ -37,10 +37,10 @@ class OutboundHandshakeSpec extends AkkaSpec with ImplicitSender { livenessProbeInterval: Duration = Duration.Undefined): (TestPublisher.Probe[String], TestSubscriber.Probe[Any]) = { TestSource.probe[String] - .map(msg ⇒ outboundEnvelopePool.acquire().init(OptionVal.None, msg, OptionVal.None)) + .map(msg => outboundEnvelopePool.acquire().init(OptionVal.None, msg, OptionVal.None)) .via(new OutboundHandshake(system, outboundContext, outboundEnvelopePool, timeout, retryInterval, injectHandshakeInterval, livenessProbeInterval)) - .map(env ⇒ env.message) + .map(env => env.message) .toMat(TestSink.probe[Any])(Keep.both) .run() } diff --git a/akka-remote/src/test/scala/akka/remote/artery/OutboundIdleShutdownSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/OutboundIdleShutdownSpec.scala index ffff9be19c..d673061bb0 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/OutboundIdleShutdownSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/OutboundIdleShutdownSpec.scala @@ -51,7 +51,7 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" "Outbound streams" should { "be stopped when they are idle" in withAssociation { - (_, remoteAddress, remoteEcho, localArtery, localProbe) ⇒ + (_, remoteAddress, remoteEcho, localArtery, localProbe) => val association = localArtery.association(remoteAddress) withClue("When initiating a connection, both the control and ordinary streams are opened") { @@ -66,7 +66,7 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" } "still be resumable after they have been stopped" in withAssociation { - (_, remoteAddress, remoteEcho, localArtery, localProbe) ⇒ + (_, remoteAddress, remoteEcho, localArtery, localProbe) => val firstAssociation = localArtery.association(remoteAddress) eventually { @@ -88,7 +88,7 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" } "eliminate quarantined association when not used" in withAssociation { - (_, remoteAddress, remoteEcho, localArtery, localProbe) ⇒ + (_, remoteAddress, remoteEcho, localArtery, localProbe) => val association = localArtery.association(remoteAddress) withClue("When initiating a connection, both the control and ordinary streams are opened") { @@ -112,7 +112,7 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" } "remove inbound compression after quarantine" in withAssociation { - (_, remoteAddress, remoteEcho, localArtery, localProbe) ⇒ + (_, remoteAddress, remoteEcho, localArtery, localProbe) => val association = localArtery.association(remoteAddress) val remoteUid = association.associationState.uniqueRemoteAddress.futureValue.uid @@ -133,7 +133,7 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" } "remove inbound compression after restart with same host:port" in withAssociation { - (remoteSystem, remoteAddress, remoteEcho, localArtery, localProbe) ⇒ + (remoteSystem, remoteAddress, remoteEcho, localArtery, localProbe) => val association = localArtery.association(remoteAddress) val remoteUid = association.associationState.uniqueRemoteAddress.futureValue.uid @@ -181,7 +181,7 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" * 2. A TestProbe is spawned locally to initiate communication with the Echo actor * 3. Details (remoteAddress, remoteEcho, localArtery, localProbe) are supplied to the test */ - def withAssociation(test: (ActorSystem, Address, ActorRef, ArteryTransport, TestProbe) ⇒ Any): Unit = { + def withAssociation(test: (ActorSystem, Address, ActorRef, ArteryTransport, TestProbe) => Any): Unit = { val remoteSystem = newRemoteSystem() try { remoteSystem.actorOf(TestActors.echoActorProps, "echo") diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteActorForSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteActorForSpec.scala index 00c58726ee..cbc363c78a 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteActorForSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteActorForSpec.scala @@ -56,8 +56,8 @@ class RemoteActorForSpec extends ArteryMultiNodeSpec("akka.loglevel=INFO") with "look-up actors across node boundaries" ignore { val l = localSystem.actorOf(Props(new Actor { def receive = { - case (p: Props, n: String) ⇒ sender() ! context.actorOf(p, n) - case ActorForReq(s) ⇒ sender() ! context.actorFor(s) + case (p: Props, n: String) => sender() ! context.actorOf(p, n) + case ActorForReq(s) => sender() ! context.actorFor(s) } }), "looker1") // child is configured to be deployed on remote-sys (remoteSystem) diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteActorSelectionSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteActorSelectionSpec.scala index f278e4831b..c9078d12cd 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteActorSelectionSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteActorSelectionSpec.scala @@ -18,11 +18,11 @@ object RemoteActorSelectionSpec { log.info("Started") def receive = { // if we get props and a name, create a child, send ref back - case ActorCreateReq(p, n) ⇒ + case ActorCreateReq(p, n) => log.info(s"Creating child $n") sender() ! context.actorOf(p, n) // or select actor from here - case ActorSelReq(s) ⇒ sender() ! context.actorSelection(s) + case ActorSelReq(s) => sender() ! context.actorSelection(s) } } def selectionActorProps = Props(new SelectionActor) diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteDeathWatchSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteDeathWatchSpec.scala index 0135a412f5..8133c6b1a2 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteDeathWatchSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteDeathWatchSpec.scala @@ -64,7 +64,7 @@ class RemoteDeathWatchSpec extends ArteryMultiNodeSpec(RemoteDeathWatchSpec.conf context.watch(ref) def receive = { - case Terminated(r) ⇒ testActor ! r + case Terminated(r) => testActor ! r } }).withDeploy(Deploy.local)) @@ -78,7 +78,7 @@ class RemoteDeathWatchSpec extends ArteryMultiNodeSpec(RemoteDeathWatchSpec.conf system.actorOf(Props(new Actor { context.watch(context.actorFor(path)) def receive = { - case t: Terminated ⇒ testActor ! t.actor.path + case t: Terminated => testActor ! t.actor.path } }).withDeploy(Deploy.local), name = "observer2") diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteDeployerSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteDeployerSpec.scala index c57288e7a0..645cbb362e 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteDeployerSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteDeployerSpec.scala @@ -24,7 +24,7 @@ object RemoteDeployerSpec { """).withFallback(ArterySpecSupport.defaultConfig) class RecipeActor extends Actor { - def receive = { case _ ⇒ } + def receive = { case _ => } } } diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteDeploymentSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteDeploymentSpec.scala index 5ac77d14b4..f924376d00 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteDeploymentSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteDeploymentSpec.scala @@ -14,8 +14,8 @@ object RemoteDeploymentSpec { var target: ActorRef = context.system.deadLetters def receive = { - case ex: Exception ⇒ throw ex - case x ⇒ target = sender(); sender() ! x + case ex: Exception => throw ex + case x => target = sender(); sender() ! x } override def preStart(): Unit = {} @@ -35,20 +35,20 @@ object RemoteDeploymentSpec { var target: ActorRef = context.system.deadLetters override val supervisorStrategy = OneForOneStrategy() { - case e: Exception ⇒ + case e: Exception => probe ! e SupervisorStrategy.stop } def receive = { - case p: Props ⇒ + case p: Props => sender() ! context.actorOf(p) - case (p: Props, numMessages: Int) ⇒ + case (p: Props, numMessages: Int) => val child = context.actorOf(p) sender() ! child // stress as quick send as possible - (0 until numMessages).foreach(n ⇒ child.tell(n, sender())) + (0 until numMessages).foreach(n => child.tell(n, sender())) } } @@ -117,23 +117,23 @@ class RemoteDeploymentSpec extends ArteryMultiNodeSpec( val numChildren = 20 val numMessages = 5 - val parents = (0 until numParents).map { i ⇒ + val parents = (0 until numParents).map { i => masterSystem.actorOf(parentProps(testActor), s"parent-$i") }.toVector val probes = Vector.fill(numParents, numChildren)(TestProbe()(masterSystem)) val childProps = Props[Echo1] - for (p ← (0 until numParents); c ← (0 until numChildren)) { + for (p <- (0 until numParents); c <- (0 until numChildren)) { parents(p).tell((childProps, numMessages), probes(p)(c).ref) } - for (p ← (0 until numParents); c ← (0 until numChildren)) { + for (p <- (0 until numParents); c <- (0 until numChildren)) { val probe = probes(p)(c) probe.expectMsgType[ActorRef] // the child } val expectedMessages = (0 until numMessages).toVector - for (p ← (0 until numParents); c ← (0 until numChildren)) { + for (p <- (0 until numParents); c <- (0 until numChildren)) { val probe = probes(p)(c) probe.receiveN(numMessages) should equal(expectedMessages) } diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteFailureSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteFailureSpec.scala index 8859a0e44a..c2254c7c7c 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteFailureSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteFailureSpec.scala @@ -25,13 +25,13 @@ class RemoteFailureSpec extends ArteryMultiNodeSpec with ImplicitSender { "not be exhausted by sending to broken connections" in { val remoteSystems = Vector.fill(5)(newRemoteSystem()) - remoteSystems foreach { sys ⇒ + remoteSystems foreach { sys => sys.eventStream.publish(TestEvent.Mute( EventFilter[EndpointDisassociatedException](), EventFilter.warning(pattern = "received dead letter.*"))) sys.actorOf(TestActors.echoActorProps, name = "echo") } - val remoteSelections = remoteSystems map { sys ⇒ + val remoteSelections = remoteSystems map { sys => system.actorSelection(rootActorPath(sys) / "user" / "echo") } @@ -41,28 +41,28 @@ class RemoteFailureSpec extends ArteryMultiNodeSpec with ImplicitSender { val n = 100 // first everything is up and running - 1 to n foreach { x ⇒ + 1 to n foreach { x => localSelection ! Ping("1") remoteSelections(x % remoteSystems.size) ! Ping("1") } within(5.seconds) { - receiveN(n * 2) foreach { reply ⇒ reply should ===(Ping("1")) } + receiveN(n * 2) foreach { reply => reply should ===(Ping("1")) } } // then we shutdown remote systems to simulate broken connections - remoteSystems foreach { sys ⇒ + remoteSystems foreach { sys => shutdown(sys) } - 1 to n foreach { x ⇒ + 1 to n foreach { x => localSelection ! Ping("2") remoteSelections(x % remoteSystems.size) ! Ping("2") } // ping messages to localEcho should go through even though we use many different broken connections within(5.seconds) { - receiveN(n) foreach { reply ⇒ reply should ===(Ping("2")) } + receiveN(n) foreach { reply => reply should ===(Ping("2")) } } } diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteInstrumentsSerializationSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteInstrumentsSerializationSpec.scala index 6d6f07cd8b..dfb614f7c3 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteInstrumentsSerializationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteInstrumentsSerializationSpec.scala @@ -21,7 +21,7 @@ class RemoteInstrumentsSerializationSpec extends AkkaSpec("akka.loglevel = DEBUG new RemoteInstruments(system.asInstanceOf[ExtendedActorSystem], system.log, vec) } - def ensureDebugLog[T](messages: String*)(f: ⇒ T): T = { + def ensureDebugLog[T](messages: String*)(f: => T): T = { if (messages.isEmpty) f else diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteInstrumentsSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteInstrumentsSpec.scala index beb942b1fb..a5b6b525de 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteInstrumentsSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteInstrumentsSpec.scala @@ -18,8 +18,8 @@ class RemoteInstrumentsSpec extends WordSpec with Matchers with Checkers { implicit val arbitraryKeyLength: Arbitrary[KeyLen] = Arbitrary { for { - key ← Gen.chooseNum(0.toByte, 31.toByte) - len ← Gen.chooseNum(1, 1024) + key <- Gen.chooseNum(0.toByte, 31.toByte) + len <- Gen.chooseNum(1, 1024) } yield KeyLen(key, len) } @@ -37,7 +37,7 @@ class RemoteInstrumentsSpec extends WordSpec with Matchers with Checkers { } "combine and decompose key with 0 multiple times" in { - check { (kl: KeyLen) ⇒ + check { (kl: KeyLen) => val k = kl.k val masked = RemoteInstruments.combineKeyLength(k, 0) @@ -48,7 +48,7 @@ class RemoteInstrumentsSpec extends WordSpec with Matchers with Checkers { } "combine and decompose length with 0 multiple times" in { - check { (kl: KeyLen) ⇒ + check { (kl: KeyLen) => val l = kl.l val masked = RemoteInstruments.combineKeyLength(0, l) @@ -59,7 +59,7 @@ class RemoteInstrumentsSpec extends WordSpec with Matchers with Checkers { } "combine and decompose key and length multiple times" in { - check { (kl: KeyLen) ⇒ + check { (kl: KeyLen) => val k = kl.k val l = kl.l diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteMessageSerializationSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteMessageSerializationSpec.scala index ed6b273dd2..7fdf569afc 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteMessageSerializationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteMessageSerializationSpec.scala @@ -17,8 +17,8 @@ import scala.concurrent.duration._ object RemoteMessageSerializationSpec { class ProxyActor(val one: ActorRef, val another: ActorRef) extends Actor { def receive = { - case s if sender().path == one.path ⇒ another ! s - case s if sender().path == another.path ⇒ one ! s + case s if sender().path == one.path => another ! s + case s if sender().path == another.path => one ! s } } } @@ -82,19 +82,19 @@ class RemoteMessageSerializationSpec extends ArteryMultiNodeSpec(""" } - private def verifySend(msg: Any)(afterSend: ⇒ Unit): Unit = { + private def verifySend(msg: Any)(afterSend: => Unit): Unit = { val bigBounceId = s"bigBounce-${ThreadLocalRandom.current.nextInt()}" val bigBounceOther = remoteSystem.actorOf(Props(new Actor { def receive = { - case x: Int ⇒ sender() ! byteStringOfSize(x) - case x ⇒ sender() ! x + case x: Int => sender() ! byteStringOfSize(x) + case x => sender() ! x } }), bigBounceId) val bigBounceHere = localSystem.actorFor(s"akka://${remoteSystem.name}@localhost:$remotePort/user/$bigBounceId") val eventForwarder = localSystem.actorOf(Props(new Actor { def receive = { - case x ⇒ testActor ! x + case x => testActor ! x } })) localSystem.eventStream.subscribe(eventForwarder, classOf[AssociationErrorEvent]) diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteRouterSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteRouterSpec.scala index 02311a0f19..9fab6b9d96 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteRouterSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteRouterSpec.scala @@ -16,7 +16,7 @@ import akka.remote.{ RARP, RemoteScope } object RemoteRouterSpec { class Parent extends Actor { def receive = { - case (p: Props, name: String) ⇒ + case (p: Props, name: String) => sender() ! context.actorOf(p, name) } } @@ -89,7 +89,7 @@ class RemoteRouterSpec extends AkkaSpec(ConfigFactory.parseString(""" } def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = { - for (i ← 1 to n) yield { + for (i <- 1 to n) yield { val msg = i.toString router.tell(msg, probe.ref) probe.expectMsg(msg) @@ -211,7 +211,7 @@ class RemoteRouterSpec extends AkkaSpec(ConfigFactory.parseString(""" "set supplied supervisorStrategy" in { val probe = TestProbe()(masterSystem) val escalator = OneForOneStrategy() { - case e ⇒ probe.ref ! e; SupervisorStrategy.Escalate + case e => probe.ref ! e; SupervisorStrategy.Escalate } val router = masterSystem.actorOf(new RemoteRouterConfig( RoundRobinPool(1, supervisorStrategy = escalator), diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteSendConsistencySpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteSendConsistencySpec.scala index fa00685c06..0c41c2ce71 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteSendConsistencySpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteSendConsistencySpec.scala @@ -61,7 +61,7 @@ abstract class AbstractRemoteSendConsistencySpec(config: Config) extends ArteryM "be able to identify a remote actor and ping it" in { val actorOnSystemB = systemB.actorOf(Props(new Actor { def receive = { - case "ping" ⇒ sender() ! "pong" + case "ping" => sender() ! "pong" } }), "echo") @@ -131,7 +131,7 @@ abstract class AbstractRemoteSendConsistencySpec(config: Config) extends ArteryM remoteRef ! counter override def receive: Receive = { - case i: Int ⇒ + case i: Int => if (i != counter) testActor ! s"Failed, expected $counter got $i" else if (counter == 0) { testActor ! "success" @@ -170,7 +170,7 @@ abstract class AbstractRemoteSendConsistencySpec(config: Config) extends ArteryM sel ! counter override def receive: Receive = { - case i: Int ⇒ + case i: Int => if (i != counter) testActor ! s"Failed, expected $counter got $i" else if (counter == 0) { testActor ! "success2" diff --git a/akka-remote/src/test/scala/akka/remote/artery/RemoteWatcherSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RemoteWatcherSpec.scala index 0372edd1b4..69a81a4fc1 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RemoteWatcherSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RemoteWatcherSpec.scala @@ -14,7 +14,7 @@ object RemoteWatcherSpec { class TestActorProxy(testActor: ActorRef) extends Actor { def receive = { - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } @@ -34,7 +34,7 @@ object RemoteWatcherSpec { acceptableHeartbeatPause = 3.seconds, firstHeartbeatEstimate = 1.second) - new DefaultFailureDetectorRegistry(() ⇒ createFailureDetector()) + new DefaultFailureDetectorRegistry(() => createFailureDetector()) } object TestRemoteWatcher { diff --git a/akka-remote/src/test/scala/akka/remote/artery/RestartCounterSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RestartCounterSpec.scala index 0ce84abb5a..1f9e70c8a8 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RestartCounterSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RestartCounterSpec.scala @@ -24,7 +24,7 @@ class RestartCounterSpec extends WordSpec with Matchers { "allow sporadic restarts" in { val counter = new RestartCounter(3, 10.millis) - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { counter.restart() should ===(true) Thread.sleep(20) } diff --git a/akka-remote/src/test/scala/akka/remote/artery/RollingEventLogSimulationSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/RollingEventLogSimulationSpec.scala index 019f2a5192..57dfde70f5 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/RollingEventLogSimulationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/RollingEventLogSimulationSpec.scala @@ -145,7 +145,7 @@ class RollingEventLogSimulationSpec extends AkkaSpec { consistencyChecks() } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => println(log.reverse.mkString("\n")) println("----------- BUFFER CONTENT -------------") println(simulatedBuffer.grouped(EntrySize).map(_.mkString("[", ",", "]")).mkString(", ")) @@ -161,7 +161,7 @@ class RollingEventLogSimulationSpec extends AkkaSpec { // No Committed records should contain bytes from two different writes (Dirty records might, though). def checkNoPartialWrites(): Unit = { - for (entry ← 0 until entryCount if simulatedBuffer(entry * EntrySize) == Committed) { + for (entry <- 0 until entryCount if simulatedBuffer(entry * EntrySize) == Committed) { val ofs = entry * EntrySize if (simulatedBuffer(ofs + 2) != simulatedBuffer(ofs + 3)) fail(s"Entry $entry is corrupted, partial writes are visible") @@ -180,13 +180,13 @@ class RollingEventLogSimulationSpec extends AkkaSpec { // [2, 3] // [2, 4] def checkGaplessWrites(): Unit = { - for (id ← 0 until writerCount) { + for (id <- 0 until writerCount) { val writeCount = writers(id).writeCount val lastWrittenSlot = (headPointer - EntrySize) % EntrySize var nextExpected = writeCount val totalWrittenEntries = headPointer % EntrySize - for (i ← 0 until math.min(entryCount, totalWrittenEntries)) { + for (i <- 0 until math.min(entryCount, totalWrittenEntries)) { val slot = (entryCount + lastWrittenSlot - i) % entryCount val offs = slot * EntrySize if (simulatedBuffer(offs) == Committed && simulatedBuffer(offs + 1) == id) { @@ -199,7 +199,7 @@ class RollingEventLogSimulationSpec extends AkkaSpec { } def allRecordsCommitted(): Unit = { - for (entry ← 0 until entryCount) { + for (entry <- 0 until entryCount) { if (simulatedBuffer(entry * EntrySize) != Committed) fail(s"Entry $entry is not Committed") } diff --git a/akka-remote/src/test/scala/akka/remote/artery/SendQueueSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/SendQueueSpec.scala index 6a052782c8..45027e54c6 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/SendQueueSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/SendQueueSpec.scala @@ -31,14 +31,14 @@ object SendQueueSpec { class Producer(producerId: String) extends Actor { def receive = { - case ProduceToQueue(from, until, queue) ⇒ + case ProduceToQueue(from, until, queue) => var i = from while (i < until) { if (!queue.offer(Msg(producerId, i))) throw new IllegalStateException(s"offer failed from $producerId value $i") i += 1 } - case ProduceToQueueValue(from, until, queue) ⇒ + case ProduceToQueueValue(from, until, queue) => var i = from while (i < until) { if (!queue.offer(Msg(producerId, i))) @@ -113,8 +113,8 @@ class SendQueueSpec extends AkkaSpec("akka.actor.serialize-messages = off") with downstream.request(10) sendQueue.inject(queue) - for (round ← 1 to 100000) { - for (n ← 1 to burstSize) { + for (round <- 1 to 100000) { + for (n <- 1 to burstSize) { if (!sendQueue.offer(round * 1000 + n)) fail(s"offer failed at round $round message $n") } @@ -128,7 +128,7 @@ class SendQueueSpec extends AkkaSpec("akka.actor.serialize-messages = off") with "support multiple producers" in { val numberOfProducers = 5 val queue = createQueue[Msg](numberOfProducers * 512) - val producers = Vector.tabulate(numberOfProducers)(i ⇒ system.actorOf(producerProps(s"producer-$i"))) + val producers = Vector.tabulate(numberOfProducers)(i => system.actorOf(producerProps(s"producer-$i"))) // send 100 per producer before materializing producers.foreach(_ ! ProduceToQueue(0, 100, queue)) @@ -142,7 +142,7 @@ class SendQueueSpec extends AkkaSpec("akka.actor.serialize-messages = off") with // send 100 more per producer downstream.request(producers.size * 200) val msgByProducer = downstream.expectNextN(producers.size * 200).groupBy(_.fromProducer) - (0 until producers.size).foreach { i ⇒ + (0 until producers.size).foreach { i => msgByProducer(s"producer-$i").map(_.value) should ===(0 until 200) } @@ -150,7 +150,7 @@ class SendQueueSpec extends AkkaSpec("akka.actor.serialize-messages = off") with downstream.request(producers.size * 1000) // more than enough producers.foreach(_ ! ProduceToQueueValue(200, 700, sendQueue)) val msgByProducer2 = downstream.expectNextN(producers.size * 500).groupBy(_.fromProducer) - (0 until producers.size).foreach { i ⇒ + (0 until producers.size).foreach { i => msgByProducer2(s"producer-$i").map(_.value) should ===(200 until 700) } @@ -159,9 +159,9 @@ class SendQueueSpec extends AkkaSpec("akka.actor.serialize-messages = off") with "deliver first message" in { - def test(f: (Queue[String], SendQueue.QueueValue[String], TestSubscriber.Probe[String]) ⇒ Unit): Unit = { + def test(f: (Queue[String], SendQueue.QueueValue[String], TestSubscriber.Probe[String]) => Unit): Unit = { - (1 to 100).foreach { n ⇒ + (1 to 100).foreach { n => val queue = createQueue[String](16) val (sendQueue, downstream) = Source.fromGraph(new SendQueue[String](sendToDeadLetters)) .toMat(TestSink.probe)(Keep.both).run() @@ -179,39 +179,39 @@ class SendQueueSpec extends AkkaSpec("akka.actor.serialize-messages = off") with } } - test { (queue, sendQueue, downstream) ⇒ + test { (queue, sendQueue, downstream) => queue.offer("a") downstream.request(10) sendQueue.inject(queue) } - test { (queue, sendQueue, downstream) ⇒ + test { (queue, sendQueue, downstream) => sendQueue.inject(queue) queue.offer("a") downstream.request(10) } - test { (queue, sendQueue, downstream) ⇒ + test { (queue, sendQueue, downstream) => queue.offer("a") sendQueue.inject(queue) downstream.request(10) } - test { (queue, sendQueue, downstream) ⇒ + test { (queue, sendQueue, downstream) => downstream.request(10) queue.offer("a") sendQueue.inject(queue) } - test { (queue, sendQueue, downstream) ⇒ + test { (queue, sendQueue, downstream) => sendQueue.inject(queue) downstream.request(10) sendQueue.offer("a") } - test { (queue, sendQueue, downstream) ⇒ + test { (queue, sendQueue, downstream) => downstream.request(10) sendQueue.inject(queue) sendQueue.offer("a") } - test { (queue, sendQueue, downstream) ⇒ + test { (queue, sendQueue, downstream) => sendQueue.inject(queue) sendQueue.offer("a") downstream.request(10) diff --git a/akka-remote/src/test/scala/akka/remote/artery/SystemMessageAckerSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/SystemMessageAckerSpec.scala index 30ef0c6e93..716a8620b3 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/SystemMessageAckerSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/SystemMessageAckerSpec.scala @@ -34,12 +34,12 @@ class SystemMessageAckerSpec extends AkkaSpec with ImplicitSender { val recipient = OptionVal.None // not used TestSource.probe[AnyRef] .map { - case sysMsg @ SystemMessageEnvelope(_, _, ackReplyTo) ⇒ + case sysMsg @ SystemMessageEnvelope(_, _, ackReplyTo) => InboundEnvelope(recipient, sysMsg, OptionVal.None, ackReplyTo.uid, inboundContext.association(ackReplyTo.uid)) } .via(new SystemMessageAcker(inboundContext)) - .map { case env: InboundEnvelope ⇒ env.message } + .map { case env: InboundEnvelope => env.message } .toMat(TestSink.probe[Any])(Keep.both) .run() } diff --git a/akka-remote/src/test/scala/akka/remote/artery/SystemMessageDeliverySpec.scala b/akka-remote/src/test/scala/akka/remote/artery/SystemMessageDeliverySpec.scala index 041af19cd7..c92aa98188 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/SystemMessageDeliverySpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/SystemMessageDeliverySpec.scala @@ -69,15 +69,15 @@ class SystemMessageDeliverySpec extends ArteryMultiNodeSpec(SystemMessageDeliver private def send(sendCount: Int, resendInterval: FiniteDuration, outboundContext: OutboundContext): Source[OutboundEnvelope, NotUsed] = { val deadLetters = TestProbe().ref Source(1 to sendCount) - .map(n ⇒ outboundEnvelopePool.acquire().init(OptionVal.None, TestSysMsg("msg-" + n), OptionVal.None)) + .map(n => outboundEnvelopePool.acquire().init(OptionVal.None, TestSysMsg("msg-" + n), OptionVal.None)) .via(new SystemMessageDelivery(outboundContext, deadLetters, resendInterval, maxBufferSize = 1000)) } private def inbound(inboundContext: InboundContext): Flow[OutboundEnvelope, InboundEnvelope, NotUsed] = { val recipient = OptionVal.None // not used Flow[OutboundEnvelope] - .map(outboundEnvelope ⇒ outboundEnvelope.message match { - case sysEnv: SystemMessageEnvelope ⇒ + .map(outboundEnvelope => outboundEnvelope.message match { + case sysEnv: SystemMessageEnvelope => InboundEnvelope(recipient, sysEnv, OptionVal.None, addressA.uid, inboundContext.association(addressA.uid)) }) @@ -87,26 +87,26 @@ class SystemMessageDeliverySpec extends ArteryMultiNodeSpec(SystemMessageDeliver private def drop(dropSeqNumbers: Vector[Long]): Flow[OutboundEnvelope, OutboundEnvelope, NotUsed] = { Flow[OutboundEnvelope] - .statefulMapConcat(() ⇒ { + .statefulMapConcat(() => { var dropping = dropSeqNumbers { - outboundEnvelope ⇒ + outboundEnvelope => outboundEnvelope.message match { - case SystemMessageEnvelope(_, seqNo, _) ⇒ + case SystemMessageEnvelope(_, seqNo, _) => val i = dropping.indexOf(seqNo) if (i >= 0) { dropping = dropping.updated(i, -1L) Nil } else List(outboundEnvelope) - case _ ⇒ Nil + case _ => Nil } } }) } - private def randomDrop[T](dropRate: Double): Flow[T, T, NotUsed] = Flow[T].mapConcat { elem ⇒ + private def randomDrop[T](dropRate: Double): Flow[T, T, NotUsed] = Flow[T].mapConcat { elem => if (ThreadLocalRandom.current().nextDouble() < dropRate) Nil else List(elem) } @@ -140,8 +140,8 @@ class SystemMessageDeliverySpec extends ArteryMultiNodeSpec(SystemMessageDeliver val idleTimeout = RARP(system).provider.transport.asInstanceOf[ArteryTransport].settings.Advanced.StopIdleOutboundAfter val rnd = ThreadLocalRandom.current() - (1 to 5).foreach { _ ⇒ - (1 to 1).foreach { _ ⇒ + (1 to 5).foreach { _ => + (1 to 1).foreach { _ => watch(remoteRef) unwatch(remoteRef) } @@ -289,7 +289,7 @@ class SystemMessageDeliverySpec extends ArteryMultiNodeSpec(SystemMessageDeliver .map(_.message.asInstanceOf[TestSysMsg]) .runWith(Sink.seq) - Await.result(output, 30.seconds) should ===((1 to N).map(n ⇒ TestSysMsg("msg-" + n)).toVector) + Await.result(output, 30.seconds) should ===((1 to N).map(n => TestSysMsg("msg-" + n)).toVector) } "deliver all during throttling and random dropping" in { @@ -308,7 +308,7 @@ class SystemMessageDeliverySpec extends ArteryMultiNodeSpec(SystemMessageDeliver .map(_.message.asInstanceOf[TestSysMsg]) .runWith(Sink.seq) - Await.result(output, 30.seconds) should ===((1 to N).map(n ⇒ TestSysMsg("msg-" + n)).toVector) + Await.result(output, 30.seconds) should ===((1 to N).map(n => TestSysMsg("msg-" + n)).toVector) } } } diff --git a/akka-remote/src/test/scala/akka/remote/artery/TestContext.scala b/akka-remote/src/test/scala/akka/remote/artery/TestContext.scala index e71f749515..813f37436b 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/TestContext.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/TestContext.scala @@ -36,13 +36,13 @@ private[remote] class TestInboundContext( override def association(remoteAddress: Address): OutboundContext = associationsByAddress.get(remoteAddress) match { - case null ⇒ + case null => val a = createAssociation(remoteAddress) associationsByAddress.putIfAbsent(remoteAddress, a) match { - case null ⇒ a - case existing ⇒ existing + case null => a + case existing => existing } - case existing ⇒ existing + case existing => existing } override def association(uid: Long): OptionVal[OutboundContext] = @@ -51,7 +51,7 @@ private[remote] class TestInboundContext( override def completeHandshake(peer: UniqueAddress): Future[Done] = { val a = association(peer.address).asInstanceOf[TestOutboundContext] val done = a.completeHandshake(peer) - done.foreach { _ ⇒ + done.foreach { _ => associationsByUid.put(peer.uid, a) }(ExecutionContexts.sameThreadExecutionContext) done @@ -80,8 +80,8 @@ private[remote] class TestOutboundContext( def completeHandshake(peer: UniqueAddress): Future[Done] = synchronized { _associationState.uniqueRemoteAddressPromise.trySuccess(peer) _associationState.uniqueRemoteAddress.value match { - case Some(Success(`peer`)) ⇒ // our value - case _ ⇒ + case Some(Success(`peer`)) => // our value + case _ => _associationState = _associationState.newIncarnation(Promise.successful(peer)) } Future.successful(Done) @@ -138,7 +138,7 @@ private[remote] class ManualReplyInboundContext( } def deliverLastReply(): Unit = synchronized { - lastReply.foreach { case (to, message) ⇒ super.sendControl(to, message) } + lastReply.foreach { case (to, message) => super.sendControl(to, message) } lastReply = None } } diff --git a/akka-remote/src/test/scala/akka/remote/artery/UntrustedSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/UntrustedSpec.scala index 1027c1464f..500a7a8124 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/UntrustedSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/UntrustedSpec.scala @@ -34,9 +34,9 @@ object UntrustedSpec { context.actorOf(Props(classOf[FakeUser], testActor), "user") def receive = { - case IdentifyReq(path) ⇒ context.actorSelection(path).tell(Identify(None), sender()) - case StopChild(name) ⇒ context.child(name) foreach context.stop - case msg ⇒ testActor forward msg + case IdentifyReq(path) => context.actorSelection(path).tell(Identify(None), sender()) + case StopChild(name) => context.child(name) foreach context.stop + case msg => testActor forward msg } } @@ -45,14 +45,14 @@ object UntrustedSpec { testActor ! s"${self.path.name} stopped" } def receive = { - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } class FakeUser(testActor: ActorRef) extends Actor { context.actorOf(Props(classOf[Child], testActor), "receptionist") def receive = { - case msg ⇒ testActor forward msg + case msg => testActor forward msg } } @@ -107,8 +107,8 @@ class UntrustedSpec extends ArteryMultiNodeSpec(UntrustedSpec.config) with Impli system.eventStream.subscribe(system.actorOf(Props(new Actor { import Logging._ def receive = { - case d @ Debug(_, _, msg: String) if msg contains "dropping" ⇒ logProbe.ref ! d - case _ ⇒ + case d @ Debug(_, _, msg: String) if msg contains "dropping" => logProbe.ref ! d + case _ => } }).withDeploy(Deploy.local), "debugSniffer"), classOf[Logging.Debug]) @@ -128,7 +128,7 @@ class UntrustedSpec extends ArteryMultiNodeSpec(UntrustedSpec.config) with Impli client.actorOf(Props(new Actor { context.watch(target2) def receive = { - case x ⇒ testActor forward x + case x => testActor forward x } }).withDeploy(Deploy.local)) receptionist ! StopChild("child2") diff --git a/akka-remote/src/test/scala/akka/remote/artery/aeron/AeronSinkSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/aeron/AeronSinkSpec.scala index a2a0a55b22..f0ec93bbb2 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/aeron/AeronSinkSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/aeron/AeronSinkSpec.scala @@ -62,13 +62,13 @@ class AeronSinkSpec extends AkkaSpec with ImplicitSender { Source.fromGraph(new AeronSource(channel, 1, aeron, taskRunner, pool, IgnoreEventSink, 0)) // fail receiver stream on first message - .map(_ ⇒ throw new RuntimeException("stop") with NoStackTrace) + .map(_ => throw new RuntimeException("stop") with NoStackTrace) .runWith(Sink.ignore) // use large enough messages to fill up buffers val payload = new Array[Byte](100000) - val done = Source(1 to 1000).map(_ ⇒ payload) - .map { n ⇒ + val done = Source(1 to 1000).map(_ => payload) + .map { n => val envelope = pool.acquire() envelope.byteBuffer.put(payload) envelope.byteBuffer.flip() diff --git a/akka-remote/src/test/scala/akka/remote/artery/compress/CompressionIntegrationSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/compress/CompressionIntegrationSpec.scala index 6c58c1ba32..f521a7ea30 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/compress/CompressionIntegrationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/compress/CompressionIntegrationSpec.scala @@ -65,7 +65,7 @@ class CompressionIntegrationSpec extends ArteryMultiNodeSpec(CompressionIntegrat // cause TestMessage manifest to become a heavy hitter // cause echo to become a heavy hitter - (1 to messagesToExchange).foreach { i ⇒ echoRefA ! TestMessage("hello") } + (1 to messagesToExchange).foreach { i => echoRefA ! TestMessage("hello") } receiveN(messagesToExchange) // the replies within(10.seconds) { @@ -218,7 +218,7 @@ class CompressionIntegrationSpec extends ArteryMultiNodeSpec(CompressionIntegrat val echoRefA = expectMsgType[ActorIdentity].ref.get // cause TestMessage manifest to become a heavy hitter - (1 to messagesToExchange).foreach { i ⇒ echoRefA ! TestMessage("hello") } + (1 to messagesToExchange).foreach { i => echoRefA ! TestMessage("hello") } receiveN(messagesToExchange) // the replies within(10.seconds) { @@ -295,7 +295,7 @@ class CompressionIntegrationSpec extends ArteryMultiNodeSpec(CompressionIntegrat allRefs ::= echoWrap // cause echo to become a heavy hitter - (1 to messagesToExchange).foreach { i ⇒ echoWrap ! TestMessage("hello") } + (1 to messagesToExchange).foreach { i => echoWrap ! TestMessage("hello") } receiveN(messagesToExchange) // the replies var currentTable: CompressionTable[ActorRef] = null @@ -317,9 +317,9 @@ class CompressionIntegrationSpec extends ArteryMultiNodeSpec(CompressionIntegrat (((currentTable.version - lastTable.version) & 127) <= 2) should be(true) def removeFirst(l: List[Int], it: Int): List[Int] = l match { - case Nil ⇒ Nil - case `it` :: tail ⇒ tail - case other :: tail ⇒ other :: removeFirst(tail, it) + case Nil => Nil + case `it` :: tail => tail + case other :: tail => other :: removeFirst(tail, it) } remainingExpectedTableVersions = removeFirst(remainingExpectedTableVersions, lastTable.version) @@ -342,17 +342,17 @@ class TestMessageSerializer(val system: ExtendedActorSystem) extends SerializerW override def manifest(o: AnyRef): String = o match { - case _: TestMessage ⇒ TestMessageManifest + case _: TestMessage => TestMessageManifest } override def toBinary(o: AnyRef): Array[Byte] = o match { - case msg: TestMessage ⇒ msg.name.getBytes + case msg: TestMessage => msg.name.getBytes } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { manifest match { - case TestMessageManifest ⇒ TestMessage(new String(bytes)) - case unknown ⇒ throw new Exception("Unknown manifest: " + unknown) + case TestMessageManifest => TestMessage(new String(bytes)) + case unknown => throw new Exception("Unknown manifest: " + unknown) } } } diff --git a/akka-remote/src/test/scala/akka/remote/artery/compress/CompressionTableSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/compress/CompressionTableSpec.scala index 7c14fc0e0d..4bc50f1ee7 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/compress/CompressionTableSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/compress/CompressionTableSpec.scala @@ -10,14 +10,14 @@ class CompressionTableSpec extends AkkaSpec { "CompressionTable" must { "should invert" in { - val decomp = CompressionTable(17L, 1, Map("0" → 0, "1" → 1, "2" → 2, "3" → 3)).invert + val decomp = CompressionTable(17L, 1, Map("0" -> 0, "1" -> 1, "2" -> 2, "3" -> 3)).invert decomp.table should ===(Array("0", "1", "2", "3")) decomp.originUid should ===(17L) decomp.version should ===(1.toByte) } "enforce to start allocating from 0th index" in { - val compressionTable = CompressionTable(17L, 1, Map("1" → 1, "3" → 3)) // missing 0 is a gap too + val compressionTable = CompressionTable(17L, 1, Map("1" -> 1, "3" -> 3)) // missing 0 is a gap too val ex = intercept[IllegalArgumentException] { compressionTable.invert @@ -26,7 +26,7 @@ class CompressionTableSpec extends AkkaSpec { } "should not allow having gaps in compression ids (inversion would fail)" in { - val compressionTable = CompressionTable(17L, 1, Map("0" → 0, "1" → 1, "3" → 3)) // missing 0 is a gap too + val compressionTable = CompressionTable(17L, 1, Map("0" -> 0, "1" -> 1, "3" -> 3)) // missing 0 is a gap too val ex = intercept[IllegalArgumentException] { compressionTable.invert diff --git a/akka-remote/src/test/scala/akka/remote/artery/compress/HandshakeShouldDropCompressionTableSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/compress/HandshakeShouldDropCompressionTableSpec.scala index b9eea4e13d..416d279534 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/compress/HandshakeShouldDropCompressionTableSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/compress/HandshakeShouldDropCompressionTableSpec.scala @@ -64,7 +64,7 @@ class HandshakeShouldDropCompressionTableSpec extends ArteryMultiNodeSpec(Handsh systemB.actorOf(TestActors.echoActorProps, "echo") // cause testActor-1 to become a heavy hitter - (1 to messagesToExchange).foreach { i ⇒ echoSel ! s"hello-$i" } // does not reply, but a hot receiver should be advertised + (1 to messagesToExchange).foreach { i => echoSel ! s"hello-$i" } // does not reply, but a hot receiver should be advertised waitForEcho(this, s"hello-$messagesToExchange") systemBTransport.triggerCompressionAdvertisements(actorRef = true, manifest = false) @@ -73,7 +73,7 @@ class HandshakeShouldDropCompressionTableSpec extends ArteryMultiNodeSpec(Handsh a0.table.dictionary.keySet should contain(testActor) // cause a1Probe to become a heavy hitter (we want to not have it in the 2nd compression table later) - (1 to messagesToExchange).foreach { i ⇒ echoSel.tell(s"hello-$i", a1Probe.ref) } + (1 to messagesToExchange).foreach { i => echoSel.tell(s"hello-$i", a1Probe.ref) } waitForEcho(a1Probe, s"hello-$messagesToExchange") systemBTransport.triggerCompressionAdvertisements(actorRef = true, manifest = false) @@ -93,9 +93,9 @@ class HandshakeShouldDropCompressionTableSpec extends ArteryMultiNodeSpec(Handsh system.eventStream.subscribe(aNewProbe.ref, classOf[Event]) systemB.actorOf(TestActors.echoActorProps, "echo") // start it again - (1 to 5) foreach { _ ⇒ + (1 to 5) foreach { _ => // since some messages may end up being lost - (1 to messagesToExchange).foreach { i ⇒ echoSel ! s"hello-$i" } // does not reply, but a hot receiver should be advertised + (1 to messagesToExchange).foreach { i => echoSel ! s"hello-$i" } // does not reply, but a hot receiver should be advertised Thread.sleep(100) } waitForEcho(this, s"hello-$messagesToExchange", max = 10.seconds) @@ -106,7 +106,7 @@ class HandshakeShouldDropCompressionTableSpec extends ArteryMultiNodeSpec(Handsh a2.table.dictionary.keySet should contain(testActor) val aNew2Probe = TestProbe() - (1 to messagesToExchange).foreach { i ⇒ echoSel.tell(s"hello-$i", aNew2Probe.ref) } // does not reply, but a hot receiver should be advertised + (1 to messagesToExchange).foreach { i => echoSel.tell(s"hello-$i", aNew2Probe.ref) } // does not reply, but a hot receiver should be advertised waitForEcho(aNew2Probe, s"hello-$messagesToExchange") systemBTransport.triggerCompressionAdvertisements(actorRef = true, manifest = false) @@ -118,8 +118,8 @@ class HandshakeShouldDropCompressionTableSpec extends ArteryMultiNodeSpec(Handsh def waitForEcho(probe: TestKit, m: String, max: Duration = 3.seconds): Any = probe.fishForMessage(max = max, hint = s"waiting for '$m'") { - case `m` ⇒ true - case x ⇒ false + case `m` => true + case x => false } def identify(_system: String, port: Int, name: String) = { diff --git a/akka-remote/src/test/scala/akka/remote/artery/compress/OutboundCompressionSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/compress/OutboundCompressionSpec.scala index 25a5ddf66c..6a44842b66 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/compress/OutboundCompressionSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/compress/OutboundCompressionSpec.scala @@ -20,7 +20,7 @@ class OutboundCompressionSpec extends AkkaSpec { } "compress previously registered actor ref" in { - val table = CompressionTable(17L, 1, Map(system.deadLetters → 0, alice → 1)) + val table = CompressionTable(17L, 1, Map(system.deadLetters -> 0, alice -> 1)) table.compress(alice) should ===(1) // compressed table.compress(bob) should ===(-1) // not compressed diff --git a/akka-remote/src/test/scala/akka/remote/artery/tcp/TcpFramingSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/tcp/TcpFramingSpec.scala index 21fab1db81..253b24fcfe 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/tcp/TcpFramingSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/tcp/TcpFramingSpec.scala @@ -32,7 +32,7 @@ class TcpFramingSpec extends AkkaSpec with ImplicitSender { private val payload5 = ByteString((1 to 5).map(_.toByte).toArray) private def frameBytes(numberOfFrames: Int): ByteString = - (1 to numberOfFrames).foldLeft(ByteString.empty)((acc, _) ⇒ acc ++ encodeFrameHeader(payload5.size) ++ payload5) + (1 to numberOfFrames).foldLeft(ByteString.empty)((acc, _) => acc ++ encodeFrameHeader(payload5.size) ++ payload5) private val rndSeed = System.currentTimeMillis() private val rnd = new Random(rndSeed) @@ -85,9 +85,9 @@ class TcpFramingSpec extends AkkaSpec with ImplicitSender { val numberOfFrames = 100 val bytes = TcpFraming.encodeConnectionHeader(3) ++ frameBytes(numberOfFrames) withClue(s"Random chunks seed: $rndSeed") { - val frames = Source.fromIterator(() ⇒ rechunk(bytes)).via(framingFlow).runWith(Sink.seq).futureValue + val frames = Source.fromIterator(() => rechunk(bytes)).via(framingFlow).runWith(Sink.seq).futureValue frames.size should ===(numberOfFrames) - frames.foreach { frame ⇒ + frames.foreach { frame => frame.byteBuffer.limit() should ===(payload5.size) val payload = new Array[Byte](frame.byteBuffer.limit()) frame.byteBuffer.get(payload) diff --git a/akka-remote/src/test/scala/akka/remote/artery/tcp/TlsTcpSpec.scala b/akka-remote/src/test/scala/akka/remote/artery/tcp/TlsTcpSpec.scala index bd6a026db6..86a8b985a7 100644 --- a/akka-remote/src/test/scala/akka/remote/artery/tcp/TlsTcpSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/artery/tcp/TlsTcpSpec.scala @@ -90,7 +90,7 @@ abstract class TlsTcpSpec(config: Config) engine.getSupportedProtocols.contains(provider.SSLProtocol) || (throw new IllegalArgumentException("Protocol not supported: " + provider.SSLProtocol)) } catch { - case e @ (_: IllegalArgumentException | _: NoSuchAlgorithmException) ⇒ + case e @ (_: IllegalArgumentException | _: NoSuchAlgorithmException) => info(e.toString) false } @@ -106,10 +106,10 @@ abstract class TlsTcpSpec(config: Config) expectMsg("ping-1") // and some more - (2 to 10).foreach { n ⇒ + (2 to 10).foreach { n => echoRef ! s"ping-$n" } - receiveN(9) should equal((2 to 10).map(n ⇒ s"ping-$n")) + receiveN(9) should equal((2 to 10).map(n => s"ping-$n")) } "Artery with TLS/TCP" must { @@ -124,7 +124,7 @@ abstract class TlsTcpSpec(config: Config) // https://doc.akka.io/docs/akka/current/security/2018-08-29-aes-rng.html // awaitAssert just in case we are very unlucky to get same sequence more than once awaitAssert { - val randomBytes = (1 to 10).map { n ⇒ + val randomBytes = (1 to 10).map { n => rng.nextBytes(bytes) bytes.toVector }.toSet @@ -202,7 +202,7 @@ class TlsTcpWithActorSystemSetupSpec val sslProviderServerProbe = TestProbe() val sslProviderClientProbe = TestProbe() - val sslProviderSetup = SSLEngineProviderSetup(sys ⇒ new ConfigSSLEngineProvider(sys) { + val sslProviderSetup = SSLEngineProviderSetup(sys => new ConfigSSLEngineProvider(sys) { override def createServerSSLEngine(hostname: String, port: Int): SSLEngine = { sslProviderServerProbe.ref ! "createServerSSLEngine" super.createServerSSLEngine(hostname, port) diff --git a/akka-remote/src/test/scala/akka/remote/serialization/AllowJavaSerializationOffSpec.scala b/akka-remote/src/test/scala/akka/remote/serialization/AllowJavaSerializationOffSpec.scala index b1dae04d2e..eb12aaff5a 100644 --- a/akka-remote/src/test/scala/akka/remote/serialization/AllowJavaSerializationOffSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/serialization/AllowJavaSerializationOffSpec.scala @@ -11,8 +11,8 @@ import akka.testkit.{ AkkaSpec, TestKit, TestProbe } import com.typesafe.config.ConfigFactory import scala.concurrent.duration._ import akka.actor.actorRef2Scala -import java.util.{ BitSet ⇒ ProgrammaticJavaDummy } -import java.util.{ Date ⇒ SerializableDummy } +import java.util.{ BitSet => ProgrammaticJavaDummy } +import java.util.{ Date => SerializableDummy } class ConfigurationDummy class ProgrammaticDummy @@ -21,7 +21,7 @@ object AllowJavaSerializationOffSpec { val dummySerializer = new FakeSerializer - val serializationSettings = SerializationSetup { _ ⇒ + val serializationSettings = SerializationSetup { _ => List( SerializerDetails("test", dummySerializer, List(classOf[ProgrammaticDummy]))) } @@ -63,7 +63,7 @@ class AllowJavaSerializationOffSpec extends AkkaSpec( // that they'd need a different actor system to be able to create it... someone MAY pick a system with // allow-java-serialization=on to create the SerializationSetup and use that SerializationSetup // in another system with allow-java-serialization=off - val addedJavaSerializationSettings = SerializationSetup { _ ⇒ + val addedJavaSerializationSettings = SerializationSetup { _ => List( SerializerDetails("test", dummySerializer, List(classOf[ProgrammaticDummy])), SerializerDetails("java-manual", new JavaSerializer(system.asInstanceOf[ExtendedActorSystem]), List(classOf[ProgrammaticJavaDummy]))) diff --git a/akka-remote/src/test/scala/akka/remote/serialization/ArteryMessageSerializerSpec.scala b/akka-remote/src/test/scala/akka/remote/serialization/ArteryMessageSerializerSpec.scala index 470a5a504c..6ce5e9831b 100644 --- a/akka-remote/src/test/scala/akka/remote/serialization/ArteryMessageSerializerSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/serialization/ArteryMessageSerializerSpec.scala @@ -21,22 +21,22 @@ class ArteryMessageSerializerSpec extends AkkaSpec { val actorB = system.actorOf(Props.empty) Seq( - "Quarantined" → Quarantined(uniqueAddress(), uniqueAddress()), - "ActorSystemTerminating" → ActorSystemTerminating(uniqueAddress()), - "ActorSystemTerminatingAck" → ActorSystemTerminatingAck(uniqueAddress()), - "HandshakeReq" → HandshakeReq(uniqueAddress(), uniqueAddress().address), - "HandshakeRsp" → HandshakeRsp(uniqueAddress()), - "ActorRefCompressionAdvertisement" → ActorRefCompressionAdvertisement(uniqueAddress(), CompressionTable(17L, 123, Map(actorA → 123, actorB → 456, system.deadLetters → 0))), - "ActorRefCompressionAdvertisementAck" → ActorRefCompressionAdvertisementAck(uniqueAddress(), 23), - "ClassManifestCompressionAdvertisement" → ClassManifestCompressionAdvertisement(uniqueAddress(), CompressionTable(17L, 42, Map("a" → 535, "b" → 23))), - "ClassManifestCompressionAdvertisementAck" → ClassManifestCompressionAdvertisementAck(uniqueAddress(), 23), - "SystemMessageDelivery.SystemMessageEnvelop" → SystemMessageDelivery.SystemMessageEnvelope("test", 1234567890123L, uniqueAddress()), - "SystemMessageDelivery.Ack" → SystemMessageDelivery.Ack(98765432109876L, uniqueAddress()), - "SystemMessageDelivery.Nack" → SystemMessageDelivery.Nack(98765432109876L, uniqueAddress()), - "RemoteWatcher.ArteryHeartbeat" → RemoteWatcher.ArteryHeartbeat, - "RemoteWatcher.ArteryHeartbeatRsp" → RemoteWatcher.ArteryHeartbeatRsp(Long.MaxValue) + "Quarantined" -> Quarantined(uniqueAddress(), uniqueAddress()), + "ActorSystemTerminating" -> ActorSystemTerminating(uniqueAddress()), + "ActorSystemTerminatingAck" -> ActorSystemTerminatingAck(uniqueAddress()), + "HandshakeReq" -> HandshakeReq(uniqueAddress(), uniqueAddress().address), + "HandshakeRsp" -> HandshakeRsp(uniqueAddress()), + "ActorRefCompressionAdvertisement" -> ActorRefCompressionAdvertisement(uniqueAddress(), CompressionTable(17L, 123, Map(actorA -> 123, actorB -> 456, system.deadLetters -> 0))), + "ActorRefCompressionAdvertisementAck" -> ActorRefCompressionAdvertisementAck(uniqueAddress(), 23), + "ClassManifestCompressionAdvertisement" -> ClassManifestCompressionAdvertisement(uniqueAddress(), CompressionTable(17L, 42, Map("a" -> 535, "b" -> 23))), + "ClassManifestCompressionAdvertisementAck" -> ClassManifestCompressionAdvertisementAck(uniqueAddress(), 23), + "SystemMessageDelivery.SystemMessageEnvelop" -> SystemMessageDelivery.SystemMessageEnvelope("test", 1234567890123L, uniqueAddress()), + "SystemMessageDelivery.Ack" -> SystemMessageDelivery.Ack(98765432109876L, uniqueAddress()), + "SystemMessageDelivery.Nack" -> SystemMessageDelivery.Nack(98765432109876L, uniqueAddress()), + "RemoteWatcher.ArteryHeartbeat" -> RemoteWatcher.ArteryHeartbeat, + "RemoteWatcher.ArteryHeartbeatRsp" -> RemoteWatcher.ArteryHeartbeatRsp(Long.MaxValue) ).foreach { - case (scenario, item) ⇒ + case (scenario, item) => s"resolve serializer for $scenario" in { val serializer = SerializationExtension(system) serializer.serializerFor(item.getClass).getClass should ===(classOf[ArteryMessageSerializer]) diff --git a/akka-remote/src/test/scala/akka/remote/serialization/DaemonMsgCreateSerializerSpec.scala b/akka-remote/src/test/scala/akka/remote/serialization/DaemonMsgCreateSerializerSpec.scala index 06d166349b..15f4c2d432 100644 --- a/akka-remote/src/test/scala/akka/remote/serialization/DaemonMsgCreateSerializerSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/serialization/DaemonMsgCreateSerializerSpec.scala @@ -28,7 +28,7 @@ object DaemonMsgCreateSerializerSpec { case class DummyParameter(val inner: String) extends Serializable -trait SerializationVerification { self: AkkaSpec ⇒ +trait SerializationVerification { self: AkkaSpec => def ser: Serialization @@ -41,7 +41,7 @@ trait SerializationVerification { self: AkkaSpec ⇒ got.props.clazz should ===(expected.props.clazz) got.props.args.length should ===(expected.props.args.length) got.props.args zip expected.props.args foreach { - case (g, e) ⇒ + case (g, e) => if (e.isInstanceOf[Function0[_]]) () else if (e.isInstanceOf[Function1[_, _]]) () else g should ===(e) @@ -98,7 +98,7 @@ class DaemonMsgCreateSerializerSpec extends AkkaSpec with SerializationVerificat "serialize and de-serialize DaemonMsgCreate with FromClassCreator, with function parameters for Props" in { verifySerialization { DaemonMsgCreate( - props = Props(classOf[MyActorWithFunParam], (i: Int) ⇒ i + 1), + props = Props(classOf[MyActorWithFunParam], (i: Int) => i + 1), deploy = Deploy(), path = "foo", supervisor = supervisor) @@ -141,7 +141,7 @@ class DaemonMsgCreateSerializerSpec extends AkkaSpec with SerializationVerificat val result = serializer.fromBinary(oldBytes, classOf[DaemonMsgCreate]) result match { - case dmc: DaemonMsgCreate ⇒ + case dmc: DaemonMsgCreate => dmc.props.args should ===(Seq("a string": Any)) } } finally { @@ -204,7 +204,7 @@ class DaemonMsgCreateSerializerNoJavaSerializationSpec extends AkkaSpec( verifySerialization { // Duration.Inf doesn't equal Duration.Inf, so we use another for test val supervisorStrategy = OneForOneStrategy(3, 10 seconds) { - case _ ⇒ SupervisorStrategy.Escalate + case _ => SupervisorStrategy.Escalate } val deploy1 = Deploy( diff --git a/akka-remote/src/test/scala/akka/remote/serialization/MiscMessageSerializerSpec.scala b/akka-remote/src/test/scala/akka/remote/serialization/MiscMessageSerializerSpec.scala index c923587bda..595abffc70 100644 --- a/akka-remote/src/test/scala/akka/remote/serialization/MiscMessageSerializerSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/serialization/MiscMessageSerializerSpec.scala @@ -33,14 +33,14 @@ object MiscMessageSerializerSpec { def this(msg: String) = this(msg, null) override def equals(other: Any): Boolean = other match { - case e: TestException ⇒ + case e: TestException => e.getMessage == getMessage && e.getCause == getCause && // on JDK9+ the stacktraces aren't equal, something about how they are constructed // they are alike enough to be roughly equal though e.stackTrace.zip(stackTrace).forall { - case (t, o) ⇒ t.getClassName == o.getClassName && t.getFileName == o.getFileName + case (t, o) => t.getClassName == o.getClassName && t.getFileName == o.getFileName } - case _ ⇒ false + case _ => false } def stackTrace: List[StackTraceElement] = @@ -50,16 +50,16 @@ object MiscMessageSerializerSpec { class TestExceptionNoStack(msg: String) extends TestException(msg) with NoStackTrace { override def equals(other: Any): Boolean = other match { - case e: TestExceptionNoStack ⇒ + case e: TestExceptionNoStack => e.getMessage == getMessage && e.stackTrace == stackTrace - case _ ⇒ false + case _ => false } } class OtherException(msg: String) extends IllegalArgumentException(msg) { override def equals(other: Any): Boolean = other match { - case e: OtherException ⇒ e.getMessage == getMessage - case _ ⇒ false + case e: OtherException => e.getMessage == getMessage + case _ => false } } } @@ -71,49 +71,49 @@ class MiscMessageSerializerSpec extends AkkaSpec(MiscMessageSerializerSpec.testC "MiscMessageSerializer" must { Seq( - "Identify" → Identify("some-message"), - "Identify with None" → Identify(None), - "Identify with Some" → Identify(Some("value")), - "ActorIdentity without actor ref" → ActorIdentity("some-message", ref = None), - "ActorIdentity with actor ref" → ActorIdentity("some-message", ref = Some(testActor)), - "TestException" → new TestException("err"), - "TestExceptionNoStack" → new TestExceptionNoStack("err2"), - "TestException with cause" → new TestException("err3", new TestException("cause")), - "Status.Success" → Status.Success("value"), - "Status.Failure" → Status.Failure(new TestException("err")), - "Status.Failure JavaSer" → Status.Failure(new OtherException("exc")), // exc with JavaSerializer - "ActorRef" → ref, - "Some" → Some("value"), - "None" → None, - "Optional.present" → Optional.of("value2"), - "Optional.empty" → Optional.empty(), - "Kill" → Kill, - "PoisonPill" → PoisonPill, - "RemoteWatcher.Heartbeat" → RemoteWatcher.Heartbeat, - "RemoteWatcher.HertbeatRsp" → RemoteWatcher.HeartbeatRsp(65537), - "Done" → Done, - "NotUsed" → NotUsed, - "Address" → Address("akka", "system", "host", 1337), - "UniqueAddress" → akka.remote.UniqueAddress(Address("akka", "system", "host", 1337), 82751), - "LocalScope" → LocalScope, - "RemoteScope" → RemoteScope(Address("akka", "system", "localhost", 2525)), - "Config" → system.settings.config, - "Empty Config" → ConfigFactory.empty(), - "FromConfig" → FromConfig, + "Identify" -> Identify("some-message"), + "Identify with None" -> Identify(None), + "Identify with Some" -> Identify(Some("value")), + "ActorIdentity without actor ref" -> ActorIdentity("some-message", ref = None), + "ActorIdentity with actor ref" -> ActorIdentity("some-message", ref = Some(testActor)), + "TestException" -> new TestException("err"), + "TestExceptionNoStack" -> new TestExceptionNoStack("err2"), + "TestException with cause" -> new TestException("err3", new TestException("cause")), + "Status.Success" -> Status.Success("value"), + "Status.Failure" -> Status.Failure(new TestException("err")), + "Status.Failure JavaSer" -> Status.Failure(new OtherException("exc")), // exc with JavaSerializer + "ActorRef" -> ref, + "Some" -> Some("value"), + "None" -> None, + "Optional.present" -> Optional.of("value2"), + "Optional.empty" -> Optional.empty(), + "Kill" -> Kill, + "PoisonPill" -> PoisonPill, + "RemoteWatcher.Heartbeat" -> RemoteWatcher.Heartbeat, + "RemoteWatcher.HertbeatRsp" -> RemoteWatcher.HeartbeatRsp(65537), + "Done" -> Done, + "NotUsed" -> NotUsed, + "Address" -> Address("akka", "system", "host", 1337), + "UniqueAddress" -> akka.remote.UniqueAddress(Address("akka", "system", "host", 1337), 82751), + "LocalScope" -> LocalScope, + "RemoteScope" -> RemoteScope(Address("akka", "system", "localhost", 2525)), + "Config" -> system.settings.config, + "Empty Config" -> ConfigFactory.empty(), + "FromConfig" -> FromConfig, // routers - "DefaultResizer" → DefaultResizer(), - "BalancingPool" → BalancingPool(nrOfInstances = 25), - "BalancingPool with custom dispatcher" → BalancingPool(nrOfInstances = 25, routerDispatcher = "my-dispatcher"), - "BroadcastPool" → BroadcastPool(nrOfInstances = 25), - "BroadcastPool with custom dispatcher and resizer" → BroadcastPool(nrOfInstances = 25, routerDispatcher = "my-dispatcher", usePoolDispatcher = true, resizer = Some(DefaultResizer())), - "RandomPool" → RandomPool(nrOfInstances = 25), - "RandomPool with custom dispatcher" → RandomPool(nrOfInstances = 25, routerDispatcher = "my-dispatcher"), - "RoundRobinPool" → RoundRobinPool(25), - "ScatterGatherFirstCompletedPool" → ScatterGatherFirstCompletedPool(25, within = 3.seconds), - "TailChoppingPool" → TailChoppingPool(25, within = 3.seconds, interval = 1.second), - "RemoteRouterConfig" → RemoteRouterConfig(local = RandomPool(25), nodes = List(Address("akka", "system", "localhost", 2525))) + "DefaultResizer" -> DefaultResizer(), + "BalancingPool" -> BalancingPool(nrOfInstances = 25), + "BalancingPool with custom dispatcher" -> BalancingPool(nrOfInstances = 25, routerDispatcher = "my-dispatcher"), + "BroadcastPool" -> BroadcastPool(nrOfInstances = 25), + "BroadcastPool with custom dispatcher and resizer" -> BroadcastPool(nrOfInstances = 25, routerDispatcher = "my-dispatcher", usePoolDispatcher = true, resizer = Some(DefaultResizer())), + "RandomPool" -> RandomPool(nrOfInstances = 25), + "RandomPool with custom dispatcher" -> RandomPool(nrOfInstances = 25, routerDispatcher = "my-dispatcher"), + "RoundRobinPool" -> RoundRobinPool(25), + "ScatterGatherFirstCompletedPool" -> ScatterGatherFirstCompletedPool(25, within = 3.seconds), + "TailChoppingPool" -> TailChoppingPool(25, within = 3.seconds, interval = 1.second), + "RemoteRouterConfig" -> RemoteRouterConfig(local = RandomPool(25), nodes = List(Address("akka", "system", "localhost", 2525))) ).foreach { - case (scenario, item) ⇒ + case (scenario, item) => s"resolve serializer for $scenario" in { val serializer = SerializationExtension(system) serializer.serializerFor(item.getClass).getClass should ===(classOf[MiscMessageSerializer]) diff --git a/akka-remote/src/test/scala/akka/remote/serialization/PrimitivesSerializationSpec.scala b/akka-remote/src/test/scala/akka/remote/serialization/PrimitivesSerializationSpec.scala index 6eb2b6e22b..c0863431e9 100644 --- a/akka-remote/src/test/scala/akka/remote/serialization/PrimitivesSerializationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/serialization/PrimitivesSerializationSpec.scala @@ -57,7 +57,7 @@ class PrimitivesSerializationSpec extends AkkaSpec(PrimitivesSerializationSpec.t "LongSerializer" must { Seq(0L, 1L, -1L, Long.MinValue, Long.MinValue + 1L, Long.MaxValue, Long.MaxValue - 1L).map(_.asInstanceOf[AnyRef]).foreach { - item ⇒ + item => s"resolve serializer for value $item" in { val serializer = SerializationExtension(system) serializer.serializerFor(item.getClass).getClass should ===(classOf[LongSerializer]) @@ -76,7 +76,7 @@ class PrimitivesSerializationSpec extends AkkaSpec(PrimitivesSerializationSpec.t "IntSerializer" must { Seq(0, 1, -1, Int.MinValue, Int.MinValue + 1, Int.MaxValue, Int.MaxValue - 1).map(_.asInstanceOf[AnyRef]).foreach { - item ⇒ + item => s"resolve serializer for value $item" in { val serializer = SerializationExtension(system) serializer.serializerFor(item.getClass).getClass should ===(classOf[IntSerializer]) @@ -95,11 +95,11 @@ class PrimitivesSerializationSpec extends AkkaSpec(PrimitivesSerializationSpec.t "StringSerializer" must { val random = Random.nextString(256) Seq( - "empty string" → "", - "hello" → "hello", - "árvíztűrőütvefúrógép" → "árvíztűrőütvefúrógép", - "random" → random).foreach { - case (scenario, item) ⇒ + "empty string" -> "", + "hello" -> "hello", + "árvíztűrőütvefúrógép" -> "árvíztűrőütvefúrógép", + "random" -> random).foreach { + case (scenario, item) => s"resolve serializer for [$scenario]" in { val serializer = SerializationExtension(system) serializer.serializerFor(item.getClass).getClass should ===(classOf[StringSerializer]) @@ -118,11 +118,11 @@ class PrimitivesSerializationSpec extends AkkaSpec(PrimitivesSerializationSpec.t "ByteStringSerializer" must { Seq( - "empty string" → ByteString.empty, - "simple content" → ByteString("hello"), - "concatenated content" → (ByteString("hello") ++ ByteString("world")), - "sliced content" → ByteString("helloabc").take(5)).foreach { - case (scenario, item) ⇒ + "empty string" -> ByteString.empty, + "simple content" -> ByteString("hello"), + "concatenated content" -> (ByteString("hello") ++ ByteString("world")), + "sliced content" -> ByteString("helloabc").take(5)).foreach { + case (scenario, item) => s"resolve serializer for [$scenario]" in { val serializer = SerializationExtension(system) serializer.serializerFor(item.getClass).getClass should ===(classOf[ByteStringSerializer]) diff --git a/akka-remote/src/test/scala/akka/remote/serialization/SerializationTransportInformationSpec.scala b/akka-remote/src/test/scala/akka/remote/serialization/SerializationTransportInformationSpec.scala index 9e98452557..7940b3d033 100644 --- a/akka-remote/src/test/scala/akka/remote/serialization/SerializationTransportInformationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/serialization/SerializationTransportInformationSpec.scala @@ -29,10 +29,10 @@ object SerializationTransportInformationSpec { class TestSerializer(system: ExtendedActorSystem) extends SerializerWithStringManifest { def identifier: Int = 666 def manifest(o: AnyRef): String = o match { - case _: TestMessage ⇒ "A" + case _: TestMessage => "A" } def toBinary(o: AnyRef): Array[Byte] = o match { - case TestMessage(from, to) ⇒ + case TestMessage(from, to) => verifyTransportInfo() val fromStr = Serialization.serializedActorPath(from) val toStr = Serialization.serializedActorPath(to) @@ -41,7 +41,7 @@ object SerializationTransportInformationSpec { def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { verifyTransportInfo() manifest match { - case "A" ⇒ + case "A" => val parts = new String(bytes, StandardCharsets.UTF_8).split(',') val fromStr = parts(0) val toStr = parts(1) @@ -53,9 +53,9 @@ object SerializationTransportInformationSpec { private def verifyTransportInfo(): Unit = { Serialization.currentTransportInformation.value match { - case null ⇒ + case null => throw new IllegalStateException("currentTransportInformation was not set") - case t ⇒ + case t => if (t.system ne system) throw new IllegalStateException( s"wrong system in currentTransportInformation, ${t.system} != $system") diff --git a/akka-remote/src/test/scala/akka/remote/serialization/SystemMessageSerializationSpec.scala b/akka-remote/src/test/scala/akka/remote/serialization/SystemMessageSerializationSpec.scala index 18ad036ea7..e22eadcd6e 100644 --- a/akka-remote/src/test/scala/akka/remote/serialization/SystemMessageSerializationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/serialization/SystemMessageSerializationSpec.scala @@ -19,8 +19,8 @@ object SystemMessageSerializationSpec { class TestException(msg: String) extends RuntimeException { override def equals(other: Any): Boolean = other match { - case e: TestException ⇒ e.getMessage == getMessage - case _ ⇒ false + case e: TestException => e.getMessage == getMessage + case _ => false } } } @@ -33,18 +33,18 @@ class SystemMessageSerializationSpec extends AkkaSpec(PrimitivesSerializationSpe "ByteStringSerializer" must { Seq( - "Create(None)" → Create(None), - "Recreate(ex)" → Recreate(new TestException("test2")), - "Suspend()" → Suspend(), - "Resume(ex)" → Resume(new TestException("test3")), - "Terminate()" → Terminate(), - "Supervise(ref, async)" → Supervise(testRef, async = true), - "Watch(ref, ref)" → Watch(testRef, testRef2), - "Unwatch(ref, ref)" → Unwatch(testRef, testRef2), - "Failed(ref, ex, uid)" → Failed(testRef, new TestException("test4"), 42), - "DeathWatchNotification(ref, confimed, addressTerminated)" → + "Create(None)" -> Create(None), + "Recreate(ex)" -> Recreate(new TestException("test2")), + "Suspend()" -> Suspend(), + "Resume(ex)" -> Resume(new TestException("test3")), + "Terminate()" -> Terminate(), + "Supervise(ref, async)" -> Supervise(testRef, async = true), + "Watch(ref, ref)" -> Watch(testRef, testRef2), + "Unwatch(ref, ref)" -> Unwatch(testRef, testRef2), + "Failed(ref, ex, uid)" -> Failed(testRef, new TestException("test4"), 42), + "DeathWatchNotification(ref, confimed, addressTerminated)" -> DeathWatchNotification(testRef, existenceConfirmed = true, addressTerminated = true)).foreach { - case (scenario, item) ⇒ + case (scenario, item) => s"resolve serializer for [$scenario]" in { val serializer = SerializationExtension(system) serializer.serializerFor(item.getClass).getClass should ===(classOf[SystemMessageSerializer]) diff --git a/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolSpec.scala b/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolSpec.scala index 04304b1ace..155732dac8 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolSpec.scala @@ -13,7 +13,7 @@ import akka.remote.transport.Transport._ import akka.remote.{ WireFormats, FailureDetector } import akka.testkit.{ ImplicitSender, AkkaSpec } import akka.util.ByteString -import akka.protobuf.{ ByteString ⇒ PByteString } +import akka.protobuf.{ ByteString => PByteString } import com.typesafe.config.ConfigFactory import scala.concurrent.duration._ import scala.concurrent.{ Await, Promise } @@ -93,33 +93,33 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit 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 { - case Heartbeat ⇒ true - case _ ⇒ false + case Heartbeat => true + case _ => false } - case _ ⇒ false + case _ => false } def lastActivityIsAssociate(registry: AssociationRegistry, uid: Long, 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 { - case Associate(info) ⇒ + case Associate(info) => info.cookie == cookie && info.origin == localAddress && info.uid == uid - case _ ⇒ false + case _ => false } - case _ ⇒ false + case _ => false } 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 { - case Disassociate(_) ⇒ true - case _ ⇒ false + case Disassociate(_) => true + case _ => false } - case _ ⇒ false + case _ => false } "ProtocolStateActor" must { @@ -154,7 +154,7 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit awaitCond(failureDetector.called) val wrappedHandle = expectMsgPF() { - case InboundAssociation(h: AkkaProtocolHandle) ⇒ + case InboundAssociation(h: AkkaProtocolHandle) => h.handshakeInfo.uid should ===(33) h } @@ -169,7 +169,7 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit reader ! testPayload expectMsgPF() { - case InboundPayload(p) ⇒ p should ===(testEnvelope) + case InboundPayload(p) => p should ===(testEnvelope) } } @@ -191,8 +191,8 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit reader ! testAssociate(uid = 33, cookie = None) awaitCond(registry.logSnapshot.exists { - case DisassociateAttempt(requester, remote) ⇒ true - case _ ⇒ false + case DisassociateAttempt(requester, remote) => true + case _ => false }) } @@ -224,12 +224,12 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit reader ! testAssociate(33, None) Await.result(statusPromise.future, 3.seconds) match { - case h: AkkaProtocolHandle ⇒ + case h: AkkaProtocolHandle => h.remoteAddress should ===(remoteAkkaAddress) h.localAddress should ===(localAkkaAddress) h.handshakeInfo.uid should ===(33) - case _ ⇒ fail() + case _ => fail() } } @@ -248,8 +248,8 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit reader ! testAssociate(uid = 33, Some("xyzzy")) awaitCond(registry.logSnapshot.exists { - case DisassociateAttempt(requester, remote) ⇒ true - case _ ⇒ false + case DisassociateAttempt(requester, remote) => true + case _ => false }) } @@ -268,7 +268,7 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit reader ! testAssociate(uid = 33, Some("abcde")) val wrappedHandle = expectMsgPF() { - case InboundAssociation(h: AkkaProtocolHandle) ⇒ + case InboundAssociation(h: AkkaProtocolHandle) => h.handshakeInfo.uid should ===(33) h.handshakeInfo.cookie should ===(Some("abcde")) h @@ -322,12 +322,12 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit reader ! testAssociate(uid = 33, cookie = None) val wrappedHandle = Await.result(statusPromise.future, 3.seconds) match { - case h: AssociationHandle ⇒ + case h: AssociationHandle => h.remoteAddress should ===(remoteAkkaAddress) h.localAddress should ===(localAkkaAddress) h - case _ ⇒ fail() + case _ => fail() } wrappedHandle.readHandlerPromise.success(ActorHandleEventListener(testActor)) @@ -358,12 +358,12 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit reader ! testAssociate(uid = 33, cookie = None) val wrappedHandle = Await.result(statusPromise.future, 3.seconds) match { - case h: AssociationHandle ⇒ + case h: AssociationHandle => h.remoteAddress should ===(remoteAkkaAddress) h.localAddress should ===(localAkkaAddress) h - case _ ⇒ fail() + case _ => fail() } wrappedHandle.readHandlerPromise.success(ActorHandleEventListener(testActor)) @@ -394,12 +394,12 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit stateActor ! testAssociate(uid = 33, cookie = None) val wrappedHandle = Await.result(statusPromise.future, 3.seconds) match { - case h: AssociationHandle ⇒ + case h: AssociationHandle => h.remoteAddress should ===(remoteAkkaAddress) h.localAddress should ===(localAkkaAddress) h - case _ ⇒ fail() + case _ => fail() } wrappedHandle.readHandlerPromise.success(ActorHandleEventListener(testActor)) @@ -433,12 +433,12 @@ class AkkaProtocolSpec extends AkkaSpec("""akka.actor.provider = remote """) wit stateActor ! testAssociate(uid = 33, cookie = None) val wrappedHandle = Await.result(statusPromise.future, 3.seconds) match { - case h: AssociationHandle ⇒ + case h: AssociationHandle => h.remoteAddress should ===(remoteAkkaAddress) h.localAddress should ===(localAkkaAddress) h - case _ ⇒ fail() + case _ => fail() } stateActor ! Disassociated(AssociationHandle.Unknown) diff --git a/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolStressTest.scala b/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolStressTest.scala index 11610b7eed..7ed1206e68 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolStressTest.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolStressTest.scala @@ -52,14 +52,14 @@ object AkkaProtocolStressTest { var losses = 0 def receive = { - case "start" ⇒ self ! "sendNext" - case "sendNext" ⇒ if (nextSeq < limit) { + case "start" => self ! "sendNext" + case "sendNext" => if (nextSeq < limit) { remote ! nextSeq nextSeq += 1 if (nextSeq % 2000 == 0) context.system.scheduler.scheduleOnce(500.milliseconds, self, "sendNext") else self ! "sendNext" } - case seq: Int ⇒ + case seq: Int => if (seq > maxSeq) { losses += seq - maxSeq - 1 maxSeq = seq @@ -79,7 +79,7 @@ object AkkaProtocolStressTest { // Make sure the other side eventually "gets the message" def done: Receive = { - case ResendFinal ⇒ + case ResendFinal => controller ! ((maxSeq, losses)) } } @@ -91,7 +91,7 @@ class AkkaProtocolStressTest extends AkkaSpec(configA) with ImplicitSender with val systemB = ActorSystem("systemB", system.settings.config) val remote = systemB.actorOf(Props(new Actor { def receive = { - case seq: Int ⇒ sender() ! seq + case seq: Int => sender() ! seq } }), "echo") @@ -112,7 +112,7 @@ class AkkaProtocolStressTest extends AkkaSpec(configA) with ImplicitSender with val tester = system.actorOf(Props(classOf[SequenceVerifier], here, self)) ! "start" expectMsgPF(60.seconds) { - case (received: Int, lost: Int) ⇒ + case (received: Int, lost: Int) => log.debug(s" ######## Received ${received - lost} messages from ${received} ########") } } diff --git a/akka-remote/src/test/scala/akka/remote/transport/GenericTransportSpec.scala b/akka-remote/src/test/scala/akka/remote/transport/GenericTransportSpec.scala index e775f570f1..a799e3afc2 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/GenericTransportSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/GenericTransportSpec.scala @@ -52,8 +52,8 @@ abstract class GenericTransportSpec(withAkkaProtocol: Boolean = false) result._2 should not be null registry.logSnapshot.exists { - case ListenAttempt(address) ⇒ address == addressATest - case _ ⇒ false + case ListenAttempt(address) => address == addressATest + case _ => false } should ===(true) } @@ -70,7 +70,7 @@ abstract class GenericTransportSpec(withAkkaProtocol: Boolean = false) transportA.associate(addressB) expectMsgPF(timeout.duration, "Expect InboundAssociation from A") { - case InboundAssociation(handle) if handle.remoteAddress == addressA ⇒ + case InboundAssociation(handle) if handle.remoteAddress == addressA => } registry.logSnapshot.contains(AssociateAttempt(addressATest, addressBTest)) should ===(true) @@ -100,7 +100,7 @@ abstract class GenericTransportSpec(withAkkaProtocol: Boolean = false) val associate: Future[AssociationHandle] = transportA.associate(addressB) val handleB = expectMsgPF(timeout.duration, "Expect InboundAssociation from A") { - case InboundAssociation(handle) if handle.remoteAddress == addressA ⇒ handle + case InboundAssociation(handle) if handle.remoteAddress == addressA => handle } val handleA = Await.result(associate, timeout.duration) @@ -116,12 +116,12 @@ abstract class GenericTransportSpec(withAkkaProtocol: Boolean = false) handleA.write(payload) expectMsgPF(timeout.duration, "Expect InboundPayload from A") { - case InboundPayload(p) if payload == p ⇒ + case InboundPayload(p) if payload == p => } registry.logSnapshot.exists { - case WriteAttempt(`addressATest`, `addressBTest`, sentPdu) ⇒ sentPdu == pdu - case _ ⇒ false + case WriteAttempt(`addressATest`, `addressBTest`, sentPdu) => sentPdu == pdu + case _ => false } should ===(true) } @@ -137,7 +137,7 @@ abstract class GenericTransportSpec(withAkkaProtocol: Boolean = false) val associate: Future[AssociationHandle] = transportA.associate(addressB) val handleB: AssociationHandle = expectMsgPF(timeout.duration, "Expect InboundAssociation from A") { - case InboundAssociation(handle) if handle.remoteAddress == addressA ⇒ handle + case InboundAssociation(handle) if handle.remoteAddress == addressA => handle } val handleA = Await.result(associate, timeout.duration) @@ -151,15 +151,15 @@ abstract class GenericTransportSpec(withAkkaProtocol: Boolean = false) handleA.disassociate() expectMsgPF(timeout.duration) { - case Disassociated(_) ⇒ + case Disassociated(_) => } awaitCond(!registry.existsAssociation(addressATest, addressBTest)) awaitCond { registry.logSnapshot exists { - case DisassociateAttempt(`addressATest`, `addressBTest`) ⇒ true - case _ ⇒ false + case DisassociateAttempt(`addressATest`, `addressBTest`) => true + case _ => false } } } diff --git a/akka-remote/src/test/scala/akka/remote/transport/SwitchableLoggedBehaviorSpec.scala b/akka-remote/src/test/scala/akka/remote/transport/SwitchableLoggedBehaviorSpec.scala index 79c6d093ef..1c84255bfd 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/SwitchableLoggedBehaviorSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/SwitchableLoggedBehaviorSpec.scala @@ -18,7 +18,7 @@ object SwitchableLoggedBehaviorSpec { class SwitchableLoggedBehaviorSpec extends AkkaSpec with DefaultTimeout { import akka.remote.transport.SwitchableLoggedBehaviorSpec._ - private def defaultBehavior = new SwitchableLoggedBehavior[Unit, Int]((_) ⇒ Future.successful(3), (_) ⇒ ()) + private def defaultBehavior = new SwitchableLoggedBehavior[Unit, Int]((_) => Future.successful(3), (_) => ()) "A SwitchableLoggedBehavior" must { @@ -31,13 +31,13 @@ class SwitchableLoggedBehaviorSpec extends AkkaSpec with DefaultTimeout { "be able to push generic behavior" in { val behavior = defaultBehavior - behavior.push((_) ⇒ Future.successful(4)) + behavior.push((_) => Future.successful(4)) Await.result(behavior(()), timeout.duration) should ===(4) - behavior.push((_) ⇒ Future.failed(TestException)) + behavior.push((_) => Future.failed(TestException)) behavior(()).value match { - case Some(Failure(`TestException`)) ⇒ - case _ ⇒ fail("Expected exception") + case Some(Failure(`TestException`)) => + case _ => fail("Expected exception") } } @@ -54,8 +54,8 @@ class SwitchableLoggedBehaviorSpec extends AkkaSpec with DefaultTimeout { behavior.pushError(TestException) behavior(()).value match { - case Some(Failure(e)) if e eq TestException ⇒ - case _ ⇒ fail("Expected exception") + case Some(Failure(e)) if e eq TestException => + case _ => fail("Expected exception") } } @@ -98,7 +98,7 @@ class SwitchableLoggedBehaviorSpec extends AkkaSpec with DefaultTimeout { "log calls and parameters" in { val logPromise = Promise[Int]() - val behavior = new SwitchableLoggedBehavior[Int, Int]((i) ⇒ Future.successful(3), (i) ⇒ logPromise.success(i)) + val behavior = new SwitchableLoggedBehavior[Int, Int]((i) => Future.successful(3), (i) => logPromise.success(i)) behavior(11) Await.result(logPromise.future, timeout.duration) should ===(11) diff --git a/akka-remote/src/test/scala/akka/remote/transport/SystemMessageDeliveryStressTest.scala b/akka-remote/src/test/scala/akka/remote/transport/SystemMessageDeliveryStressTest.scala index b1904de815..562c02eb38 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/SystemMessageDeliveryStressTest.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/SystemMessageDeliveryStressTest.scala @@ -71,8 +71,8 @@ object SystemMessageDeliveryStressTest { override def sendSystemMessage(message: SystemMessage): Unit = { message match { - case Failed(_, _, seq) ⇒ testActor ! seq - case _ ⇒ + case Failed(_, _, seq) => testActor ! seq + case _ => } } } @@ -88,7 +88,7 @@ object SystemMessageDeliveryStressTest { override def preStart(): Unit = self ! "sendnext" override def receive = { - case "sendnext" ⇒ + case "sendnext" => targetRef.sendSystemMessage(Failed(child, null, counter)) counter += 1 burstCounter += 1 @@ -168,7 +168,7 @@ abstract class SystemMessageDeliveryStressTest(msg: String, cfg: String) val toSend = (0 until msgCount).toList var maxDelay = 0L - for (m ← 0 until msgCount) { + for (m <- 0 until msgCount) { val start = System.currentTimeMillis() probeB.expectMsg(10.minutes, m) probeA.expectMsg(10.minutes, m) diff --git a/akka-remote/src/test/scala/akka/remote/transport/TestTransportSpec.scala b/akka-remote/src/test/scala/akka/remote/transport/TestTransportSpec.scala index db966fbcee..65ff32d2aa 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/TestTransportSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/TestTransportSpec.scala @@ -30,8 +30,8 @@ class TestTransportSpec extends AkkaSpec with DefaultTimeout with ImplicitSender result._2 should not be null registry.logSnapshot.exists { - case ListenAttempt(address) ⇒ address == addressA - case _ ⇒ false + case ListenAttempt(address) => address == addressA + case _ => false } should ===(true) } @@ -48,7 +48,7 @@ class TestTransportSpec extends AkkaSpec with DefaultTimeout with ImplicitSender transportA.associate(addressB) expectMsgPF(timeout.duration, "Expect InboundAssociation from A") { - case InboundAssociation(handle) if handle.remoteAddress == addressA ⇒ + case InboundAssociation(handle) if handle.remoteAddress == addressA => } registry.logSnapshot.contains(AssociateAttempt(addressA, addressB)) should ===(true) @@ -77,7 +77,7 @@ class TestTransportSpec extends AkkaSpec with DefaultTimeout with ImplicitSender val associate: Future[AssociationHandle] = transportA.associate(addressB) val handleB = expectMsgPF(timeout.duration, "Expect InboundAssociation from A") { - case InboundAssociation(handle) if handle.remoteAddress == addressA ⇒ handle + case InboundAssociation(handle) if handle.remoteAddress == addressA => handle } handleB.readHandlerPromise.success(ActorHandleEventListener(self)) @@ -92,13 +92,13 @@ class TestTransportSpec extends AkkaSpec with DefaultTimeout with ImplicitSender handleA.write(akkaPDU) expectMsgPF(timeout.duration, "Expect InboundPayload from A") { - case InboundPayload(payload) if payload == akkaPDU ⇒ + case InboundPayload(payload) if payload == akkaPDU => } registry.logSnapshot.exists { - case WriteAttempt(sender, recipient, payload) ⇒ + case WriteAttempt(sender, recipient, payload) => sender == addressA && recipient == addressB && payload == akkaPDU - case _ ⇒ false + case _ => false } should ===(true) } @@ -114,7 +114,7 @@ class TestTransportSpec extends AkkaSpec with DefaultTimeout with ImplicitSender val associate: Future[AssociationHandle] = transportA.associate(addressB) val handleB: AssociationHandle = expectMsgPF(timeout.duration, "Expect InboundAssociation from A") { - case InboundAssociation(handle) if handle.remoteAddress == addressA ⇒ handle + case InboundAssociation(handle) if handle.remoteAddress == addressA => handle } handleB.readHandlerPromise.success(ActorHandleEventListener(self)) @@ -128,14 +128,14 @@ class TestTransportSpec extends AkkaSpec with DefaultTimeout with ImplicitSender handleA.disassociate() expectMsgPF(timeout.duration) { - case Disassociated(_) ⇒ + case Disassociated(_) => } awaitCond(!registry.existsAssociation(addressA, addressB)) registry.logSnapshot exists { - case DisassociateAttempt(requester, remote) if requester == addressA && remote == addressB ⇒ true - case _ ⇒ false + case DisassociateAttempt(requester, remote) if requester == addressA && remote == addressB => true + case _ => false } should ===(true) } diff --git a/akka-remote/src/test/scala/akka/remote/transport/ThrottlerTransportAdapterSpec.scala b/akka-remote/src/test/scala/akka/remote/transport/ThrottlerTransportAdapterSpec.scala index 67a3f769db..460b41cfae 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/ThrottlerTransportAdapterSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/ThrottlerTransportAdapterSpec.scala @@ -34,8 +34,8 @@ object ThrottlerTransportAdapterSpec { class Echo extends Actor { override def receive = { - case "ping" ⇒ sender() ! "pong" - case x ⇒ sender() ! x + case "ping" => sender() ! "pong" + case x => sender() ! x } } @@ -50,15 +50,15 @@ object ThrottlerTransportAdapterSpec { var startTime = 0L override def receive = { - case "start" ⇒ + case "start" => self ! "sendNext" startTime = System.nanoTime() - case "sendNext" ⇒ if (messageCount > 0) { + case "sendNext" => if (messageCount > 0) { remote ! "ping" self ! "sendNext" messageCount -= 1 } - case "pong" ⇒ + case "pong" => received += 1 if (received >= MessageCount) controller ! (System.nanoTime() - startTime) } @@ -131,8 +131,8 @@ class ThrottlerTransportAdapterSpec extends AkkaSpec(configA) with ImplicitSende here ! "Cleanup" fishForMessage(5.seconds) { - case "Cleanup" ⇒ true - case Lost("Blackhole 3") ⇒ false + case "Cleanup" => true + case Lost("Blackhole 3") => false } } diff --git a/akka-remote/src/test/scala/akka/remote/transport/netty/NettyTransportSpec.scala b/akka-remote/src/test/scala/akka/remote/transport/netty/NettyTransportSpec.scala index 364b1fce07..fe8091fd52 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/netty/NettyTransportSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/netty/NettyTransportSpec.scala @@ -144,7 +144,7 @@ class NettyTransportSpec extends WordSpec with Matchers with BindBehavior { } trait BindBehavior { - this: WordSpec with Matchers ⇒ + this: WordSpec with Matchers => import akka.remote.transport.netty.NettyTransportSpec._ @@ -175,7 +175,7 @@ trait BindBehavior { val bindAddress = try SocketUtil.temporaryServerAddress(address = "127.0.1.1", udp = proto == "udp") catch { - case e: java.net.BindException ⇒ + case e: java.net.BindException => info(s"skipping test due to [${e.getMessage}], you probably have to use `ifconfig lo0 alias 127.0.1.1`") pending null diff --git a/akka-slf4j/src/main/scala/akka/event/slf4j/Slf4jLogger.scala b/akka-slf4j/src/main/scala/akka/event/slf4j/Slf4jLogger.scala index 2d5b8119a7..1067249d66 100644 --- a/akka-slf4j/src/main/scala/akka/event/slf4j/Slf4jLogger.scala +++ b/akka-slf4j/src/main/scala/akka/event/slf4j/Slf4jLogger.scala @@ -4,7 +4,7 @@ package akka.event.slf4j -import org.slf4j.{ MDC, Marker, MarkerFactory, Logger ⇒ SLFLogger, LoggerFactory ⇒ SLFLoggerFactory } +import org.slf4j.{ MDC, Marker, MarkerFactory, Logger => SLFLogger, LoggerFactory => SLFLoggerFactory } import akka.event.Logging._ import akka.actor._ import akka.event.{ LogMarker, _ } @@ -35,8 +35,8 @@ object Logger { * @return a Logger for the specified parameters */ def apply(logClass: Class[_], logSource: String): SLFLogger = logClass match { - case c if c == classOf[DummyClassForStringSources] ⇒ apply(logSource) - case _ ⇒ SLFLoggerFactory getLogger logClass + case c if c == classOf[DummyClassForStringSources] => apply(logSource) + case _ => SLFLoggerFactory getLogger logClass } /** @@ -60,64 +60,64 @@ class Slf4jLogger extends Actor with SLF4JLogging with RequiresMessageQueue[Logg def receive = { - case event @ Error(cause, logSource, logClass, message) ⇒ + case event @ Error(cause, logSource, logClass, message) => withMdc(logSource, event) { cause match { - case Error.NoCause | null ⇒ + case Error.NoCause | null => Logger(logClass, logSource).error(markerIfPresent(event), if (message != null) message.toString else null) - case _ ⇒ + case _ => Logger(logClass, logSource).error(markerIfPresent(event), if (message != null) message.toString else cause.getLocalizedMessage, cause) } } - case event @ Warning(logSource, logClass, message) ⇒ + case event @ Warning(logSource, logClass, message) => withMdc(logSource, event) { event match { - case e: LogEventWithCause ⇒ Logger(logClass, logSource).warn(markerIfPresent(event), if (message != null) message.toString else e.cause.getLocalizedMessage, e.cause) - case _ ⇒ Logger(logClass, logSource).warn(markerIfPresent(event), if (message != null) message.toString else null) + case e: LogEventWithCause => Logger(logClass, logSource).warn(markerIfPresent(event), if (message != null) message.toString else e.cause.getLocalizedMessage, e.cause) + case _ => Logger(logClass, logSource).warn(markerIfPresent(event), if (message != null) message.toString else null) } } - case event @ Info(logSource, logClass, message) ⇒ + case event @ Info(logSource, logClass, message) => withMdc(logSource, event) { Logger(logClass, logSource).info(markerIfPresent(event), "{}", message.asInstanceOf[AnyRef]) } - case event @ Debug(logSource, logClass, message) ⇒ + case event @ Debug(logSource, logClass, message) => withMdc(logSource, event) { Logger(logClass, logSource).debug(markerIfPresent(event), "{}", message.asInstanceOf[AnyRef]) } - case InitializeLogger(_) ⇒ + case InitializeLogger(_) => log.info("Slf4jLogger started") sender() ! LoggerInitialized } @inline - final def withMdc(logSource: String, logEvent: LogEvent)(logStatement: ⇒ Unit): Unit = { + final def withMdc(logSource: String, logEvent: LogEvent)(logStatement: => Unit): Unit = { MDC.put(mdcAkkaSourceAttributeName, logSource) MDC.put(mdcThreadAttributeName, logEvent.thread.getName) MDC.put(mdcAkkaTimestamp, formatTimestamp(logEvent.timestamp)) MDC.put(mdcActorSystemAttributeName, actorSystemName) - logEvent.mdc foreach { case (k, v) ⇒ MDC.put(k, String.valueOf(v)) } + logEvent.mdc foreach { case (k, v) => MDC.put(k, String.valueOf(v)) } try logStatement finally { MDC.remove(mdcAkkaSourceAttributeName) MDC.remove(mdcThreadAttributeName) MDC.remove(mdcAkkaTimestamp) MDC.remove(mdcActorSystemAttributeName) - logEvent.mdc.keys.foreach(k ⇒ MDC.remove(k)) + logEvent.mdc.keys.foreach(k => MDC.remove(k)) } } private final def markerIfPresent(event: LogEvent): Marker = event match { - case m: LogEventWithMarker ⇒ + case m: LogEventWithMarker => m.marker match { - case null ⇒ null - case slf4jMarker: Slf4jLogMarker ⇒ slf4jMarker.marker - case marker ⇒ MarkerFactory.getMarker(marker.name) + case null => null + case slf4jMarker: Slf4jLogMarker => slf4jMarker.marker + case marker => MarkerFactory.getMarker(marker.name) } - case _ ⇒ null + case _ => null } /** @@ -147,9 +147,9 @@ class Slf4jLoggingFilter(settings: ActorSystem.Settings, eventStream: EventStrea (eventStream.logLevel >= DebugLevel) && Logger(logClass, logSource).isDebugEnabled private def slf4jMarker(marker: LogMarker) = marker match { - case null ⇒ null - case slf4jMarker: Slf4jLogMarker ⇒ slf4jMarker.marker - case marker ⇒ MarkerFactory.getMarker(marker.name) + case null => null + case slf4jMarker: Slf4jLogMarker => slf4jMarker.marker + case marker => MarkerFactory.getMarker(marker.name) } override def isErrorEnabled(logClass: Class[_], logSource: String, marker: LogMarker): Boolean = diff --git a/akka-slf4j/src/test/scala/akka/event/slf4j/Slf4jLoggerSpec.scala b/akka-slf4j/src/test/scala/akka/event/slf4j/Slf4jLoggerSpec.scala index c6fed3c851..3251f28f7e 100644 --- a/akka-slf4j/src/test/scala/akka/event/slf4j/Slf4jLoggerSpec.scala +++ b/akka-slf4j/src/test/scala/akka/event/slf4j/Slf4jLoggerSpec.scala @@ -38,21 +38,21 @@ object Slf4jLoggerSpec { val markLog = Logging.withMarker(this) def receive = { - case e: Exception ⇒ + case e: Exception => log.error(e, e.getMessage) - case (s: String, x: Int, y: Int) ⇒ + case (s: String, x: Int, y: Int) => log.info(s, x, y) - case StringWithSlf4jMarker(s, m) ⇒ + case StringWithSlf4jMarker(s, m) => markLog.info(Slf4jLogMarker(m), s) - case StringWithSlf4jMarkerMDC(s, mark, mdc) ⇒ + case StringWithSlf4jMarkerMDC(s, mark, mdc) => markLog.mdc(mdc) markLog.info(Slf4jLogMarker(mark), s) markLog.clearMDC() - case StringWithMDC(s, mdc) ⇒ + case StringWithMDC(s, mdc) => log.mdc(mdc) log.info(s) log.clearMDC() - case StringWithMarker(s, marker) ⇒ + case StringWithMarker(s, marker) => markLog.info(marker, s) } } @@ -133,7 +133,7 @@ class Slf4jLoggerSpec extends AkkaSpec(Slf4jLoggerSpec.config) with BeforeAndAft "log info with slf4j marker and MDC" in { val slf4jMarker = MarkerFactory.getMarker("SLF") slf4jMarker.add(MarkerFactory.getMarker("ADDED")) // slf4j markers can have children - producer ! StringWithSlf4jMarkerMDC("security-wise interesting message", slf4jMarker, Map("ticketNumber" → 3671, "ticketDesc" → "Custom MDC Values")) + producer ! StringWithSlf4jMarkerMDC("security-wise interesting message", slf4jMarker, Map("ticketNumber" -> 3671, "ticketDesc" -> "Custom MDC Values")) awaitCond(outputString.contains("----"), 5 seconds) val s = outputString @@ -143,7 +143,7 @@ class Slf4jLoggerSpec extends AkkaSpec(Slf4jLoggerSpec.config) with BeforeAndAft } "put custom MDC values when specified" in { - producer ! StringWithMDC("Message with custom MDC values", Map("ticketNumber" → 3671, "ticketDesc" → "Custom MDC Values")) + producer ! StringWithMDC("Message with custom MDC values", Map("ticketNumber" -> 3671, "ticketDesc" -> "Custom MDC Values")) awaitCond(outputString.contains("----"), 5 seconds) val s = outputString @@ -164,7 +164,7 @@ class Slf4jLoggerSpec extends AkkaSpec(Slf4jLoggerSpec.config) with BeforeAndAft } "Support null values in custom MDC" in { - producer ! StringWithMDC("Message with null custom MDC values", Map("ticketNumber" → 3671, "ticketDesc" → null)) + producer ! StringWithMDC("Message with null custom MDC values", Map("ticketNumber" -> 3671, "ticketDesc" -> null)) awaitCond(outputString.contains("----"), 5 seconds) val s = outputString diff --git a/akka-slf4j/src/test/scala/akka/event/slf4j/Slf4jLoggingFilterSpec.scala b/akka-slf4j/src/test/scala/akka/event/slf4j/Slf4jLoggingFilterSpec.scala index 534403afce..838991c057 100644 --- a/akka-slf4j/src/test/scala/akka/event/slf4j/Slf4jLoggingFilterSpec.scala +++ b/akka-slf4j/src/test/scala/akka/event/slf4j/Slf4jLoggingFilterSpec.scala @@ -35,13 +35,13 @@ object Slf4jLoggingFilterSpec { class TestLogger extends Actor { var target: Option[ActorRef] = None override def receive: Receive = { - case InitializeLogger(bus) ⇒ + case InitializeLogger(bus) => bus.subscribe(context.self, classOf[SetTarget]) sender() ! LoggerInitialized - case SetTarget(ref) ⇒ + case SetTarget(ref) => target = Some(ref) ref ! ("OK") - case event: LogEvent ⇒ + case event: LogEvent => println("# event: " + event) target foreach { _ ! event } } @@ -49,7 +49,7 @@ object Slf4jLoggingFilterSpec { class DebugLevelProducer extends Actor with ActorLogging { def receive = { - case s: String ⇒ + case s: String => log.warning(s) log.info(s) println("# DebugLevelProducer: " + log.isDebugEnabled) @@ -59,7 +59,7 @@ object Slf4jLoggingFilterSpec { class WarningLevelProducer extends Actor with ActorLogging { def receive = { - case s: String ⇒ + case s: String => log.warning(s) log.info(s) log.debug(s) diff --git a/akka-stream-testkit/src/main/scala/akka/stream/testkit/StreamTestKit.scala b/akka-stream-testkit/src/main/scala/akka/stream/testkit/StreamTestKit.scala index be350659cd..128b0c980a 100644 --- a/akka-stream-testkit/src/main/scala/akka/stream/testkit/StreamTestKit.scala +++ b/akka-stream-testkit/src/main/scala/akka/stream/testkit/StreamTestKit.scala @@ -84,7 +84,7 @@ object TestPublisher { //this is a way to pause receiving message from probe until subscription is done private val subscribed = new CountDownLatch(1) - probe.ignoreMsg { case SubscriptionDone ⇒ true } + probe.ignoreMsg { case SubscriptionDone => true } probe.setAutoPilot(new TestActor.AutoPilot() { override def run(sender: ActorRef, msg: Any): AutoPilot = { if (msg == SubscriptionDone) subscribed.countDown() @@ -103,7 +103,7 @@ object TestPublisher { probe.ref ! SubscriptionDone } - def executeAfterSubscription[T](f: ⇒ T): T = { + def executeAfterSubscription[T](f: => T): T = { subscribed.await( probe.testKitSettings.DefaultTimeout.duration.length, probe.testKitSettings.DefaultTimeout.duration.unit) @@ -187,12 +187,12 @@ object TestPublisher { * } * }}} */ - def within[T](min: FiniteDuration, max: FiniteDuration)(f: ⇒ T): T = executeAfterSubscription { probe.within(min, max)(f) } + def within[T](min: FiniteDuration, max: FiniteDuration)(f: => T): T = executeAfterSubscription { probe.within(min, max)(f) } /** * Same as calling `within(0 seconds, max)(f)`. */ - def within[T](max: FiniteDuration)(f: ⇒ T): T = executeAfterSubscription { probe.within(max)(f) } + def within[T](max: FiniteDuration)(f: => T): T = executeAfterSubscription { probe.within(max)(f) } } /** @@ -332,9 +332,9 @@ object TestSubscriber { def expectNext(d: FiniteDuration): I = { val t = probe.remainingOr(d) probe.receiveOne(t) match { - case null ⇒ throw new AssertionError(s"Expected OnNext(_), yet no element signaled during $t") - case OnNext(elem) ⇒ elem.asInstanceOf[I] - case other ⇒ throw new AssertionError("expected OnNext, found " + other) + case null => throw new AssertionError(s"Expected OnNext(_), yet no element signaled during $t") + case OnNext(elem) => elem.asInstanceOf[I] + case other => throw new AssertionError("expected OnNext, found " + other) } } @@ -394,7 +394,7 @@ object TestSubscriber { * Expect the given elements to be signalled in order. */ def expectNextN(all: immutable.Seq[I]): Self = { - all.foreach(e ⇒ probe.expectMsg(OnNext(e))) + all.foreach(e => probe.expectMsg(OnNext(e))) self } @@ -404,8 +404,8 @@ object TestSubscriber { */ def expectNextUnorderedN(all: immutable.Seq[I]): Self = { @annotation.tailrec def expectOneOf(all: immutable.Seq[I]): Unit = all match { - case Nil ⇒ - case list ⇒ + case Nil => + case list => val next = expectNext() assert(all.contains(next), s"expected one of $all, but received $next") expectOneOf(all.diff(Seq(next))) @@ -527,11 +527,11 @@ object TestSubscriber { */ def expectNextOrError(): Either[Throwable, I] = { probe.fishForMessage(hint = s"OnNext(_) or error") { - case OnNext(element) ⇒ true - case OnError(cause) ⇒ true + case OnNext(element) => true + case OnError(cause) => true } match { - case OnNext(n: I @unchecked) ⇒ Right(n) - case OnError(err) ⇒ Left(err) + case OnNext(n: I @unchecked) => Right(n) + case OnError(err) => Left(err) } } @@ -541,11 +541,11 @@ object TestSubscriber { */ def expectNextOrError(element: I, cause: Throwable): Either[Throwable, I] = { probe.fishForMessage(hint = s"OnNext($element) or ${cause.getClass.getName}") { - case OnNext(`element`) ⇒ true - case OnError(`cause`) ⇒ true + case OnNext(`element`) => true + case OnError(`cause`) => true } match { - case OnNext(n: I @unchecked) ⇒ Right(n) - case OnError(err) ⇒ Left(err) + case OnNext(n: I @unchecked) => Right(n) + case OnError(err) => Left(err) } } @@ -554,11 +554,11 @@ object TestSubscriber { */ def expectNextOrComplete(): Either[OnComplete.type, I] = { probe.fishForMessage(hint = s"OnNext(_) or OnComplete") { - case OnNext(n) ⇒ true - case OnComplete ⇒ true + case OnNext(n) => true + case OnComplete => true } match { - case OnComplete ⇒ Left(OnComplete) - case OnNext(n: I @unchecked) ⇒ Right(n) + case OnComplete => Left(OnComplete) + case OnNext(n: I @unchecked) => Right(n) } } @@ -569,8 +569,8 @@ object TestSubscriber { */ def expectNextOrComplete(element: I): Self = { probe.fishForMessage(hint = s"OnNext($element) or OnComplete") { - case OnNext(`element`) ⇒ true - case OnComplete ⇒ true + case OnNext(`element`) => true + case OnComplete => true } self } @@ -632,7 +632,7 @@ object TestSubscriber { */ def expectNextWithTimeoutPF[T](max: Duration, f: PartialFunction[Any, T]): T = expectEventWithTimeoutPF(max, { - case OnNext(n) if f.isDefinedAt(n) ⇒ f(n) + case OnNext(n) if f.isDefinedAt(n) => f(n) }) /** @@ -643,7 +643,7 @@ object TestSubscriber { * @param max wait no more than max time, otherwise throw AssertionError */ def expectNextChainingPF(max: Duration, f: PartialFunction[Any, Any]): Self = - expectNextWithTimeoutPF(max, f.andThen(_ ⇒ self)) + expectNextWithTimeoutPF(max, f.andThen(_ => self)) /** * Expect a stream element during specified time or timeout and test it with partial function. @@ -670,8 +670,8 @@ object TestSubscriber { */ def receiveWithin(max: FiniteDuration, messages: Int = Int.MaxValue): immutable.Seq[I] = probe.receiveWhile(max, max, messages) { - case OnNext(i) ⇒ Some(i.asInstanceOf[I]) - case _ ⇒ None + case OnNext(i) => Some(i.asInstanceOf[I]) + case _ => None }.flatten /** @@ -685,11 +685,11 @@ object TestSubscriber { @tailrec def drain(): immutable.Seq[I] = self.expectEvent(deadline.timeLeft) match { - case OnError(ex) ⇒ + case OnError(ex) => throw new AssertionError(s"toStrict received OnError while draining stream! Accumulated elements: ${b.result()}", ex) - case OnComplete ⇒ + case OnComplete => b.result() - case OnNext(i: I @unchecked) ⇒ + case OnNext(i: I @unchecked) => b += i drain() } @@ -717,12 +717,12 @@ object TestSubscriber { * } * }}} */ - def within[T](min: FiniteDuration, max: FiniteDuration)(f: ⇒ T): T = probe.within(min, max)(f) + def within[T](min: FiniteDuration, max: FiniteDuration)(f: => T): T = probe.within(min, max)(f) /** * Same as calling `within(0 seconds, max)(f)`. */ - def within[T](max: FiniteDuration)(f: ⇒ T): T = probe.within(max)(f) + def within[T](max: FiniteDuration)(f: => T): T = probe.within(max)(f) def onSubscribe(subscription: Subscription): Unit = probe.ref ! OnSubscribe(subscription) def onNext(element: I): Unit = probe.ref ! OnNext(element) @@ -804,12 +804,12 @@ private[testkit] object StreamTestKit { def expectRequest(n: Long): Unit = publisherProbe.expectMsg(RequestMore(this, n)) def expectRequest(): Long = publisherProbe.expectMsgPF(hint = "expecting request() signal") { - case RequestMore(sub, n) if sub eq this ⇒ n + case RequestMore(sub, n) if sub eq this => n } def expectCancellation(): Unit = publisherProbe.fishForMessage(hint = "Expecting cancellation") { - case CancelSubscription(sub) if sub eq this ⇒ true - case RequestMore(sub, _) if sub eq this ⇒ false + case CancelSubscription(sub) if sub eq this => true + case RequestMore(sub, _) if sub eq this => false } def sendNext(element: I): Unit = subscriber.onNext(element) diff --git a/akka-stream-testkit/src/main/scala/akka/stream/testkit/TestGraphStage.scala b/akka-stream-testkit/src/main/scala/akka/stream/testkit/TestGraphStage.scala index e9a893d7e2..e1ff5fc7e4 100644 --- a/akka-stream-testkit/src/main/scala/akka/stream/testkit/TestGraphStage.scala +++ b/akka-stream-testkit/src/main/scala/akka/stream/testkit/TestGraphStage.scala @@ -65,7 +65,7 @@ private[testkit] class TestSinkStage[T, M]( inHandler.onPush() probe.ref ! GraphStageMessages.Push } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.Push, ex) throw ex } @@ -75,7 +75,7 @@ private[testkit] class TestSinkStage[T, M]( inHandler.onUpstreamFinish() probe.ref ! GraphStageMessages.UpstreamFinish } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.UpstreamFinish, ex) throw ex } @@ -86,7 +86,7 @@ private[testkit] class TestSinkStage[T, M]( inHandler.onUpstreamFailure(ex) probe.ref ! GraphStageMessages.Failure(ex) } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.Failure(ex), ex) throw ex } @@ -131,7 +131,7 @@ private[testkit] class TestSourceStage[T, M]( outHandler.onPull() probe.ref ! GraphStageMessages.Pull } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.Pull, ex) throw ex } @@ -141,7 +141,7 @@ private[testkit] class TestSourceStage[T, M]( outHandler.onDownstreamFinish() probe.ref ! GraphStageMessages.DownstreamFinish } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.DownstreamFinish, ex) throw ex } diff --git a/akka-stream-testkit/src/main/scala/akka/stream/testkit/javadsl/StreamTestKit.scala b/akka-stream-testkit/src/main/scala/akka/stream/testkit/javadsl/StreamTestKit.scala index 0a964f68a4..f158493da3 100644 --- a/akka-stream-testkit/src/main/scala/akka/stream/testkit/javadsl/StreamTestKit.scala +++ b/akka-stream-testkit/src/main/scala/akka/stream/testkit/javadsl/StreamTestKit.scala @@ -17,8 +17,8 @@ object StreamTestKit { */ def assertAllStagesStopped(mat: Materializer): Unit = mat match { - case impl: PhasedFusingActorMaterializer ⇒ + case impl: PhasedFusingActorMaterializer => scaladsl.StreamTestKit.assertNoChildren(impl.system, impl.supervisor) - case _ ⇒ + case _ => } } diff --git a/akka-stream-testkit/src/main/scala/akka/stream/testkit/scaladsl/StreamTestKit.scala b/akka-stream-testkit/src/main/scala/akka/stream/testkit/scaladsl/StreamTestKit.scala index 8092aef841..cfc1d80656 100644 --- a/akka-stream-testkit/src/main/scala/akka/stream/testkit/scaladsl/StreamTestKit.scala +++ b/akka-stream-testkit/src/main/scala/akka/stream/testkit/scaladsl/StreamTestKit.scala @@ -25,14 +25,14 @@ object StreamTestKit { * This assertion is useful to check that all of the stages have * terminated successfully. */ - def assertAllStagesStopped[T](block: ⇒ T)(implicit materializer: Materializer): T = + def assertAllStagesStopped[T](block: => T)(implicit materializer: Materializer): T = materializer match { - case impl: PhasedFusingActorMaterializer ⇒ + case impl: PhasedFusingActorMaterializer => stopAllChildren(impl.system, impl.supervisor) val result = block assertNoChildren(impl.system, impl.supervisor) result - case _ ⇒ block + case _ => block } /** INTERNAL API */ @@ -55,7 +55,7 @@ object StreamTestKit { children.isEmpty, s"expected no StreamSupervisor children, but got [${children.mkString(", ")}]") } catch { - case ex: Throwable ⇒ + case ex: Throwable => import sys.dispatcher printDebugDump(supervisor) throw ex @@ -66,8 +66,8 @@ object StreamTestKit { /** INTERNAL API */ @InternalApi private[akka] def printDebugDump(streamSupervisor: ActorRef)(implicit ec: ExecutionContext): Unit = { val doneDumping = MaterializerState.requestFromSupervisor(streamSupervisor) - .map(snapshots ⇒ - snapshots.foreach(s ⇒ println(snapshotString(s.asInstanceOf[StreamSnapshotImpl])) + .map(snapshots => + snapshots.foreach(s => println(snapshotString(s.asInstanceOf[StreamSnapshotImpl])) )) Await.result(doneDumping, 5.seconds) } @@ -76,7 +76,7 @@ object StreamTestKit { @InternalApi private[testkit] def snapshotString(snapshot: StreamSnapshotImpl): String = { val builder = StringBuilder.newBuilder builder.append(s"activeShells (actor: ${snapshot.self}):\n") - snapshot.activeInterpreters.foreach { shell ⇒ + snapshot.activeInterpreters.foreach { shell => builder.append(" ") appendShellSnapshot(builder, shell) builder.append("\n") @@ -84,7 +84,7 @@ object StreamTestKit { builder.append("\n") } builder.append(s"newShells:\n") - snapshot.newShells.foreach { shell ⇒ + snapshot.newShells.foreach { shell => builder.append(" ") appendShellSnapshot(builder, shell) builder.append("\n") @@ -97,7 +97,7 @@ object StreamTestKit { private def appendShellSnapshot(builder: StringBuilder, shell: InterpreterSnapshot): Unit = { builder.append("GraphInterpreterShell(\n logics: [\n") val logicsToPrint = shell.logics - logicsToPrint.foreach { logic ⇒ + logicsToPrint.foreach { logic => builder.append(" ") .append(logic.label) .append(" attrs: [") @@ -106,9 +106,9 @@ object StreamTestKit { } builder.setLength(builder.length - 2) shell match { - case running: RunningInterpreter ⇒ + case running: RunningInterpreter => builder.append("\n ],\n connections: [\n") - running.connections.foreach { connection ⇒ + running.connections.foreach { connection => builder.append(" ") .append("Connection(") .append(connection.asInstanceOf[ConnectionSnapshotImpl].id) @@ -122,7 +122,7 @@ object StreamTestKit { } builder.setLength(builder.length - 2) - case _ ⇒ + case _ => } builder.append("\n ]\n)") builder.toString() @@ -134,24 +134,24 @@ object StreamTestKit { builder.append("================================================================\n") builder.append("digraph waits {\n") - for (i ← snapshot.logics.indices) { + for (i <- snapshot.logics.indices) { val logic = snapshot.logics(i) builder.append(s""" N$i [label="${logic.label}"];""").append('\n') } - for (connection ← snapshot.connections) { + for (connection <- snapshot.connections) { val inName = "N" + connection.in.asInstanceOf[LogicSnapshotImpl].index val outName = "N" + connection.out.asInstanceOf[LogicSnapshotImpl].index builder.append(s" $inName -> $outName ") connection.state match { - case ConnectionSnapshot.ShouldPull ⇒ + case ConnectionSnapshot.ShouldPull => builder.append("[label=shouldPull, color=blue];") - case ConnectionSnapshot.ShouldPush ⇒ + case ConnectionSnapshot.ShouldPush => builder.append(s"[label=shouldPush, color=red];") - case ConnectionSnapshot.Closed ⇒ + case ConnectionSnapshot.Closed => builder.append("[style=dotted, label=closed, dir=both];") - case _ ⇒ + case _ => } builder.append("\n") } @@ -160,7 +160,7 @@ object StreamTestKit { builder.append(s"// ${snapshot.queueStatus} (running=${snapshot.runningLogicsCount}, shutdown=${snapshot.stoppedLogics.mkString(",")})") builder.toString() } catch { - case _: NoSuchElementException ⇒ builder.append("Not all logics has a stage listed, cannot create graph") + case _: NoSuchElementException => builder.append("Not all logics has a stage listed, cannot create graph") } } diff --git a/akka-stream-testkit/src/test/scala/akka/stream/testkit/ChainSetup.scala b/akka-stream-testkit/src/test/scala/akka/stream/testkit/ChainSetup.scala index 57facb4ed2..ec5f4e9ce7 100644 --- a/akka-stream-testkit/src/test/scala/akka/stream/testkit/ChainSetup.scala +++ b/akka-stream-testkit/src/test/scala/akka/stream/testkit/ChainSetup.scala @@ -12,24 +12,24 @@ import org.reactivestreams.Publisher import akka.stream.ActorMaterializer class ChainSetup[In, Out, M]( - stream: Flow[In, In, NotUsed] ⇒ Flow[In, Out, M], + stream: Flow[In, In, NotUsed] => Flow[In, Out, M], val settings: ActorMaterializerSettings, materializer: ActorMaterializer, - toPublisher: (Source[Out, _], ActorMaterializer) ⇒ Publisher[Out])(implicit val system: ActorSystem) { + toPublisher: (Source[Out, _], ActorMaterializer) => Publisher[Out])(implicit val system: ActorSystem) { - def this(stream: Flow[In, In, NotUsed] ⇒ Flow[In, Out, M], settings: ActorMaterializerSettings, toPublisher: (Source[Out, _], ActorMaterializer) ⇒ Publisher[Out])(implicit system: ActorSystem) = + def this(stream: Flow[In, In, NotUsed] => Flow[In, Out, M], settings: ActorMaterializerSettings, toPublisher: (Source[Out, _], ActorMaterializer) => Publisher[Out])(implicit system: ActorSystem) = this(stream, settings, ActorMaterializer(settings)(system), toPublisher)(system) def this( - stream: Flow[In, In, NotUsed] ⇒ Flow[In, Out, M], + stream: Flow[In, In, NotUsed] => Flow[In, Out, M], settings: ActorMaterializerSettings, - materializerCreator: (ActorMaterializerSettings, ActorRefFactory) ⇒ ActorMaterializer, - toPublisher: (Source[Out, _], ActorMaterializer) ⇒ Publisher[Out])(implicit system: ActorSystem) = + materializerCreator: (ActorMaterializerSettings, ActorRefFactory) => ActorMaterializer, + toPublisher: (Source[Out, _], ActorMaterializer) => Publisher[Out])(implicit system: ActorSystem) = this(stream, settings, materializerCreator(settings, system), toPublisher)(system) val upstream = TestPublisher.manualProbe[In]() val downstream = TestSubscriber.probe[Out]() - private val s = Source.fromPublisher(upstream).via(stream(Flow[In].map(x ⇒ x).named("buh"))) + private val s = Source.fromPublisher(upstream).via(stream(Flow[In].map(x => x).named("buh"))) val publisher = toPublisher(s, materializer) val upstreamSubscription = upstream.expectSubscription() publisher.subscribe(downstream) diff --git a/akka-stream-testkit/src/test/scala/akka/stream/testkit/ScriptedTest.scala b/akka-stream-testkit/src/test/scala/akka/stream/testkit/ScriptedTest.scala index 2c51e3fc86..6d0d091e60 100644 --- a/akka-stream-testkit/src/test/scala/akka/stream/testkit/ScriptedTest.scala +++ b/akka-stream-testkit/src/test/scala/akka/stream/testkit/ScriptedTest.scala @@ -21,8 +21,8 @@ trait ScriptedTest extends Matchers { class ScriptException(msg: String) extends RuntimeException(msg) - def toPublisher[In, Out]: (Source[Out, _], ActorMaterializer) ⇒ Publisher[Out] = - (f, m) ⇒ f.runWith(Sink.asPublisher(false))(m) + def toPublisher[In, Out]: (Source[Out, _], ActorMaterializer) => Publisher[Out] = + (f, m) => f.runWith(Sink.asPublisher(false))(m) object Script { def apply[In, Out](phases: (Seq[In], Seq[Out])*): Script[In, Out] = { @@ -30,7 +30,7 @@ trait ScriptedTest extends Matchers { var expectedOutputs = Vector[Out]() var jumps = Vector[Int]() - for ((ins, outs) ← phases) { + for ((ins, outs) <- phases) { providedInputs ++= ins expectedOutputs ++= outs jumps ++= Vector.fill(ins.size - 1)(0) ++ Vector(outs.size) @@ -89,7 +89,7 @@ trait ScriptedTest extends Matchers { } class ScriptRunner[In, Out, M]( - op: Flow[In, In, NotUsed] ⇒ Flow[In, Out, M], + op: Flow[In, In, NotUsed] => Flow[In, Out, M], settings: ActorMaterializerSettings, script: Script[In, Out], maximumOverrun: Int, @@ -130,28 +130,28 @@ trait ScriptedTest extends Matchers { def shakeIt(): Boolean = { val u = upstream.receiveWhile(1.milliseconds) { - case RequestMore(_, n) ⇒ + case RequestMore(_, n) => debugLog(s"operation requests $n") pendingRequests += n true - case _ ⇒ false // Ignore + case _ => false // Ignore } val d = downstream.receiveWhile(1.milliseconds) { - case OnNext(elem: Out @unchecked) ⇒ + case OnNext(elem: Out @unchecked) => debugLog(s"operation produces [$elem]") if (outstandingDemand == 0) fail("operation produced while there was no demand") outstandingDemand -= 1 currentScript = currentScript.consumeOutput(elem) true - case OnComplete ⇒ + case OnComplete => currentScript = currentScript.complete() true - case OnError(e) ⇒ + case OnError(e) => currentScript = currentScript.error(e) true - case _ ⇒ false // Ignore + case _ => false // Ignore } - (u ++ d) exists (x ⇒ x) + (u ++ d) exists (x => x) } def run(): Unit = { @@ -189,7 +189,7 @@ trait ScriptedTest extends Matchers { request(getNextDemand()) doRun(0) } catch { - case e: Throwable ⇒ + case e: Throwable => println(_debugLog.mkString("Steps leading to failure:\n", "\n", "\nCurrentScript: " + currentScript.debug)) throw e } @@ -199,7 +199,7 @@ trait ScriptedTest extends Matchers { } def runScript[In, Out, M](script: Script[In, Out], settings: ActorMaterializerSettings, maximumOverrun: Int = 3, maximumRequest: Int = 3, maximumBuffer: Int = 3)( - op: Flow[In, In, NotUsed] ⇒ Flow[In, Out, M])(implicit system: ActorSystem): Unit = { + op: Flow[In, In, NotUsed] => Flow[In, Out, M])(implicit system: ActorSystem): Unit = { new ScriptRunner(op, settings, script, maximumOverrun, maximumRequest, maximumBuffer).run() } diff --git a/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamSpec.scala b/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamSpec.scala index 369005d2ec..d0eb004c40 100644 --- a/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamSpec.scala +++ b/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamSpec.scala @@ -28,7 +28,7 @@ class StreamSpec(_system: ActorSystem) extends AkkaSpec(_system) { override def withFixture(test: NoArgTest) = { super.withFixture(test) match { - case failed: Failed ⇒ + case failed: Failed => implicit val ec = system.dispatcher val probe = TestProbe()(system) // FIXME I don't think it always runs under /user anymore (typed) @@ -36,20 +36,20 @@ class StreamSpec(_system: ActorSystem) extends AkkaSpec(_system) { val streamSupervisors = system.actorSelection("/user/" + StreamSupervisor.baseName + "*") streamSupervisors.tell(StreamSupervisor.GetChildren, probe.ref) val children: Seq[ActorRef] = probe.receiveWhile(2.seconds) { - case StreamSupervisor.Children(children) ⇒ children + case StreamSupervisor.Children(children) => children }.flatten println("--- Stream actors debug dump ---") if (children.isEmpty) println("Stream is completed. No debug information is available") else { println("Stream actors alive: " + children) Future.sequence(children.map(MaterializerState.requestFromChild)) - .foreach(snapshots ⇒ - snapshots.foreach(s ⇒ + .foreach(snapshots => + snapshots.foreach(s => akka.stream.testkit.scaladsl.StreamTestKit.snapshotString(s.asInstanceOf[StreamSnapshotImpl])) ) } failed - case other ⇒ other + case other => other } } } diff --git a/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamTestDefaultMailbox.scala b/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamTestDefaultMailbox.scala index 0bda9acf08..131ce45f2f 100644 --- a/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamTestDefaultMailbox.scala +++ b/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamTestDefaultMailbox.scala @@ -25,7 +25,7 @@ private[akka] final case class StreamTestDefaultMailbox() extends MailboxType wi final override def create(owner: Option[ActorRef], system: Option[ActorSystem]): MessageQueue = { owner match { - case Some(r: ActorRefWithCell) ⇒ + case Some(r: ActorRefWithCell) => val actorClass = r.underlying.props.actorClass assert(actorClass != classOf[Actor], s"Don't use anonymous actor classes, actor class for $r was [${actorClass.getName}]") // StreamTcpManager is allowed to use another dispatcher @@ -35,7 +35,7 @@ private[akka] final case class StreamTestDefaultMailbox() extends MailboxType wi "Did you forget to define `props.withDispatcher` when creating the actor? " + "Or did you forget to configure the `akka.stream.materializer` setting accordingly or force the " + """dispatcher using `ActorMaterializerSettings(sys).withDispatcher("akka.test.stream-dispatcher")` in the test?""") - case _ ⇒ + case _ => } new UnboundedMailbox.MessageQueue } diff --git a/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamTestKitSpec.scala b/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamTestKitSpec.scala index b9e5798d52..965d6a5e5d 100644 --- a/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamTestKitSpec.scala +++ b/akka-stream-testkit/src/test/scala/akka/stream/testkit/StreamTestKitSpec.scala @@ -30,7 +30,7 @@ class StreamTestKitSpec extends AkkaSpec { system.eventStream.publish(Mute(EventFilter[Exception]())) try { val error = intercept[AssertionError] { - Source.fromIterator(() ⇒ new Iterator[Int] { + Source.fromIterator(() => new Iterator[Int] { var i = 0 override def hasNext: Boolean = true @@ -38,8 +38,8 @@ class StreamTestKitSpec extends AkkaSpec { override def next(): Int = { i += 1 i match { - case 3 ⇒ throw ex - case n ⇒ n + case 3 => throw ex + case n => n } } }).runWith(TestSink.probe) @@ -127,7 +127,7 @@ class StreamTestKitSpec extends AkkaSpec { val result = Source.single(1).runWith(TestSink.probe) .request(1) .expectNextPF { - case 1 ⇒ "success" + case 1 => "success" } result should be("success") } @@ -137,7 +137,7 @@ class StreamTestKitSpec extends AkkaSpec { Source.single(1).runWith(TestSink.probe) .request(1) .expectNextPF { - case 2 ⇒ + case 2 => } }.getMessage should include("message matching partial function") } @@ -149,7 +149,7 @@ class StreamTestKitSpec extends AkkaSpec { Source.tick(overTimeout, 1.millis, 1).runWith(TestSink.probe) .request(1) .expectNextWithTimeoutPF(timeout, { - case 1 ⇒ + case 1 => }) }.getMessage should include("timeout") @@ -159,7 +159,7 @@ class StreamTestKitSpec extends AkkaSpec { Source.single(1).runWith(TestSink.probe) .request(1) .expectNextChainingPF { - case 1 ⇒ + case 1 => } } @@ -167,7 +167,7 @@ class StreamTestKitSpec extends AkkaSpec { Source(1 to 2).runWith(TestSink.probe) .request(2) .expectNextChainingPF { - case 1 ⇒ + case 1 => }.expectNext(2) } @@ -176,7 +176,7 @@ class StreamTestKitSpec extends AkkaSpec { Source.single(1).runWith(TestSink.probe) .request(1) .expectNextChainingPF { - case 2 ⇒ + case 2 => } }.getMessage should include("message matching partial function") } @@ -188,7 +188,7 @@ class StreamTestKitSpec extends AkkaSpec { Source.tick(overTimeout, 1.millis, 1).runWith(TestSink.probe) .request(1) .expectNextChainingPF(timeout, { - case 1 ⇒ + case 1 => system.log.info("Message received :(") }) }.getMessage should include("timeout") diff --git a/akka-stream-testkit/src/test/scala/akka/stream/testkit/TestPublisherSubscriberSpec.scala b/akka-stream-testkit/src/test/scala/akka/stream/testkit/TestPublisherSubscriberSpec.scala index 08f372ecfe..adc7e30af3 100644 --- a/akka-stream-testkit/src/test/scala/akka/stream/testkit/TestPublisherSubscriberSpec.scala +++ b/akka-stream-testkit/src/test/scala/akka/stream/testkit/TestPublisherSubscriberSpec.scala @@ -27,21 +27,21 @@ class TestPublisherSubscriberSpec extends AkkaSpec { Source.fromPublisher(upstream).runWith(Sink.asPublisher(false))(materializer).subscribe(downstream) val upstreamSubscription = upstream.expectSubscription() - val downstreamSubscription: Subscription = downstream.expectEventPF { case OnSubscribe(sub) ⇒ sub } + val downstreamSubscription: Subscription = downstream.expectEventPF { case OnSubscribe(sub) => sub } upstreamSubscription.sendNext(1) downstreamSubscription.request(1) - upstream.expectEventPF { case RequestMore(_, e) ⇒ e } should ===(1L) - downstream.expectEventPF { case OnNext(e) ⇒ e } should ===(1) + upstream.expectEventPF { case RequestMore(_, e) => e } should ===(1L) + downstream.expectEventPF { case OnNext(e) => e } should ===(1) upstreamSubscription.sendNext(1) downstreamSubscription.request(1) - downstream.expectNextPF[Int] { case e: Int ⇒ e } should ===(1) + downstream.expectNextPF[Int] { case e: Int => e } should ===(1) upstreamSubscription.sendComplete() downstream.expectEventPF { - case OnComplete ⇒ - case _ ⇒ fail() + case OnComplete => + case _ => fail() } } @@ -50,12 +50,12 @@ class TestPublisherSubscriberSpec extends AkkaSpec { val downstream = TestSubscriber.manualProbe[Int]() Source.fromPublisher(upstream).runWith(Sink.asPublisher(false))(materializer).subscribe(downstream) val upstreamSubscription = upstream.expectSubscription() - val downstreamSubscription: Subscription = downstream.expectEventPF { case OnSubscribe(sub) ⇒ sub } + val downstreamSubscription: Subscription = downstream.expectEventPF { case OnSubscribe(sub) => sub } upstreamSubscription.sendNext(1) downstreamSubscription.request(1) - an[AssertionError] should be thrownBy upstream.expectEventPF { case Subscribe(e) ⇒ e } - an[AssertionError] should be thrownBy downstream.expectNextPF[String] { case e: String ⇒ e } + an[AssertionError] should be thrownBy upstream.expectEventPF { case Subscribe(e) => e } + an[AssertionError] should be thrownBy downstream.expectNextPF[String] { case e: String => e } upstreamSubscription.sendComplete() } diff --git a/akka-stream-testkit/src/test/scala/akka/stream/testkit/TwoStreamsSetup.scala b/akka-stream-testkit/src/test/scala/akka/stream/testkit/TwoStreamsSetup.scala index fde8b67a95..91bff9895e 100644 --- a/akka-stream-testkit/src/test/scala/akka/stream/testkit/TwoStreamsSetup.scala +++ b/akka-stream-testkit/src/test/scala/akka/stream/testkit/TwoStreamsSetup.scala @@ -20,7 +20,7 @@ abstract class TwoStreamsSetup extends BaseTwoStreamsSetup { override def setup(p1: Publisher[Int], p2: Publisher[Int]) = { val subscriber = TestSubscriber.probe[Outputs]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val f = fixture(b) diff --git a/akka-stream-testkit/src/test/scala/akka/stream/testkit/Utils.scala b/akka-stream-testkit/src/test/scala/akka/stream/testkit/Utils.scala index 2b569d8aed..261f269fd5 100644 --- a/akka-stream-testkit/src/test/scala/akka/stream/testkit/Utils.scala +++ b/akka-stream-testkit/src/test/scala/akka/stream/testkit/Utils.scala @@ -17,10 +17,10 @@ object Utils { case class TE(message: String) extends RuntimeException(message) with NoStackTrace def assertDispatcher(ref: ActorRef, dispatcher: String): Unit = ref match { - case r: ActorRefWithCell ⇒ + case r: ActorRefWithCell => if (r.underlying.props.dispatcher != dispatcher) throw new AssertionError(s"Expected $ref to use dispatcher [$dispatcher], yet used: [${r.underlying.props.dispatcher}]") - case _ ⇒ + case _ => throw new Exception(s"Unable to determine dispatcher of $ref") } } diff --git a/akka-stream-tests-tck/src/test/scala-jdk9-only/akka/stream/tck/IterablePublisherViaJavaFlowPublisherTest.scala b/akka-stream-tests-tck/src/test/scala-jdk9-only/akka/stream/tck/IterablePublisherViaJavaFlowPublisherTest.scala index 8630d79214..78acc993c3 100644 --- a/akka-stream-tests-tck/src/test/scala-jdk9-only/akka/stream/tck/IterablePublisherViaJavaFlowPublisherTest.scala +++ b/akka-stream-tests-tck/src/test/scala-jdk9-only/akka/stream/tck/IterablePublisherViaJavaFlowPublisherTest.scala @@ -4,7 +4,7 @@ package akka.stream.tck -import java.util.concurrent.{ Flow ⇒ JavaFlow } +import java.util.concurrent.{ Flow => JavaFlow } import akka.NotUsed import akka.stream.scaladsl.{ Flow, JavaFlowSupport, Sink, Source } diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorPublisherTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorPublisherTest.scala index af71d78130..161866e890 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorPublisherTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorPublisherTest.scala @@ -21,18 +21,18 @@ object ActorPublisherTest { val source: Iterator[Int] = (if (allElements == Long.MaxValue) 1 to Int.MaxValue else 0 until allElements.toInt).toIterator override def receive: Receive = { - case Request(elements) ⇒ + case Request(elements) => loopDemand() - case Produce if totalDemand > 0 && !isCompleted && source.hasNext ⇒ onNext(source.next()) - case Produce if !isCompleted && !source.hasNext ⇒ onComplete() - case Produce if isCompleted ⇒ // no-op - case _ ⇒ // no-op + case Produce if totalDemand > 0 && !isCompleted && source.hasNext => onNext(source.next()) + case Produce if !isCompleted && !source.hasNext => onComplete() + case Produce if isCompleted => // no-op + case _ => // no-op } def loopDemand(): Unit = { val loopUntil = math.min(100, totalDemand) - 1 to loopUntil.toInt foreach { _ ⇒ self ! Produce } + 1 to loopUntil.toInt foreach { _ => self ! Produce } if (loopUntil > 100) self ! Loop } } diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorSubscriberTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorSubscriberTest.scala index 98082c494f..d575c59987 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorSubscriberTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorSubscriberTest.scala @@ -13,7 +13,7 @@ import org.reactivestreams.Subscriber object ActorSubscriberOneByOneRequestTest { class StrategySubscriber(val requestStrategy: RequestStrategy) extends ActorSubscriber { - override def receive: Receive = { case _ ⇒ } + override def receive: Receive = { case _ => } } } diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorSystemLifecycle.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorSystemLifecycle.scala index a387ef7860..cb1cbaae74 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorSystemLifecycle.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ActorSystemLifecycle.scala @@ -35,7 +35,7 @@ trait ActorSystemLifecycle { try { Await.ready(system.terminate(), shutdownTimeout) } catch { - case _: TimeoutException ⇒ + case _: TimeoutException => val msg = "Failed to stop [%s] within [%s] \n%s".format(system.name, shutdownTimeout, system.asInstanceOf[ActorSystemImpl].printTree) throw new RuntimeException(msg) diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/FilePublisherTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/FilePublisherTest.scala index 4ab34b1e3f..6cac4cbdd5 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/FilePublisherTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/FilePublisherTest.scala @@ -31,7 +31,7 @@ class FilePublisherTest extends AkkaPublisherVerification[ByteString] { val chunk = "x" * ChunkSize val fw = Files.newBufferedWriter(f) - for (i ← 1 to Elements) fw.append(chunk) + for (i <- 1 to Elements) fw.append(chunk) fw.close() f } diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ForeachSinkSubscriberTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ForeachSinkSubscriberTest.scala index 166d6654af..bffbd3ae94 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ForeachSinkSubscriberTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/ForeachSinkSubscriberTest.scala @@ -10,7 +10,7 @@ import org.reactivestreams.Subscriber class ForeachSinkSubscriberTest extends AkkaSubscriberBlackboxVerification[Int] { override def createSubscriber(): Subscriber[Int] = - Flow[Int].to(Sink.foreach { _ ⇒ }).runWith(Source.asSubscriber) + Flow[Int].to(Sink.foreach { _ => }).runWith(Source.asSubscriber) override def createElement(element: Int): Int = element } diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/GroupByTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/GroupByTest.scala index 805929e045..f77c6b1f47 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/GroupByTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/GroupByTest.scala @@ -19,7 +19,7 @@ class GroupByTest extends AkkaPublisherVerification[Int] { else { val futureGroupSource = Source(iterable(elements)) - .groupBy(1, elem ⇒ "all") + .groupBy(1, elem => "all") .prefixAndTail(0) .map(_._2) .concatSubstreams diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/InputStreamSourceTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/InputStreamSourceTest.scala index 2dbb1efa96..c6598aa034 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/InputStreamSourceTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/InputStreamSourceTest.scala @@ -14,7 +14,7 @@ import org.reactivestreams.Publisher class InputStreamSourceTest extends AkkaPublisherVerification[ByteString] { def createPublisher(elements: Long): Publisher[ByteString] = { - StreamConverters.fromInputStream(() ⇒ new InputStream { + StreamConverters.fromInputStream(() => new InputStream { @volatile var num = 0 override def read(): Int = { num += 1 diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/MapTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/MapTest.scala index 2d671608f1..ab96166b6c 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/MapTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/MapTest.scala @@ -13,7 +13,7 @@ class MapTest extends AkkaIdentityProcessorVerification[Int] { override def createIdentityProcessor(maxBufferSize: Int): Processor[Int, Int] = { implicit val materializer = ActorMaterializer()(system) - Flow[Int].map(elem ⇒ elem).named("identity").toProcessor.run() + Flow[Int].map(elem => elem).named("identity").toProcessor.run() } override def createElement(element: Int): Int = element diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/PrefixAndTailTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/PrefixAndTailTest.scala index 8d7e28c733..55af036184 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/PrefixAndTailTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/PrefixAndTailTest.scala @@ -13,7 +13,7 @@ import org.reactivestreams.Publisher class PrefixAndTailTest extends AkkaPublisherVerification[Int] { def createPublisher(elements: Long): Publisher[Int] = { - val futureTailSource = Source(iterable(elements)).prefixAndTail(0).map { case (_, tail) ⇒ tail }.runWith(Sink.head) + val futureTailSource = Source(iterable(elements)).prefixAndTail(0).map { case (_, tail) => tail }.runWith(Sink.head) val tailSource = Await.result(futureTailSource, 3.seconds) tailSource.runWith(Sink.asPublisher(false)) } diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/SinkholeSubscriberTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/SinkholeSubscriberTest.scala index 8c0a0f4b41..efec8126ae 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/SinkholeSubscriberTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/SinkholeSubscriberTest.scala @@ -9,7 +9,7 @@ import akka.stream.impl.SinkholeSubscriber import org.reactivestreams.tck.{ TestEnvironment, SubscriberWhiteboxVerification } import org.reactivestreams.tck.SubscriberWhiteboxVerification.{ SubscriberPuppet, WhiteboxSubscriberProbe } import org.scalatestplus.testng.{ TestNGSuiteLike } -import java.lang.{ Integer ⇒ JInt } +import java.lang.{ Integer => JInt } import scala.concurrent.Promise import org.reactivestreams.{ Subscription, Subscriber } diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/SplitWhenTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/SplitWhenTest.scala index d704182f40..49f6580ba2 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/SplitWhenTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/SplitWhenTest.scala @@ -19,7 +19,7 @@ class SplitWhenTest extends AkkaPublisherVerification[Int] { else { val futureSource = Source(iterable(elements)) - .splitWhen(elem ⇒ false) + .splitWhen(elem => false) .prefixAndTail(0) .map(_._2) .concatSubstreams diff --git a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/VirtualPublisherTest.scala b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/VirtualPublisherTest.scala index ea4dd04cd6..01d178db23 100644 --- a/akka-stream-tests-tck/src/test/scala/akka/stream/tck/VirtualPublisherTest.scala +++ b/akka-stream-tests-tck/src/test/scala/akka/stream/tck/VirtualPublisherTest.scala @@ -14,7 +14,7 @@ class VirtualProcessorTest extends AkkaIdentityProcessorVerification[Int] { override def createIdentityProcessor(maxBufferSize: Int): Processor[Int, Int] = { implicit val materializer = ActorMaterializer()(system) - val identity = Flow[Int].map(elem ⇒ elem).named("identity").toProcessor.run() + val identity = Flow[Int].map(elem => elem).named("identity").toProcessor.run() val left, right = new VirtualProcessor[Int] left.subscribe(identity) identity.subscribe(right) diff --git a/akka-stream-tests/src/test/scala-jdk9-only/akka/stream/scaladsl/FlowPublisherSinkSpec.scala b/akka-stream-tests/src/test/scala-jdk9-only/akka/stream/scaladsl/FlowPublisherSinkSpec.scala index 3654de7aaf..b38acdc0cd 100644 --- a/akka-stream-tests/src/test/scala-jdk9-only/akka/stream/scaladsl/FlowPublisherSinkSpec.scala +++ b/akka-stream-tests/src/test/scala-jdk9-only/akka/stream/scaladsl/FlowPublisherSinkSpec.scala @@ -27,7 +27,7 @@ class FlowPublisherSinkSpec extends StreamSpec { "be able to use Publisher in materialized value transformation" in { val f = Source(1 to 3).runWith( - JavaFlowSupport.Sink.asPublisher[Int](false).mapMaterializedValue { p ⇒ + JavaFlowSupport.Sink.asPublisher[Int](false).mapMaterializedValue { p => JavaFlowSupport.Source.fromPublisher(p).runFold(0)(_ + _) }) diff --git a/akka-stream-tests/src/test/scala/akka/stream/ActorMaterializerSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/ActorMaterializerSpec.scala index 9c59d3288b..c869919c2f 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/ActorMaterializerSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/ActorMaterializerSpec.scala @@ -50,7 +50,7 @@ class ActorMaterializerSpec extends StreamSpec with ImplicitSender { val m = ActorMaterializer.create(system) the[IllegalStateException] thrownBy { - Source(1 to 5).mapMaterializedValue { _ ⇒ + Source(1 to 5).mapMaterializedValue { _ => // shutdown while materializing m.shutdown() Thread.sleep(100) @@ -107,7 +107,7 @@ object ActorMaterializerSpec { .take(1) .concat(Source.maybe) .map(p.ref ! _) - .runWith(Sink.onComplete(signal ⇒ { + .runWith(Sink.onComplete(signal => { p.ref ! signal })) diff --git a/akka-stream-tests/src/test/scala/akka/stream/DslConsistencySpec.scala b/akka-stream-tests/src/test/scala/akka/stream/DslConsistencySpec.scala index 8a0f662603..488257610a 100755 --- a/akka-stream-tests/src/test/scala/akka/stream/DslConsistencySpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/DslConsistencySpec.scala @@ -44,66 +44,66 @@ class DslConsistencySpec extends WordSpec with Matchers { val graphHelpers = Set("zipGraph", "zipWithGraph", "zipLatestGraph", "zipLatestWithGraph", "mergeGraph", "mergeSortedGraph", "interleaveGraph", "concatGraph", "prependGraph", "alsoToGraph", "wireTapGraph", "orElseGraph", "divertToGraph") val allowMissing: Map[Class[_], Set[String]] = Map( - jFlowClass → graphHelpers, - jSourceClass → (graphHelpers ++ Set("watch", "ask")), + jFlowClass -> graphHelpers, + jSourceClass -> (graphHelpers ++ Set("watch", "ask")), // Java subflows can only be nested using .via and .to (due to type system restrictions) - jSubFlowClass → (graphHelpers ++ Set("groupBy", "splitAfter", "splitWhen", "subFlow", "watch", "ask")), - jSubSourceClass → (graphHelpers ++ Set("groupBy", "splitAfter", "splitWhen", "subFlow", "watch", "ask")), + jSubFlowClass -> (graphHelpers ++ Set("groupBy", "splitAfter", "splitWhen", "subFlow", "watch", "ask")), + jSubSourceClass -> (graphHelpers ++ Set("groupBy", "splitAfter", "splitWhen", "subFlow", "watch", "ask")), - sFlowClass → Set("of"), - sSourceClass → Set("adapt", "from", "watch"), - sSinkClass → Set("adapt"), - sSubFlowClass → Set(), - sSubSourceClass → Set(), + sFlowClass -> Set("of"), + sSourceClass -> Set("adapt", "from", "watch"), + sSinkClass -> Set("adapt"), + sSubFlowClass -> Set(), + sSubSourceClass -> Set(), - sRunnableGraphClass → Set("builder")) + sRunnableGraphClass -> Set("builder")) def materializing(m: Method): Boolean = m.getParameterTypes.contains(classOf[ActorMaterializer]) def assertHasMethod(c: Class[_], name: String): Unit = { // include class name to get better error message if (!allowMissing.getOrElse(c, Set.empty).contains(name)) - c.getMethods.collect { case m if !ignore(m.getName) ⇒ c.getName + "." + m.getName } should contain(c.getName + "." + name) + c.getMethods.collect { case m if !ignore(m.getName) => c.getName + "." + m.getName } should contain(c.getName + "." + name) } "Java and Scala DSLs" must { - ("Source" → List[Class[_]](sSourceClass, jSourceClass)) :: - ("SubSource" → List[Class[_]](sSubSourceClass, jSubSourceClass)) :: - ("Flow" → List[Class[_]](sFlowClass, jFlowClass)) :: - ("SubFlow" → List[Class[_]](sSubFlowClass, jSubFlowClass)) :: - ("Sink" → List[Class[_]](sSinkClass, jSinkClass)) :: - ("RunnableFlow" → List[Class[_]](sRunnableGraphClass, jRunnableGraphClass)) :: + ("Source" -> List[Class[_]](sSourceClass, jSourceClass)) :: + ("SubSource" -> List[Class[_]](sSubSourceClass, jSubSourceClass)) :: + ("Flow" -> List[Class[_]](sFlowClass, jFlowClass)) :: + ("SubFlow" -> List[Class[_]](sSubFlowClass, jSubFlowClass)) :: + ("Sink" -> List[Class[_]](sSinkClass, jSinkClass)) :: + ("RunnableFlow" -> List[Class[_]](sRunnableGraphClass, jRunnableGraphClass)) :: Nil foreach { - case (element, classes) ⇒ + case (element, classes) => s"provide same $element transforming operators" in { val allOps = (for { - c ← classes - m ← c.getMethods + c <- classes + m <- c.getMethods if !Modifier.isStatic(m.getModifiers) if !ignore(m.getName) if !m.getName.contains("$") if !materializing(m) } yield m.getName).toSet - for (c ← classes; op ← allOps) + for (c <- classes; op <- allOps) assertHasMethod(c, op) } s"provide same $element materializing operators" in { val materializingOps = (for { - c ← classes - m ← c.getMethods + c <- classes + m <- c.getMethods if !Modifier.isStatic(m.getModifiers) if !ignore(m.getName) if !m.getName.contains("$") if materializing(m) } yield m.getName).toSet - for (c ← classes; op ← materializingOps) + for (c <- classes; op <- materializingOps) assertHasMethod(c, op) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/DslFactoriesConsistencySpec.scala b/akka-stream-tests/src/test/scala/akka/stream/DslFactoriesConsistencySpec.scala index a6ad3e4dd3..c9db03ead6 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/DslFactoriesConsistencySpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/DslFactoriesConsistencySpec.scala @@ -18,12 +18,12 @@ class DslFactoriesConsistencySpec extends WordSpec with Matchers { Set("adapt") // the scaladsl -> javadsl bridge val `scala -> java aliases` = - ("apply" → "create") :: - ("apply" → "of") :: - ("apply" → "from") :: - ("apply" → "fromGraph") :: - ("apply" → "fromIterator") :: - ("apply" → "fromFunctions") :: + ("apply" -> "create") :: + ("apply" -> "of") :: + ("apply" -> "from") :: + ("apply" -> "fromGraph") :: + ("apply" -> "fromIterator") :: + ("apply" -> "fromFunctions") :: Nil // format: OFF @@ -88,13 +88,13 @@ class DslFactoriesConsistencySpec extends WordSpec with Matchers { "Java DSL" must provide { testCases foreach { - case TestCase(name, Some(sClass), jClass, jFactoryOption) ⇒ + case TestCase(name, Some(sClass), jClass, jFactoryOption) => name which { s"allows creating the same ${name}s as Scala DSL" in { runSpec( getSMethods(sClass), jClass.toList.flatMap(getJMethods) ++ - jFactoryOption.toList.flatMap(f ⇒ getJMethods(f).map(unspecializeName andThen curryLikeJava))) + jFactoryOption.toList.flatMap(f => getJMethods(f).map(unspecializeName andThen curryLikeJava))) } } } @@ -108,28 +108,28 @@ class DslFactoriesConsistencySpec extends WordSpec with Matchers { private def toMethod(m: java.lang.reflect.Method): Method = Method(m.getName, List(m.getParameterTypes: _*), m.getReturnType, m.getDeclaringClass) - private case class Ignore(cls: Class[_] ⇒ Boolean, name: String ⇒ Boolean, parameters: Int ⇒ Boolean, paramTypes: List[Class[_]] ⇒ Boolean) + private case class Ignore(cls: Class[_] => Boolean, name: String => Boolean, parameters: Int => Boolean, paramTypes: List[Class[_]] => Boolean) private def ignore(m: Method): Boolean = { val ignores = Seq( // private scaladsl method Ignore(_ == akka.stream.scaladsl.Source.getClass, _ == "apply", _ == 1, _ == List(classOf[akka.stream.impl.SourceModule[_, _]])), // corresponding matches on java side would need to have Function23 - Ignore(_ == akka.stream.scaladsl.Source.getClass, _ == "apply", _ == 24, _ ⇒ true), - Ignore(_ == akka.stream.scaladsl.Flow.getClass, _ == "apply", _ == 24, _ ⇒ true), - Ignore(_ == akka.stream.scaladsl.Sink.getClass, _ == "apply", _ == 24, _ ⇒ true), - Ignore(_ == akka.stream.scaladsl.Sink.getClass, _ == "collection", _ ⇒ true, _ ⇒ true), - Ignore(_ == akka.stream.scaladsl.Sink.getClass, _ == "actorRef", _ ⇒ true, _ ⇒ true), // Internal in scaladsl - Ignore(_ == akka.stream.scaladsl.Sink.getClass, _ == "actorRefWithAck", _ ⇒ true, _ ⇒ true), // Internal in scaladsl - Ignore(_ == akka.stream.scaladsl.Source.getClass, _ == "actorRef", _ ⇒ true, _ ⇒ true), // Internal in scaladsl - Ignore(_ == akka.stream.scaladsl.BidiFlow.getClass, _ == "apply", _ == 24, _ ⇒ true), - Ignore(_ == akka.stream.scaladsl.GraphDSL.getClass, _ == "runnable", _ == 24, _ ⇒ true), - Ignore(_ == akka.stream.scaladsl.GraphDSL.getClass, _ == "create", _ == 24, _ ⇒ true), + Ignore(_ == akka.stream.scaladsl.Source.getClass, _ == "apply", _ == 24, _ => true), + Ignore(_ == akka.stream.scaladsl.Flow.getClass, _ == "apply", _ == 24, _ => true), + Ignore(_ == akka.stream.scaladsl.Sink.getClass, _ == "apply", _ == 24, _ => true), + Ignore(_ == akka.stream.scaladsl.Sink.getClass, _ == "collection", _ => true, _ => true), + Ignore(_ == akka.stream.scaladsl.Sink.getClass, _ == "actorRef", _ => true, _ => true), // Internal in scaladsl + Ignore(_ == akka.stream.scaladsl.Sink.getClass, _ == "actorRefWithAck", _ => true, _ => true), // Internal in scaladsl + Ignore(_ == akka.stream.scaladsl.Source.getClass, _ == "actorRef", _ => true, _ => true), // Internal in scaladsl + Ignore(_ == akka.stream.scaladsl.BidiFlow.getClass, _ == "apply", _ == 24, _ => true), + Ignore(_ == akka.stream.scaladsl.GraphDSL.getClass, _ == "runnable", _ == 24, _ => true), + Ignore(_ == akka.stream.scaladsl.GraphDSL.getClass, _ == "create", _ == 24, _ => true), // all generated methods like scaladsl.Sink$.akka$stream$scaladsl$Sink$$newOnCompleteStage$1 - Ignore(_ ⇒ true, _.contains("$"), _ ⇒ true, _ ⇒ true)) + Ignore(_ => true, _.contains("$"), _ => true, _ => true)) ignores.foldLeft(false) { - case (acc, i) ⇒ + case (acc, i) => acc || (i.cls(m.declaringClass) && i.name(m.name) && i.parameters(m.parameterTypes.length) && i.paramTypes(m.parameterTypes)) } } @@ -141,34 +141,34 @@ class DslFactoriesConsistencySpec extends WordSpec with Matchers { * createN => create */ private val unspecializeName: PartialFunction[Method, Method] = { - case m ⇒ m.copy(name = m.name.filter(Character.isLetter)) + case m => m.copy(name = m.name.filter(Character.isLetter)) } /** * Adapt java side non curried functions to scala side like */ private val curryLikeJava: PartialFunction[Method, Method] = { - case m if m.parameterTypes.size > 1 ⇒ + case m if m.parameterTypes.size > 1 => m.copy(name = m.name.filter(Character.isLetter), parameterTypes = m.parameterTypes.dropRight(1) :+ classOf[akka.japi.function.Function[_, _]]) - case m ⇒ m + case m => m } def runSpec(sMethods: List[Method], jMethods: List[Method]): Unit = { var warnings = 0 val results = for { - s ← sMethods - j ← jMethods + s <- sMethods + j <- jMethods } yield delegationCheck(s, j) for { - row ← results.groupBy(_.s) + row <- results.groupBy(_.s) matches = row._2.filter(_.matches) } { if (matches.length == 0) { warnings += 1 alert("No match for " + row._1) - row._2 foreach { m ⇒ alert(s" > ${m.j.toString}: ${m.reason}") } + row._2 foreach { m => alert(s" > ${m.j.toString}: ${m.reason}") } } else if (matches.length == 1) { info("Matched: Scala:" + row._1.name + "(" + row._1.parameterTypes.map(_.getName).mkString(",") + "): " + returnTypeString(row._1) + " == " + @@ -176,13 +176,13 @@ class DslFactoriesConsistencySpec extends WordSpec with Matchers { } else { warnings += 1 alert("Multiple matches for " + row._1 + "!") - matches foreach { m ⇒ alert(s" > ${m.j.toString}") } + matches foreach { m => alert(s" > ${m.j.toString}") } } } if (warnings > 0) { - jMethods foreach { m ⇒ info(" java: " + m + ": " + returnTypeString(m)) } - sMethods foreach { m ⇒ info(" scala: " + m + ": " + returnTypeString(m)) } + jMethods foreach { m => info(" java: " + m + ": " + returnTypeString(m)) } + sMethods foreach { m => info(" scala: " + m + ": " + returnTypeString(m)) } fail("Warnings were issued! Fix name / type mappings or delegation code!") } } @@ -220,9 +220,9 @@ class DslFactoriesConsistencySpec extends WordSpec with Matchers { def nameMatch(scalaName: String, javaName: String): Boolean = (scalaName, javaName) match { - case (s, j) if s == j ⇒ true - case t if `scala -> java aliases` contains t ⇒ true - case t ⇒ false + case (s, j) if s == j => true + case t if `scala -> java aliases` contains t => true + case t => false } /** @@ -238,9 +238,9 @@ class DslFactoriesConsistencySpec extends WordSpec with Matchers { def typeMatch(scalaParams: List[Class[_]], javaParams: List[Class[_]]): Boolean = (scalaParams.toList, javaParams.toList) match { - case (s, j) if s == j ⇒ true - case (s, j) if s.zip(j).forall(typeMatch) ⇒ true - case _ ⇒ false + case (s, j) if s == j => true + case (s, j) if s.zip(j).forall(typeMatch) => true + case _ => false } def typeMatch(p: (Class[_], Class[_])): Boolean = diff --git a/akka-stream-tests/src/test/scala/akka/stream/FusingSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/FusingSpec.scala index 32fb510309..c112a939f2 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/FusingSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/FusingSpec.scala @@ -16,7 +16,7 @@ class FusingSpec extends StreamSpec { GraphInterpreter.currentInterpreter.context } - val snitchFlow = Flow[Int].map(x ⇒ { testActor ! actorRunningStage; x }).async + val snitchFlow = Flow[Int].map(x => { testActor ! actorRunningStage; x }).async "SubFusingActorMaterializer" must { @@ -24,7 +24,7 @@ class FusingSpec extends StreamSpec { val async = Flow[Int].map(_ * 2).async Source(0 to 9) .map(_ * 10) - .flatMapMerge(5, i ⇒ Source(i to (i + 9)).via(async)) + .flatMapMerge(5, i => Source(i to (i + 9)).via(async)) .grouped(1000) .runWith(Sink.head) .futureValue @@ -32,10 +32,10 @@ class FusingSpec extends StreamSpec { } "use multiple actors when there are asynchronous boundaries in the subflows (manual)" in { - val async = Flow[Int].map(x ⇒ { testActor ! actorRunningStage; x }).async + val async = Flow[Int].map(x => { testActor ! actorRunningStage; x }).async Source(0 to 9) .via(snitchFlow.async) - .flatMapMerge(5, i ⇒ Source.single(i).via(async)) + .flatMapMerge(5, i => Source.single(i).via(async)) .grouped(1000) .runWith(Sink.head) .futureValue @@ -47,7 +47,7 @@ class FusingSpec extends StreamSpec { "use multiple actors when there are asynchronous boundaries in the subflows (operator)" in { Source(0 to 9) .via(snitchFlow) - .flatMapMerge(5, i ⇒ Source.single(i).via(snitchFlow.async)) + .flatMapMerge(5, i => Source.single(i).via(snitchFlow.async)) .grouped(1000) .runWith(Sink.head) .futureValue diff --git a/akka-stream-tests/src/test/scala/akka/stream/actor/ActorPublisherSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/actor/ActorPublisherSpec.scala index 3748148e13..54102bf574 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/actor/ActorPublisherSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/actor/ActorPublisherSpec.scala @@ -50,14 +50,14 @@ object ActorPublisherSpec { import akka.stream.actor.ActorPublisherMessage._ def receive = { - case Request(element) ⇒ probe ! TotalDemand(totalDemand) - case Produce(elem) ⇒ onNext(elem) - case Err(reason) ⇒ onError(new RuntimeException(reason) with NoStackTrace) - case ErrThenStop(reason) ⇒ onErrorThenStop(new RuntimeException(reason) with NoStackTrace) - case Complete ⇒ onComplete() - case CompleteThenStop ⇒ onCompleteThenStop() - case Boom ⇒ throw new RuntimeException("boom") with NoStackTrace - case ThreadName ⇒ probe ! Thread.currentThread.getName + case Request(element) => probe ! TotalDemand(totalDemand) + case Produce(elem) => onNext(elem) + case Err(reason) => onError(new RuntimeException(reason) with NoStackTrace) + case ErrThenStop(reason) => onErrorThenStop(new RuntimeException(reason) with NoStackTrace) + case Complete => onComplete() + case CompleteThenStop => onCompleteThenStop() + case Boom => throw new RuntimeException("boom") with NoStackTrace + case ThreadName => probe ! Thread.currentThread.getName } } @@ -66,10 +66,10 @@ object ActorPublisherSpec { override def receive = stashing def stashing: Receive = { - case "unstash" ⇒ + case "unstash" => unstashAll() context.become(super.receive) - case _ ⇒ stash() + case _ => stash() } } @@ -82,16 +82,16 @@ object ActorPublisherSpec { var buf = Vector.empty[Int] def receive = { - case i: Int ⇒ + case i: Int => if (buf.isEmpty && totalDemand > 0) onNext(i) else { buf :+= i deliverBuf() } - case Request(_) ⇒ + case Request(_) => deliverBuf() - case Cancel ⇒ + case Cancel => context.stop(self) } @@ -121,9 +121,9 @@ object ActorPublisherSpec { override def subscriptionTimeout = timeout override def receive: Receive = { - case Request(_) ⇒ + case Request(_) => onNext(1) - case SubscriptionTimeoutExceeded ⇒ + case SubscriptionTimeoutExceeded => probe ! "timed-out" context.system.scheduler.scheduleOnce(timeout, probe, "cleaned-up") context.system.scheduler.scheduleOnce(timeout, self, PoisonPill) @@ -139,7 +139,7 @@ object ActorPublisherSpec { override val requestStrategy = WatermarkRequestStrategy(10) def receive = { - case OnNext(s: String) ⇒ + case OnNext(s: String) => probe ! s } } @@ -351,18 +351,18 @@ class ActorPublisherSpec extends StreamSpec(ActorPublisherSpec.config) with Impl val sink: Sink[String, ActorRef] = Sink.actorSubscriber(receiverProps(probe.ref)) val (snd, rcv) = source.collect { - case n if n % 2 == 0 ⇒ "elem-" + n + case n if n % 2 == 0 => "elem-" + n }.toMat(sink)(Keep.both).run() (1 to 3) foreach { snd ! _ } probe.expectMsg("elem-2") - (4 to 500) foreach { n ⇒ + (4 to 500) foreach { n => if (n % 19 == 0) Thread.sleep(50) // simulate bursts snd ! n } - (4 to 500 by 2) foreach { n ⇒ probe.expectMsg("elem-" + n) } + (4 to 500 by 2) foreach { n => probe.expectMsg("elem-" + n) } watch(snd) rcv ! PoisonPill @@ -381,7 +381,7 @@ class ActorPublisherSpec extends StreamSpec(ActorPublisherSpec.config) with Impl val sink1 = Sink.fromSubscriber(ActorSubscriber[String](system.actorOf(receiverProps(probe1.ref)))) val sink2: Sink[String, ActorRef] = Sink.actorSubscriber(receiverProps(probe2.ref)) - val senderRef2 = RunnableGraph.fromGraph(GraphDSL.create(Source.actorPublisher[Int](senderProps)) { implicit b ⇒ source2 ⇒ + val senderRef2 = RunnableGraph.fromGraph(GraphDSL.create(Source.actorPublisher[Int](senderProps)) { implicit b => source2 => import GraphDSL.Implicits._ val merge = b.add(Merge[Int](2)) @@ -402,7 +402,7 @@ class ActorPublisherSpec extends StreamSpec(ActorPublisherSpec.config) with Impl senderRef2 ! _ } - (0 to 10).foreach { msg ⇒ + (0 to 10).foreach { msg => probe1.expectMsg(msg.toString + "mark") probe2.expectMsg(msg.toString) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/actor/ActorSubscriberSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/actor/ActorSubscriberSpec.scala index 94f49869bc..3374b4b733 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/actor/ActorSubscriberSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/actor/ActorSubscriberSpec.scala @@ -26,13 +26,13 @@ object ActorSubscriberSpec { override val requestStrategy = ZeroRequestStrategy def receive = { - case next @ OnNext(elem) ⇒ probe ! next - case OnComplete ⇒ probe ! OnComplete - case err @ OnError(cause) ⇒ probe ! err - case "ready" ⇒ request(elements = 2) - case "boom" ⇒ throw new RuntimeException("boom") with NoStackTrace - case "requestAndCancel" ⇒ { request(1); cancel() } - case "cancel" ⇒ cancel() + case next @ OnNext(elem) => probe ! next + case OnComplete => probe ! OnComplete + case err @ OnError(cause) => probe ! err + case "ready" => request(elements = 2) + case "boom" => throw new RuntimeException("boom") with NoStackTrace + case "requestAndCancel" => { request(1); cancel() } + case "cancel" => cancel() } } @@ -56,8 +56,8 @@ object ActorSubscriberSpec { override val requestStrategy = strat def receive = { - case next @ OnNext(elem) ⇒ probe ! next - case OnComplete ⇒ probe ! OnComplete + case next @ OnNext(elem) => probe ! next + case OnComplete => probe ! OnComplete } } @@ -85,11 +85,11 @@ object ActorSubscriberSpec { } def receive = { - case OnNext(Msg(id, replyTo)) ⇒ - queue += (id → replyTo) + case OnNext(Msg(id, replyTo)) => + queue += (id -> replyTo) assert(queue.size <= 10, s"queued too many: ${queue.size}") router.route(Work(id), self) - case Reply(id) ⇒ + case Reply(id) => queue(id) ! Done(id) queue -= id } @@ -97,7 +97,7 @@ object ActorSubscriberSpec { class Worker extends Actor { def receive = { - case Work(id) ⇒ + case Work(id) => // ... sender() ! Reply(id) } @@ -126,7 +126,7 @@ class ActorSubscriberSpec extends StreamSpec with ImplicitSender { "signal error" in { val e = new RuntimeException("simulated") with NoStackTrace - val ref = Source.fromIterator(() ⇒ throw e).runWith(Sink.actorSubscriber(manualSubscriberProps(testActor))) + val ref = Source.fromIterator(() => throw e).runWith(Sink.actorSubscriber(manualSubscriberProps(testActor))) ref ! "ready" expectMsg(OnError(e)) } @@ -143,7 +143,7 @@ class ActorSubscriberSpec extends StreamSpec with ImplicitSender { ref ! "ready" ref ! "ready" ref ! "boom" - (3 to 6) foreach { n ⇒ expectMsg(OnNext(n)) } + (3 to 6) foreach { n => expectMsg(OnNext(n)) } expectNoMsg(200.millis) ref ! "ready" expectMsg(OnNext(7)) @@ -182,13 +182,13 @@ class ActorSubscriberSpec extends StreamSpec with ImplicitSender { "work with OneByOneRequestStrategy" in { Source(1 to 17).runWith(Sink.actorSubscriber(requestStrategySubscriberProps(testActor, OneByOneRequestStrategy))) - for (n ← 1 to 17) expectMsg(OnNext(n)) + for (n <- 1 to 17) expectMsg(OnNext(n)) expectMsg(OnComplete) } "work with WatermarkRequestStrategy" in { Source(1 to 17).runWith(Sink.actorSubscriber(requestStrategySubscriberProps(testActor, WatermarkRequestStrategy(highWatermark = 10)))) - for (n ← 1 to 17) expectMsg(OnNext(n)) + for (n <- 1 to 17) expectMsg(OnNext(n)) expectMsg(OnComplete) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/extra/FlowTimedSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/extra/FlowTimedSpec.scala index d0397315f4..a140c54649 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/extra/FlowTimedSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/extra/FlowTimedSpec.scala @@ -29,7 +29,7 @@ class FlowTimedSpec extends StreamSpec with ScriptedTest { val testActor = TestProbe() val measureBetweenEvery = 5 - val printInfo = (interval: Duration) ⇒ { + val printInfo = (interval: Duration) => { testActor.ref ! interval info(s"Measured interval between $measureBetweenEvery elements was: $interval") } @@ -37,34 +37,34 @@ class FlowTimedSpec extends StreamSpec with ScriptedTest { val n = 20 val testRuns = 1 to 2 - def script = Script((1 to n) map { x ⇒ Seq(x) → Seq(x) }: _*) - testRuns foreach (_ ⇒ runScript(script, settings) { flow ⇒ + def script = Script((1 to n) map { x => Seq(x) -> Seq(x) }: _*) + testRuns foreach (_ => runScript(script, settings) { flow => flow. map(identity). timedIntervalBetween(_ % measureBetweenEvery == 0, onInterval = printInfo) }) val expectedNrOfOnIntervalCalls = testRuns.size * ((n / measureBetweenEvery) - 1) // first time has no value to compare to, so skips calling onInterval - 1 to expectedNrOfOnIntervalCalls foreach { _ ⇒ testActor.expectMsgType[Duration] } + 1 to expectedNrOfOnIntervalCalls foreach { _ => testActor.expectMsgType[Duration] } } "measure time it takes from start to complete, by wrapping operations" in { val testActor = TestProbe() val n = 50 - val printInfo = (d: FiniteDuration) ⇒ { + val printInfo = (d: FiniteDuration) => { testActor.ref ! d info(s"Processing $n elements took $d") } val testRuns = 1 to 3 - def script = Script((1 to n) map { x ⇒ Seq(x) → Seq(x) }: _*) - testRuns foreach (_ ⇒ runScript(script, settings) { flow ⇒ + def script = Script((1 to n) map { x => Seq(x) -> Seq(x) }: _*) + testRuns foreach (_ => runScript(script, settings) { flow => flow.timed(_.map(identity), onComplete = printInfo) }) - testRuns foreach { _ ⇒ testActor.expectMsgType[Duration] } + testRuns foreach { _ => testActor.expectMsgType[Duration] } testActor.expectNoMsg(1.second) } @@ -77,7 +77,7 @@ class FlowTimedSpec extends StreamSpec with ScriptedTest { "measure time it between elements matching a predicate" in assertAllStagesStopped { val probe = TestProbe() - val flow: Flow[Int, Long, _] = Flow[Int].map(_.toLong).timedIntervalBetween(in ⇒ in % 2 == 1, d ⇒ probe.ref ! d) + val flow: Flow[Int, Long, _] = Flow[Int].map(_.toLong).timedIntervalBetween(in => in % 2 == 1, d => probe.ref ! d) val c1 = TestSubscriber.manualProbe[Long]() Source(List(1, 2, 3)).via(flow).runWith(Sink.fromSubscriber(c1)) @@ -102,8 +102,8 @@ class FlowTimedSpec extends StreamSpec with ScriptedTest { timed(_. map(_.toDouble). map(_.toInt). - map(_.toString), duration ⇒ probe.ref ! duration). - map { s: String ⇒ s + "!" } + map(_.toString), duration => probe.ref ! duration). + map { s: String => s + "!" } val (flowIn: Subscriber[Int], flowOut: Publisher[String]) = flow.runWith(Source.asSubscriber[Int], Sink.asPublisher[String](false)) @@ -115,7 +115,7 @@ class FlowTimedSpec extends StreamSpec with ScriptedTest { val s = c1.expectSubscription() s.request(200) - 0 to 100 foreach { i ⇒ c1.expectNext(i.toString + "!") } + 0 to 100 foreach { i => c1.expectNext(i.toString + "!") } c1.expectComplete() val duration = probe.expectMsgType[Duration] diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/FixedBufferSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/FixedBufferSpec.scala index 96127a179f..ec1154bb5c 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/FixedBufferSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/FixedBufferSpec.scala @@ -9,7 +9,7 @@ import akka.stream.ActorMaterializerSettings class FixedBufferSpec extends StreamSpec { - for (size ← List(1, 3, 4)) { + for (size <- List(1, 3, 4)) { s"FixedSizeBuffer of size $size" must { @@ -28,7 +28,7 @@ class FixedBufferSpec extends StreamSpec { "become full after size elements are enqueued" in { val buf = FixedSizeBuffer[String](size) - for (_ ← 1 to size) buf.enqueue("test") + for (_ <- 1 to size) buf.enqueue("test") buf.isEmpty should be(false) buf.isFull should be(true) } @@ -51,21 +51,21 @@ class FixedBufferSpec extends StreamSpec { "drop head properly" in { val buf = FixedSizeBuffer[Int](size) - for (elem ← 1 to size) buf.enqueue(elem) + for (elem <- 1 to size) buf.enqueue(elem) buf.dropHead() - for (elem ← 2 to size) buf.dequeue() should be(elem) + for (elem <- 2 to size) buf.dequeue() should be(elem) } "drop tail properly" in { val buf = FixedSizeBuffer[Int](size) - for (elem ← 1 to size) buf.enqueue(elem) + for (elem <- 1 to size) buf.enqueue(elem) buf.dropTail() - for (elem ← 1 to size - 1) buf.dequeue() should be(elem) + for (elem <- 1 to size - 1) buf.dequeue() should be(elem) } "become non-full after tail dropped from full buffer" in { val buf = FixedSizeBuffer[String](size) - for (_ ← 1 to size) buf.enqueue("test") + for (_ <- 1 to size) buf.enqueue("test") buf.dropTail() buf.isEmpty should be(size == 1) buf.isFull should be(false) @@ -73,7 +73,7 @@ class FixedBufferSpec extends StreamSpec { "become non-full after head dropped from full buffer" in { val buf = FixedSizeBuffer[String](size) - for (_ ← 1 to size) buf.enqueue("test") + for (_ <- 1 to size) buf.enqueue("test") buf.dropHead() buf.isEmpty should be(size == 1) buf.isFull should be(false) @@ -82,13 +82,13 @@ class FixedBufferSpec extends StreamSpec { "work properly with full-range filling/draining cycles" in { val buf = FixedSizeBuffer[Int](size) - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { buf.isEmpty should be(true) buf.isFull should be(false) - for (elem ← 1 to size) buf.enqueue(elem) + for (elem <- 1 to size) buf.enqueue(elem) buf.isEmpty should be(false) buf.isFull should be(true) - for (elem ← 1 to size) buf.dequeue() should be(elem) + for (elem <- 1 to size) buf.dequeue() should be(elem) } } @@ -100,13 +100,13 @@ class FixedBufferSpec extends StreamSpec { cheat.readIdx_=(Int.MaxValue) cheat.writeIdx_=(Int.MaxValue) - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { buf.isEmpty should be(true) buf.isFull should be(false) - for (elem ← 1 to size) buf.enqueue(elem) + for (elem <- 1 to size) buf.enqueue(elem) buf.isEmpty should be(false) buf.isFull should be(true) - for (elem ← 1 to size) buf.dequeue() should be(elem) + for (elem <- 1 to size) buf.dequeue() should be(elem) } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/GraphStageLogicSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/GraphStageLogicSpec.scala index a811a87ba4..185b5603ef 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/GraphStageLogicSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/GraphStageLogicSpec.scala @@ -29,8 +29,8 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S setHandler(in, eagerTerminateInput) setHandler(out, eagerTerminateOutput) override def preStart(): Unit = { - emit(out, 1, () ⇒ emit(out, 2)) - emit(out, 3, () ⇒ emit(out, 4)) + emit(out, 1, () => emit(out, 2)) + emit(out, 3, () => emit(out, 4)) } } } @@ -66,8 +66,8 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S setHandler(in, new InHandler { override def onPush(): Unit = push(out, grab(in)) override def onUpstreamFinish(): Unit = { - emit(out, 5, () ⇒ emit(out, 6)) - emit(out, 7, () ⇒ emit(out, 8)) + emit(out, 5, () => emit(out, 6)) + emit(out, 7, () => emit(out, 8)) completeStage() } }) @@ -102,7 +102,7 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) { setHandler(out, new OutHandler { - override def onPull(): Unit = emitMultiple(out, Iterator.empty, () ⇒ emit(out, 42, () ⇒ completeStage())) + override def onPull(): Unit = emitMultiple(out, Iterator.empty, () => emit(out, 42, () => completeStage())) }) } override def toString = "GraphStageLogicSpec.emitEmptyIterable" @@ -115,7 +115,7 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S new GraphStageLogic(shape) { setHandler(shape.in, EagerTerminateInput) setHandler(shape.out, EagerTerminateOutput) - override def preStart(): Unit = readN(shape.in, n)(e ⇒ emitMultiple(shape.out, e.iterator, () ⇒ completeStage()), (_) ⇒ ()) + override def preStart(): Unit = readN(shape.in, n)(e => emitMultiple(shape.out, e.iterator, () => completeStage()), (_) => ()) } } @@ -128,8 +128,8 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S setHandler(shape.out, EagerTerminateOutput) override def preStart(): Unit = readN(shape.in, n)( - _ ⇒ failStage(new IllegalStateException("Shouldn't happen!")), - e ⇒ emitMultiple(shape.out, e.iterator, () ⇒ completeStage())) + _ => failStage(new IllegalStateException("Shouldn't happen!")), + e => emitMultiple(shape.out, e.iterator, () => completeStage())) } } @@ -150,7 +150,7 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S "read N should not emit if upstream fails before N is sent" in assertAllStagesStopped { val error = new IllegalArgumentException("Don't argue like that!") - Source(1 to 5).map(x ⇒ if (x > 3) throw error else x).via(ReadNEmitN(6)).runWith(TestSink.probe) + Source(1 to 5).map(x => if (x > 3) throw error else x).via(ReadNEmitN(6)).runWith(TestSink.probe) .request(10) .expectError(error) } @@ -300,7 +300,7 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S override def toString = "stage-name" }) // just to have another graphstage downstream - .map(_ ⇒ "whatever") + .map(_ => "whatever") .runWith(Sink.ignore) } ex.getMessage should startWith("No handler defined in stage [stage-name] for out port [out") diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/LinearTraversalBuilderSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/LinearTraversalBuilderSpec.scala index cb4d07d0de..6cfae289f4 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/LinearTraversalBuilderSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/LinearTraversalBuilderSpec.scala @@ -427,7 +427,7 @@ class LinearTraversalBuilderSpec extends AkkaSpec { "keep mapped materialized value of empty builder" in { val builder = LinearTraversalBuilder.empty() - .transformMat((_: Any) ⇒ "NOTUSED") + .transformMat((_: Any) => "NOTUSED") .append(source.traversalBuilder, source.shape, Keep.left) .append(sink.traversalBuilder, sink.shape, Keep.left) @@ -585,8 +585,8 @@ class LinearTraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - sink → (Attributes.name("test") and Attributes.name("testSink")), - source → (Attributes.name("test") and Attributes.name("testSource")) + sink -> (Attributes.name("test") and Attributes.name("testSink")), + source -> (Attributes.name("test") and Attributes.name("testSource")) )) } @@ -599,8 +599,8 @@ class LinearTraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - sink → (Attributes.name("test") and Attributes.name("testSink")), - source → (Attributes.name("test") and Attributes.name("source")) + sink -> (Attributes.name("test") and Attributes.name("testSink")), + source -> (Attributes.name("test") and Attributes.name("source")) )) } @@ -615,8 +615,8 @@ class LinearTraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - sink → (Attributes.name("test2") and Attributes.name("testSink")), - source → (Attributes.name("test2") and Attributes.name("source2")) + sink -> (Attributes.name("test2") and Attributes.name("testSink")), + source -> (Attributes.name("test2") and Attributes.name("source2")) )) } @@ -630,8 +630,8 @@ class LinearTraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - sink → (Attributes.name("test") and Attributes.name("sink")), - source → (Attributes.name("test") and Attributes.name("source")) + sink -> (Attributes.name("test") and Attributes.name("sink")), + source -> (Attributes.name("test") and Attributes.name("source")) )) } @@ -647,9 +647,9 @@ class LinearTraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - sink → (Attributes.name("test") and Attributes.name("sink")), - flow1 → (Attributes.name("test") and Attributes.name("compositeSource") and Attributes.name("flow")), - source → (Attributes.name("test") and Attributes.name("compositeSource") and Attributes.name("source")) + sink -> (Attributes.name("test") and Attributes.name("sink")), + flow1 -> (Attributes.name("test") and Attributes.name("compositeSource") and Attributes.name("flow")), + source -> (Attributes.name("test") and Attributes.name("compositeSource") and Attributes.name("source")) )) } @@ -664,9 +664,9 @@ class LinearTraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - compositeSink → (Attributes.name("test") and Attributes.name("sink")), - flow1 → (Attributes.name("test") and Attributes.name("flow")), - source → (Attributes.name("test") and Attributes.name("source")) + compositeSink -> (Attributes.name("test") and Attributes.name("sink")), + flow1 -> (Attributes.name("test") and Attributes.name("flow")), + source -> (Attributes.name("test") and Attributes.name("source")) )) } @@ -686,9 +686,9 @@ class LinearTraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - sink → (Attributes.name("test") and Attributes.name("sink")), - flow1 → (Attributes.name("test") and Attributes.name("flow")), - compositeSource → (Attributes.name("test") and Attributes.name("source-outer") and Attributes.name("source")) + sink -> (Attributes.name("test") and Attributes.name("sink")), + flow1 -> (Attributes.name("test") and Attributes.name("flow")), + compositeSource -> (Attributes.name("test") and Attributes.name("source-outer") and Attributes.name("source")) )) } @@ -703,9 +703,9 @@ class LinearTraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - sink → (Attributes.name("test") and Attributes.name("sink")), - compositeFlow1 → (Attributes.name("test") and Attributes.name("flow")), - source → (Attributes.name("test") and Attributes.name("source")) + sink -> (Attributes.name("test") and Attributes.name("sink")), + compositeFlow1 -> (Attributes.name("test") and Attributes.name("flow")), + source -> (Attributes.name("test") and Attributes.name("source")) )) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/ResizableMultiReaderRingBufferSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/ResizableMultiReaderRingBufferSpec.scala index 9216d06b8a..86afed03d0 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/ResizableMultiReaderRingBufferSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/ResizableMultiReaderRingBufferSpec.scala @@ -124,7 +124,7 @@ class ResizableMultiReaderRingBufferSpec extends WordSpec with Matchers { val COUNTER_LIMIT = 200 val LOG = false val sb = new java.lang.StringBuilder - def log(s: ⇒ String): Unit = if (LOG) sb.append(s) + def log(s: => String): Unit = if (LOG) sb.append(s) class StressTestCursor(cursorNr: Int, run: Int) extends Cursor { var cursor: Int = _ @@ -143,7 +143,7 @@ class ResizableMultiReaderRingBufferSpec extends WordSpec with Matchers { counter += 1 counter == COUNTER_LIMIT } catch { - case NothingToReadException ⇒ log("FAILED\n"); false // ok, we currently can't read, try again later + case NothingToReadException => log("FAILED\n"); false // ok, we currently can't read, try again later } } override def toString: String = s"cursorNr $cursorNr, ix $cursor, counter $counter" @@ -151,8 +151,8 @@ class ResizableMultiReaderRingBufferSpec extends WordSpec with Matchers { val random = new Random for { - bit ← 1 to MAXSIZEBIT_LIMIT - n ← 1 to 2 + bit <- 1 to MAXSIZEBIT_LIMIT + n <- 1 to 2 } { var counter = 1 var activeCursors = List.tabulate(random.nextInt(8) + 1)(new StressTestCursor(_, 1 << bit)) @@ -184,12 +184,12 @@ class ResizableMultiReaderRingBufferSpec extends WordSpec with Matchers { class TestBuffer(iSize: Int, mSize: Int, cursors: Cursors) extends ResizableMultiReaderRingBuffer[Int](iSize, mSize, cursors) { def inspect: String = - underlyingArray.map(x ⇒ if (x == null) 0 else x).mkString("", " ", " " + toString.dropWhile(_ != '(')) + underlyingArray.map(x => if (x == null) 0 else x).mkString("", " ", " " + toString.dropWhile(_ != '(')) } class Test(iSize: Int, mSize: Int, cursorCount: Int) extends TestBuffer(iSize, mSize, new SimpleCursors(cursorCount)) { def read(cursorIx: Int): Integer = - try read(cursors.cursors(cursorIx)) catch { case NothingToReadException ⇒ null } + try read(cursors.cursors(cursorIx)) catch { case NothingToReadException => null } } class SimpleCursors(cursorCount: Int) extends Cursors { diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/TimeoutsSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/TimeoutsSpec.scala index 16b2b90a91..13db3179cc 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/TimeoutsSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/TimeoutsSpec.scala @@ -121,7 +121,7 @@ class TimeoutsSpec extends StreamSpec { // Two seconds in overall, but won't timeout until time between elements is large enough // (i.e. this works differently from completionTimeout) - for (_ ← 1 to 4) { + for (_ <- 1 to 4) { upstreamProbe.sendNext(1) downstreamProbe.requestNext(1) downstreamProbe.expectNoMsg(500.millis) // No timeout yet @@ -146,7 +146,7 @@ class TimeoutsSpec extends StreamSpec { .backpressureTimeout(1.second) .runWith(Sink.fromSubscriber(subscriber)) - for (i ← 1 to 3) { + for (i <- 1 to 3) { subscriber.requestNext(i) subscriber.expectNoMsg(250.millis) } @@ -288,7 +288,7 @@ class TimeoutsSpec extends StreamSpec { val downWrite = TestPublisher.probe[Int]() val downRead = TestSubscriber.probe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val timeoutStage = b.add(BidiFlow.bidirectionalIdleTimeout[String, Int](2.seconds)) Source.fromPublisher(upWrite) ~> timeoutStage.in1 @@ -336,7 +336,7 @@ class TimeoutsSpec extends StreamSpec { val downWrite = TestPublisher.probe[Int]() val downRead = TestSubscriber.probe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val timeoutStage = b.add(BidiFlow.bidirectionalIdleTimeout[String, Int](2.seconds)) Source.fromPublisher(upWrite) ~> timeoutStage.in1 diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/TraversalBuilderSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/TraversalBuilderSpec.scala index f64c9bc567..47a7b6eeea 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/TraversalBuilderSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/TraversalBuilderSpec.scala @@ -237,7 +237,7 @@ class TraversalBuilderSpec extends AkkaSpec { "keep mapped materialized value of empty builder" in { val builder = TraversalBuilder.empty() - .transformMat((_: Any) ⇒ "NOTUSED") + .transformMat((_: Any) => "NOTUSED") .add(source.traversalBuilder, source.shape, Keep.left) .add(sink.traversalBuilder, sink.shape, Keep.left) .wire(source.out, sink.in) @@ -368,8 +368,8 @@ class TraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - source → (Attributes.name("test") and Attributes.name("testSource")), - sink → (Attributes.name("test") and Attributes.name("testSink")) + source -> (Attributes.name("test") and Attributes.name("testSource")), + sink -> (Attributes.name("test") and Attributes.name("testSink")) )) } @@ -389,8 +389,8 @@ class TraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - source → (Attributes.name("outer2") and Attributes.name("test2") and Attributes.name("testSource")), - sink → (Attributes.name("outer2") and Attributes.name("test2") and Attributes.name("testSinkB")) + source -> (Attributes.name("outer2") and Attributes.name("test2") and Attributes.name("testSource")), + sink -> (Attributes.name("outer2") and Attributes.name("test2") and Attributes.name("testSinkB")) )) } @@ -409,9 +409,9 @@ class TraversalBuilderSpec extends AkkaSpec { val mat = testMaterialize(builder) mat.attributesAssignments should ===(List( - source → (Attributes.name("test") and Attributes.name("testSource")), - flow1 → (Attributes.name("test") and Attributes.name("flow")), - sink → (Attributes.name("test") and Attributes.name("testSink")) + source -> (Attributes.name("test") and Attributes.name("testSource")), + flow1 -> (Attributes.name("test") and Attributes.name("flow")), + sink -> (Attributes.name("test") and Attributes.name("testSink")) )) } @@ -532,8 +532,8 @@ class TraversalBuilderSpec extends AkkaSpec { "bidiflow1" in { implicit val mat = PhasedFusingActorMaterializer() - val flow1 = Flow.fromGraph(fusing.Map((x: Int) ⇒ x + 1)) - val flow2 = Flow.fromGraph(fusing.Map((x: Int) ⇒ x + 1)) + val flow1 = Flow.fromGraph(fusing.Map((x: Int) => x + 1)) + val flow2 = Flow.fromGraph(fusing.Map((x: Int) => x + 1)) val bidi = BidiFlow.fromFlowsMat(flow1, flow2)(Keep.none) @@ -544,8 +544,8 @@ class TraversalBuilderSpec extends AkkaSpec { "bidiflow reverse" in { implicit val mat = PhasedFusingActorMaterializer() - val flow1 = Flow.fromGraph(new fusing.Map((x: Int) ⇒ x + 1)) - val flow2 = Flow.fromGraph(new fusing.Map((x: Int) ⇒ x + 1)) + val flow1 = Flow.fromGraph(new fusing.Map((x: Int) => x + 1)) + val flow2 = Flow.fromGraph(new fusing.Map((x: Int) => x + 1)) val bidi = BidiFlow.fromFlowsMat(flow1, flow2)(Keep.none) diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/TraversalTestUtils.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/TraversalTestUtils.scala index e10cbb724c..1efdbbea9b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/TraversalTestUtils.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/TraversalTestUtils.scala @@ -121,7 +121,7 @@ object TraversalTestUtils { var nextStep: Traversal = EmptyTraversal current match { - case MaterializeAtomic(mod, outToSlot) ⇒ + case MaterializeAtomic(mod, outToSlot) => var i = 0 val inletsIter = mod.shape.inlets.iterator while (inletsIter.hasNext) { @@ -137,37 +137,37 @@ object TraversalTestUtils { } // Recording attributes assignment results for testing purposes - attributesResult = (mod → attributesStack.getLast) :: attributesResult + attributesResult = (mod -> attributesStack.getLast) :: attributesResult islandsResult = (mod, islandStack.head._2, islandStack.head._1) :: islandsResult // Dummy materialized value is simply the name of the module matValueStack.addLast(mod.toString) inOffs += mod.shape.inlets.size - case Pop ⇒ + case Pop => matValueStack.removeLast() - case PushNotUsed ⇒ + case PushNotUsed => matValueStack.addLast(NotUsed) - case transform: Transform ⇒ + case transform: Transform => val prev = matValueStack.removeLast() val result = transform(prev) matValueStack.addLast(result) - case compose: Compose ⇒ + case compose: Compose => val second = matValueStack.removeLast() val first = matValueStack.removeLast() val result = compose(first, second) matValueStack.addLast(result) - case PushAttributes(attr) ⇒ + case PushAttributes(attr) => attributesStack.addLast(attributesStack.getLast and attr) - case PopAttributes ⇒ + case PopAttributes => attributesStack.removeLast() - case Concat(first, next) ⇒ + case Concat(first, next) => if (next ne EmptyTraversal) traversalStack.add(next) nextStep = first - case EnterIsland(tag) ⇒ + case EnterIsland(tag) => islandStack = (tag, attributesStack.getLast) :: islandStack - case ExitIsland ⇒ + case ExitIsland => islandStack = islandStack.tail - case _ ⇒ + case _ => } current = nextStep diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/ActorGraphInterpreterSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/ActorGraphInterpreterSpec.scala index ab7bf985c5..fc11f83681 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/ActorGraphInterpreterSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/ActorGraphInterpreterSpec.scala @@ -81,7 +81,7 @@ class ActorGraphInterpreterSpec extends StreamSpec { override def toString = "IdentityBidi" } - val identity = BidiFlow.fromGraph(identityBidi).join(Flow[Int].map { x ⇒ x }) + val identity = BidiFlow.fromGraph(identityBidi).join(Flow[Int].map { x => x }) Await.result( Source(1 to 10).via(identity).grouped(100).runWith(Sink.head), @@ -127,7 +127,7 @@ class ActorGraphInterpreterSpec extends StreamSpec { } val identityBidiF = BidiFlow.fromGraph(identityBidi) - val identity = (identityBidiF atop identityBidiF atop identityBidiF).join(Flow[Int].map { x ⇒ x }) + val identity = (identityBidiF atop identityBidiF atop identityBidiF).join(Flow[Int].map { x => x }) Await.result( Source(1 to 10).via(identity).grouped(100).runWith(Sink.head), @@ -173,7 +173,7 @@ class ActorGraphInterpreterSpec extends StreamSpec { } val identityBidiF = BidiFlow.fromGraph(identityBidi) - val identity = (identityBidiF atop identityBidiF atop identityBidiF).join(Flow[Int].map { x ⇒ x }) + val identity = (identityBidiF atop identityBidiF atop identityBidiF).join(Flow[Int].map { x => x }) Await.result( Source(1 to 10).via(identity).grouped(100).runWith(Sink.head), @@ -223,7 +223,7 @@ class ActorGraphInterpreterSpec extends StreamSpec { val takeAll = Flow[Int].grouped(200).toMat(Sink.head)(Keep.right) - val (f1, f2) = RunnableGraph.fromGraph(GraphDSL.create(takeAll, takeAll)(Keep.both) { implicit b ⇒ (out1, out2) ⇒ + val (f1, f2) = RunnableGraph.fromGraph(GraphDSL.create(takeAll, takeAll)(Keep.both) { implicit b => (out1, out2) => import GraphDSL.Implicits._ val bidi = b.add(rotatedBidi) @@ -311,7 +311,7 @@ class ActorGraphInterpreterSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val faily = b.add(failyStage) @@ -351,7 +351,7 @@ class ActorGraphInterpreterSpec extends StreamSpec { Source.combine( Source.fromPublisher(filthyPublisher), - Source.fromPublisher(upstream))(count ⇒ Merge(count)) + Source.fromPublisher(upstream))(count => Merge(count)) .runWith(Sink.fromSubscriber(downstream)) upstream.ensureSubscription() diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/AsyncCallbackSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/AsyncCallbackSpec.scala index b9f794e16f..aa162d4fc8 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/AsyncCallbackSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/AsyncCallbackSpec.scala @@ -24,7 +24,7 @@ class AsyncCallbackSpec extends AkkaSpec { case class Elem(n: Int) case object Stopped - class AsyncCallbackGraphStage(probe: ActorRef, early: Option[AsyncCallback[AnyRef] ⇒ Unit] = None) + class AsyncCallbackGraphStage(probe: ActorRef, early: Option[AsyncCallback[AnyRef] => Unit] = None) extends GraphStageWithMaterializedValue[FlowShape[Int, Int], AsyncCallback[AnyRef]] { val in = Inlet[Int]("in") @@ -33,14 +33,14 @@ class AsyncCallbackSpec extends AkkaSpec { def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, AsyncCallback[AnyRef]) = { val logic = new GraphStageLogic(shape) { - val callback = getAsyncCallback((whatever: AnyRef) ⇒ { + val callback = getAsyncCallback((whatever: AnyRef) => { whatever match { - case t: Throwable ⇒ throw t - case "fail-the-stage" ⇒ failStage(new RuntimeException("failing the stage")) - case anythingElse ⇒ probe ! anythingElse + case t: Throwable => throw t + case "fail-the-stage" => failStage(new RuntimeException("failing the stage")) + case anythingElse => probe ! anythingElse } }) - early.foreach(cb ⇒ cb(callback)) + early.foreach(cb => cb(callback)) override def preStart(): Unit = { probe ! Started @@ -82,7 +82,7 @@ class AsyncCallbackSpec extends AkkaSpec { out.request(1) in.expectRequest() - (0 to 10).foreach { n ⇒ + (0 to 10).foreach { n => val msg = "whatever" + n callback.invoke(msg) probe.expectMsg(msg) @@ -107,7 +107,7 @@ class AsyncCallbackSpec extends AkkaSpec { out.request(1) in.expectRequest() - (0 to 10).foreach { n ⇒ + (0 to 10).foreach { n => val msg = "whatever" + n val feedbackF = callback.invokeWithFeedback(msg) probe.expectMsg(msg) @@ -139,7 +139,7 @@ class AsyncCallbackSpec extends AkkaSpec { val callback = Source.fromPublisher(in) .viaMat(new AsyncCallbackGraphStage( probe.ref, - Some(asyncCb ⇒ asyncCb.invoke("early")) + Some(asyncCb => asyncCb.invoke("early")) ))(Keep.right) .to(Sink.ignore) .run() @@ -163,7 +163,7 @@ class AsyncCallbackSpec extends AkkaSpec { val callback = Source.fromPublisher(in) .viaMat(new AsyncCallbackGraphStage( probe.ref, - Some(asyncCb ⇒ earlyFeedback.completeWith(asyncCb.invokeWithFeedback("early"))) + Some(asyncCb => earlyFeedback.completeWith(asyncCb.invokeWithFeedback("early"))) ))(Keep.right) .to(Sink.ignore) .run() @@ -191,15 +191,15 @@ class AsyncCallbackSpec extends AkkaSpec { .run() import system.dispatcher - val feedbacks = (1 to 100).map { n ⇒ + val feedbacks = (1 to 100).map { n => Future { callback.invokeWithFeedback(n.toString) - }.flatMap(d ⇒ d) + }.flatMap(d => d) } probe.expectMsg(Started) Future.sequence(feedbacks).futureValue should have size (100) - (1 to 100).map(_ ⇒ probe.expectMsgType[String]).toSet should have size (100) + (1 to 100).map(_ => probe.expectMsgType[String]).toSet should have size (100) in.sendComplete() probe.expectMsg(Stopped) @@ -248,7 +248,7 @@ class AsyncCallbackSpec extends AkkaSpec { val shape = SourceShape(out) def createLogicAndMaterializedValue(inheritedAttributes: Attributes) = { val logic = new GraphStageLogic(shape) { - val callbacks = (0 to 10).map(_ ⇒ getAsyncCallback[AnyRef](probe ! _)).toSet + val callbacks = (0 to 10).map(_ => getAsyncCallback[AnyRef](probe ! _)).toSet setHandler(out, new OutHandler { def onPull(): Unit = () }) @@ -266,12 +266,12 @@ class AsyncCallbackSpec extends AkkaSpec { .run() val happyPathFeedbacks = - acbs.map(acb ⇒ + acbs.map(acb => Future { acb.invokeWithFeedback("bö") }.flatMap(identity) ) Future.sequence(happyPathFeedbacks).futureValue // will throw on fail or timeout on not completed - for (_ ← 0 to 10) acbProbe.expectMsg("bö") + for (_ <- 0 to 10) acbProbe.expectMsg("bö") val (half, otherHalf) = acbs.splitAt(4) val firstHalfFutures = half.map(_.invokeWithFeedback("ba")) @@ -280,12 +280,12 @@ class AsyncCallbackSpec extends AkkaSpec { val unhappyPath = firstHalfFutures ++ otherHalfFutures // all futures should either be completed or failed with StreamDetachedException - unhappyPath.foreach { future ⇒ + unhappyPath.foreach { future => try { val done = Await.result(future, remainingOrDefault) done should ===(Done) } catch { - case _: StreamDetachedException ⇒ // this is fine + case _: StreamDetachedException => // this is fine } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/GraphInterpreterPortsSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/GraphInterpreterPortsSpec.scala index e317a76366..185d661ccb 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/GraphInterpreterPortsSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/GraphInterpreterPortsSpec.scala @@ -13,7 +13,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit // FIXME test failure scenarios - for (chasing ← List(false, true)) { + for (chasing <- List(false, true)) { s"properly transition on push and pull (chasing = $chasing)" in new PortTestSetup(chasing) { lastEvents() should be(Set.empty) diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/GraphInterpreterSpecKit.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/GraphInterpreterSpecKit.scala index 41b0094b82..21159cf485 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/GraphInterpreterSpecKit.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/GraphInterpreterSpecKit.scala @@ -12,7 +12,7 @@ import akka.stream.stage.{ GraphStage, GraphStageLogic, InHandler, OutHandler, _ import akka.stream.testkit.StreamSpec import akka.stream.testkit.Utils.TE -import scala.collection.{ Map ⇒ SMap } +import scala.collection.{ Map => SMap } object GraphInterpreterSpecKit { @@ -45,7 +45,7 @@ object GraphInterpreterSpecKit { upstream.stageId = idx logics(idx) = upstream upstream.out.id = 0 - outOwners = outOwners + (upstream.out → upstream) + outOwners = outOwners + (upstream.out -> upstream) idx += 1 } @@ -65,7 +65,7 @@ object GraphInterpreterSpecKit { while (inletIdx < stage.shape.inlets.length) { val inlet = stage.shape.inlets(inletIdx) inlet.id = inletIdx - inOwners = inOwners + (inlet → logic) + inOwners = inOwners + (inlet -> logic) inletIdx += 1 } @@ -73,7 +73,7 @@ object GraphInterpreterSpecKit { while (outletIdx < stage.shape.outlets.length) { val outlet = stage.shape.outlets(outletIdx) outlet.id = outletIdx - outOwners = outOwners + (outlet → logic) + outOwners = outOwners + (outlet -> logic) outletIdx += 1 } logics(idx) = logic @@ -88,7 +88,7 @@ object GraphInterpreterSpecKit { downstream.stageId = idx logics(idx) = downstream downstream.in.id = 0 - inOwners = inOwners + (downstream.in → downstream) + inOwners = inOwners + (downstream.in -> downstream) idx += 1 downstreamIdx += 1 @@ -103,7 +103,7 @@ object GraphInterpreterSpecKit { private[stream] def createLinearFlowConnections(logics: Seq[GraphStageLogic]): Array[Connection] = { require(logics.length >= 2, s"$logics is too short to create a linear flow") logics.sliding(2).zipWithIndex.map { - case (window, idx) ⇒ + case (window, idx) => val outOwner = window(0) val inOwner = window(1) @@ -133,7 +133,7 @@ object GraphInterpreterSpecKit { val connections = new Array[Connection](connectedPorts.size) connectedPorts.zipWithIndex.foreach { - case ((outlet, inlet), idx) ⇒ + case ((outlet, inlet), idx) => val outOwner = outOwners(outlet) val inOwner = inOwners(inlet) @@ -155,20 +155,20 @@ object GraphInterpreterSpecKit { private def setPortIds(shape: Shape): Unit = { shape.inlets.zipWithIndex.foreach { - case (inlet, idx) ⇒ inlet.id = idx + case (inlet, idx) => inlet.id = idx } shape.outlets.zipWithIndex.foreach { - case (outlet, idx) ⇒ outlet.id = idx + case (outlet, idx) => outlet.id = idx } } private def setPortIds(stage: GraphStageWithMaterializedValue[_ <: Shape, _]): Unit = { - stage.shape.inlets.zipWithIndex.foreach { case (inlet, idx) ⇒ inlet.id = idx } - stage.shape.outlets.zipWithIndex.foreach { case (inlet, idx) ⇒ inlet.id = idx } + stage.shape.inlets.zipWithIndex.foreach { case (inlet, idx) => inlet.id = idx } + stage.shape.outlets.zipWithIndex.foreach { case (inlet, idx) => inlet.id = idx } } private def setLogicIds(logics: Array[GraphStageLogic]): Unit = { - logics.zipWithIndex.foreach { case (logic, idx) ⇒ logic.stageId = idx } + logics.zipWithIndex.foreach { case (logic, idx) => logic.stageId = idx } } } @@ -222,18 +222,18 @@ trait GraphInterpreterSpecKit extends StreamSpec { def connect[T](upstream: UpstreamBoundaryStageLogic[T], in: Inlet[T]): AssemblyBuilder = { upstreams :+= upstream - connectedPorts :+= upstream.out → in + connectedPorts :+= upstream.out -> in this } def connect[T](out: Outlet[T], downstream: DownstreamBoundaryStageLogic[T]): AssemblyBuilder = { downstreams :+= downstream - connectedPorts :+= out → downstream.in + connectedPorts :+= out -> downstream.in this } def connect[T](out: Outlet[T], in: Inlet[T]): AssemblyBuilder = { - connectedPorts :+= out → in + connectedPorts :+= out -> in this } @@ -251,7 +251,7 @@ trait GraphInterpreterSpecKit extends StreamSpec { logger, logics, connections, - onAsyncInput = (_, _, _, _) ⇒ (), + onAsyncInput = (_, _, _, _) => (), fuzzingMode = false, context = null) _interpreter.init(null) @@ -393,8 +393,8 @@ trait GraphInterpreterSpecKit extends StreamSpec { val internalEvent = portToConn(in.id).slot internalEvent match { - case Failed(_, elem) ⇒ lastEvent += OnNext(DownstreamPortProbe.this, elem) - case elem ⇒ lastEvent += OnNext(DownstreamPortProbe.this, elem) + case Failed(_, elem) => lastEvent += OnNext(DownstreamPortProbe.this, elem) + case elem => lastEvent += OnNext(DownstreamPortProbe.this, elem) } } @@ -441,7 +441,7 @@ trait GraphInterpreterSpecKit extends StreamSpec { // Must be lazy because I turned this stage "inside-out" therefore changing initialization order // to make tests a bit more readable lazy val insideOutStage: GraphStageLogic = new GraphStageLogic(stageshape) { - private def mayFail(task: ⇒ Unit): Unit = { + private def mayFail(task: => Unit): Unit = { if (!_failOnNextEvent) task else { _failOnNextEvent = false diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterSpec.scala index 732afbdcdb..1a15c0d0a7 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterSpec.scala @@ -24,7 +24,7 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { "Interpreter" must { - "implement map correctly" in new OneBoundedSetup[Int](Map((x: Int) ⇒ x + 1)) { + "implement map correctly" in new OneBoundedSetup[Int](Map((x: Int) => x + 1)) { lastEvents() should be(Set.empty) downstream.requestOne() @@ -44,9 +44,9 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "implement chain of maps correctly" in new OneBoundedSetup[Int]( - Map((x: Int) ⇒ x + 1), - Map((x: Int) ⇒ x * 2), - Map((x: Int) ⇒ x + 1)) { + Map((x: Int) => x + 1), + Map((x: Int) => x * 2), + Map((x: Int) => x + 1)) { lastEvents() should be(Set.empty) @@ -81,7 +81,7 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { "implement one-to-many many-to-one chain correctly" in new OneBoundedSetup[Int]( Doubler(), - Filter((x: Int) ⇒ x != 0)) { + Filter((x: Int) => x != 0)) { lastEvents() should be(Set.empty) @@ -105,7 +105,7 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "implement many-to-one one-to-many chain correctly" in new OneBoundedSetup[Int]( - Filter((x: Int) ⇒ x != 0), + Filter((x: Int) => x != 0), Doubler()) { lastEvents() should be(Set.empty) @@ -147,9 +147,9 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "implement take inside a chain" in new OneBoundedSetup[Int]( - Filter((x: Int) ⇒ x != 0), + Filter((x: Int) => x != 0), takeTwo, - Map((x: Int) ⇒ x + 1)) { + Map((x: Int) => x + 1)) { lastEvents() should be(Set.empty) @@ -169,7 +169,7 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { lastEvents() should be(Set(Cancel, OnComplete, OnNext(3))) } - "implement fold" in new OneBoundedSetup[Int](Fold(0, (agg: Int, x: Int) ⇒ agg + x)) { + "implement fold" in new OneBoundedSetup[Int](Fold(0, (agg: Int, x: Int) => agg + x)) { lastEvents() should be(Set.empty) downstream.requestOne() @@ -188,7 +188,7 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { lastEvents() should be(Set(OnNext(3), OnComplete)) } - "implement fold with proper cancel" in new OneBoundedSetup[Int](Fold(0, (agg: Int, x: Int) ⇒ agg + x)) { + "implement fold with proper cancel" in new OneBoundedSetup[Int](Fold(0, (agg: Int, x: Int) => agg + x)) { lastEvents() should be(Set.empty) @@ -208,7 +208,7 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { lastEvents() should be(Set(Cancel)) } - "work if fold completes while not in a push position" in new OneBoundedSetup[Int](Fold(0, (agg: Int, x: Int) ⇒ agg + x)) { + "work if fold completes while not in a push position" in new OneBoundedSetup[Int](Fold(0, (agg: Int, x: Int) => agg + x)) { lastEvents() should be(Set.empty) @@ -247,8 +247,8 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { "implement batch (conflate)" in new OneBoundedSetup[Int](Batch( 1L, ConstantFun.zeroLong, - (in: Int) ⇒ in, - (agg: Int, x: Int) ⇒ agg + x)) { + (in: Int) => in, + (agg: Int, x: Int) => agg + x)) { lastEvents() should be(Set(RequestOne)) @@ -307,13 +307,13 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { Batch( 1L, ConstantFun.zeroLong, - (in: Int) ⇒ in, - (agg: Int, x: Int) ⇒ agg + x), + (in: Int) => in, + (agg: Int, x: Int) => agg + x), Batch( 1L, ConstantFun.zeroLong, - (in: Int) ⇒ in, - (agg: Int, x: Int) ⇒ agg + x)) { + (in: Int) => in, + (agg: Int, x: Int) => agg + x)) { lastEvents() should be(Set(RequestOne)) @@ -344,8 +344,8 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "work with expand-expand" in new OneBoundedSetup[Int]( - new Expand((x: Int) ⇒ Iterator.from(x)), - new Expand((x: Int) ⇒ Iterator.from(x))) { + new Expand((x: Int) => Iterator.from(x)), + new Expand((x: Int) => Iterator.from(x))) { lastEvents() should be(Set(RequestOne)) @@ -380,8 +380,8 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { Batch( 1L, ConstantFun.zeroLong, - (in: Int) ⇒ in, - (agg: Int, x: Int) ⇒ agg + x), + (in: Int) => in, + (agg: Int, x: Int) => agg + x), new Expand(Iterator.continually(_: Int))) { lastEvents() should be(Set(RequestOne)) @@ -416,8 +416,8 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { Batch( 1L, ConstantFun.zeroLong, - (in: Int) ⇒ in, - (agg: Int, x: Int) ⇒ agg + x)) { + (in: Int) => in, + (agg: Int, x: Int) => agg + x)) { lastEvents() should be(Set(RequestOne)) upstream.onNext(1) @@ -433,11 +433,11 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { // Note, the new interpreter has no jumpback table, still did not want to remove the test "work with jumpback table and completed elements" in new OneBoundedSetup[Int]( - Map((x: Int) ⇒ x), - Map((x: Int) ⇒ x), + Map((x: Int) => x), + Map((x: Int) => x), KeepGoing(), - Map((x: Int) ⇒ x), - Map((x: Int) ⇒ x)) { + Map((x: Int) => x), + Map((x: Int) => x)) { lastEvents() should be(Set.empty) @@ -476,9 +476,9 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "work with pushAndFinish if indirect upstream completes with pushAndFinish" in new OneBoundedSetup[Int]( - Map((x: Any) ⇒ x), + Map((x: Any) => x), new PushFinishStage, - Map((x: Any) ⇒ x)) { + Map((x: Any) => x)) { lastEvents() should be(Set.empty) @@ -491,7 +491,7 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { "work with pushAndFinish if upstream completes with pushAndFinish and downstream immediately pulls" in new OneBoundedSetup[Int]( new PushFinishStage, - Fold(0, (x: Int, y: Int) ⇒ x + y)) { + Fold(0, (x: Int, y: Int) => x + y)) { lastEvents() should be(Set.empty) @@ -525,8 +525,8 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { val ev = lastEvents() ev.nonEmpty should be(true) ev.forall { - case OnError(_: IllegalArgumentException) ⇒ true - case _ ⇒ false + case OnError(_: IllegalArgumentException) => true + case _ => false } should be(true) } @@ -615,7 +615,7 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } - private[akka] class PushFinishStage(onPostStop: () ⇒ Unit = () ⇒ ()) extends SimpleLinearGraphStage[Any] { + private[akka] class PushFinishStage(onPostStop: () => Unit = () => ()) extends SimpleLinearGraphStage[Any] { override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { override def onPush(): Unit = { diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterStressSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterStressSpec.scala index 3e509bbc12..566fe86a10 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterStressSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterStressSpec.scala @@ -14,7 +14,7 @@ class InterpreterStressSpec extends StreamSpec with GraphInterpreterSpecKit { val halfLength = chainLength / 2 val repetition = 100 - val map = Map((x: Int) ⇒ x + 1) + val map = Map((x: Int) => x + 1) // GraphStages can be reused val dropOne = Drop(1) @@ -108,8 +108,8 @@ class InterpreterStressSpec extends StreamSpec with GraphInterpreterSpecKit { val batch = Batch( 0L, ConstantFun.zeroLong, - (in: Int) ⇒ in, - (agg: Int, in: Int) ⇒ agg + in) + (in: Int) => in, + (agg: Int, in: Int) => agg + in) new OneBoundedSetup[Int](Vector.fill(chainLength / 10)(batch): _*) { diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterSupervisionSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterSupervisionSpec.scala index 79b8030f49..f60e38080e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterSupervisionSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/InterpreterSupervisionSpec.scala @@ -17,14 +17,14 @@ class InterpreterSupervisionSpec extends StreamSpec with GraphInterpreterSpecKit "Interpreter error handling" must { - "handle external failure" in new OneBoundedSetup[Int](Map((x: Int) ⇒ x + 1)) { + "handle external failure" in new OneBoundedSetup[Int](Map((x: Int) => x + 1)) { lastEvents() should be(Set.empty) upstream.onError(TE) lastEvents() should be(Set(OnError(TE))) } - "emit failure when op throws" in new OneBoundedSetup[Int](Map((x: Int) ⇒ if (x == 0) throw TE else x)) { + "emit failure when op throws" in new OneBoundedSetup[Int](Map((x: Int) => if (x == 0) throw TE else x)) { downstream.requestOne() lastEvents() should be(Set(RequestOne)) upstream.onNext(2) @@ -37,9 +37,9 @@ class InterpreterSupervisionSpec extends StreamSpec with GraphInterpreterSpecKit } "emit failure when op throws in middle of the chain" in new OneBoundedSetup[Int]( - Map((x: Int) ⇒ x + 1), - Map((x: Int) ⇒ if (x == 0) throw TE else x + 10), - Map((x: Int) ⇒ x + 100)) { + Map((x: Int) => x + 1), + Map((x: Int) => if (x == 0) throw TE else x + 10), + Map((x: Int) => x + 100)) { downstream.requestOne() lastEvents() should be(Set(RequestOne)) @@ -54,7 +54,7 @@ class InterpreterSupervisionSpec extends StreamSpec with GraphInterpreterSpecKit "resume when Map throws" in new OneBoundedSetupWithDecider[Int]( Supervision.resumingDecider, - Map((x: Int) ⇒ if (x == 0) throw TE else x) + Map((x: Int) => if (x == 0) throw TE else x) ) { downstream.requestOne() lastEvents() should be(Set(RequestOne)) @@ -81,9 +81,9 @@ class InterpreterSupervisionSpec extends StreamSpec with GraphInterpreterSpecKit "resume when Map throws in middle of the chain" in new OneBoundedSetupWithDecider[Int]( Supervision.resumingDecider, - Map((x: Int) ⇒ x + 1), - Map((x: Int) ⇒ if (x == 0) throw TE else x + 10), - Map((x: Int) ⇒ x + 100) + Map((x: Int) => x + 1), + Map((x: Int) => if (x == 0) throw TE else x + 10), + Map((x: Int) => x + 100) ) { downstream.requestOne() @@ -102,8 +102,8 @@ class InterpreterSupervisionSpec extends StreamSpec with GraphInterpreterSpecKit "resume when Map throws before Grouped" in new OneBoundedSetupWithDecider[Int]( Supervision.resumingDecider, - Map((x: Int) ⇒ x + 1), - Map((x: Int) ⇒ if (x <= 0) throw TE else x + 10), + Map((x: Int) => x + 1), + Map((x: Int) => if (x <= 0) throw TE else x + 10), Grouped(3)) { downstream.requestOne() @@ -123,8 +123,8 @@ class InterpreterSupervisionSpec extends StreamSpec with GraphInterpreterSpecKit "complete after resume when Map throws before Grouped" in new OneBoundedSetupWithDecider[Int]( Supervision.resumingDecider, - Map((x: Int) ⇒ x + 1), - Map((x: Int) ⇒ if (x <= 0) throw TE else x + 10), + Map((x: Int) => x + 1), + Map((x: Int) => if (x <= 0) throw TE else x + 10), Grouped(1000)) { downstream.requestOne() @@ -143,7 +143,7 @@ class InterpreterSupervisionSpec extends StreamSpec with GraphInterpreterSpecKit } "fail when Expand `seed` throws" in new OneBoundedSetup[Int]( - new Expand((in: Int) ⇒ if (in == 2) throw TE else Iterator(in) ++ Iterator.continually(-math.abs(in)))) { + new Expand((in: Int) => if (in == 2) throw TE else Iterator(in) ++ Iterator.continually(-math.abs(in)))) { lastEvents() should be(Set(RequestOne)) @@ -164,7 +164,7 @@ class InterpreterSupervisionSpec extends StreamSpec with GraphInterpreterSpecKit } "fail when Expand `expander` throws" in new OneBoundedSetup[Int]( - new Expand((in: Int) ⇒ if (in == 2) Iterator.continually(throw TE) else Iterator(in) ++ Iterator.continually(-math.abs(in)))) { + new Expand((in: Int) => if (in == 2) Iterator.continually(throw TE) else Iterator(in) ++ Iterator.continually(-math.abs(in)))) { lastEvents() should be(Set(RequestOne)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/KeepGoingStageSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/KeepGoingStageSpec.scala index f5fde50936..00ccbfb463 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/KeepGoingStageSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/KeepGoingStageSpec.scala @@ -55,15 +55,15 @@ class KeepGoingStageSpec extends StreamSpec { } private def onCommand(cmd: PingCmd): Unit = cmd match { - case Register(probe) ⇒ listener = Some(probe) - case Ping ⇒ listener.foreach(_ ! Pong) - case CompleteStage ⇒ + case Register(probe) => listener = Some(probe) + case Ping => listener.foreach(_ ! Pong) + case CompleteStage => completeStage() listener.foreach(_ ! EndOfEventHandler) - case FailStage ⇒ + case FailStage => failStage(TE("test")) listener.foreach(_ ! EndOfEventHandler) - case Throw ⇒ + case Throw => try { throw TE("test") } finally listener.foreach(_ ! EndOfEventHandler) diff --git a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/LifecycleInterpreterSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/LifecycleInterpreterSpec.scala index 57cb9444fe..fa8a5f24ae 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/LifecycleInterpreterSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/impl/fusing/LifecycleInterpreterSpec.scala @@ -17,9 +17,9 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { "Interpreter" must { "call preStart in order on stages" in new OneBoundedSetup[String]( - PreStartAndPostStopIdentity(onStart = () ⇒ testActor ! "start-a"), - PreStartAndPostStopIdentity(onStart = () ⇒ testActor ! "start-b"), - PreStartAndPostStopIdentity(onStart = () ⇒ testActor ! "start-c")) { + PreStartAndPostStopIdentity(onStart = () => testActor ! "start-a"), + PreStartAndPostStopIdentity(onStart = () => testActor ! "start-b"), + PreStartAndPostStopIdentity(onStart = () => testActor ! "start-c")) { expectMsg("start-a") expectMsg("start-b") expectMsg("start-c") @@ -28,9 +28,9 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "call postStop in order on stages - when upstream completes" in new OneBoundedSetup[String]( - PreStartAndPostStopIdentity(onUpstreamCompleted = () ⇒ testActor ! "complete-a", onStop = () ⇒ testActor ! "stop-a"), - PreStartAndPostStopIdentity(onUpstreamCompleted = () ⇒ testActor ! "complete-b", onStop = () ⇒ testActor ! "stop-b"), - PreStartAndPostStopIdentity(onUpstreamCompleted = () ⇒ testActor ! "complete-c", onStop = () ⇒ testActor ! "stop-c")) { + PreStartAndPostStopIdentity(onUpstreamCompleted = () => testActor ! "complete-a", onStop = () => testActor ! "stop-a"), + PreStartAndPostStopIdentity(onUpstreamCompleted = () => testActor ! "complete-b", onStop = () => testActor ! "stop-b"), + PreStartAndPostStopIdentity(onUpstreamCompleted = () => testActor ! "complete-c", onStop = () => testActor ! "stop-c")) { upstream.onComplete() expectMsg("complete-a") expectMsg("stop-a") @@ -43,8 +43,8 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { "call postStop in order on stages - when upstream onErrors" in new OneBoundedSetup[String]( PreStartAndPostStopIdentity( - onUpstreamFailed = ex ⇒ testActor ! ex.getMessage, - onStop = () ⇒ testActor ! "stop-c")) { + onUpstreamFailed = ex => testActor ! ex.getMessage, + onStop = () => testActor ! "stop-c")) { val msg = "Boom! Boom! Boom!" upstream.onError(TE(msg)) expectMsg(msg) @@ -53,9 +53,9 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "call postStop in order on stages - when downstream cancels" in new OneBoundedSetup[String]( - PreStartAndPostStopIdentity(onStop = () ⇒ testActor ! "stop-a"), - PreStartAndPostStopIdentity(onStop = () ⇒ testActor ! "stop-b"), - PreStartAndPostStopIdentity(onStop = () ⇒ testActor ! "stop-c")) { + PreStartAndPostStopIdentity(onStop = () => testActor ! "stop-a"), + PreStartAndPostStopIdentity(onStop = () => testActor ! "stop-b"), + PreStartAndPostStopIdentity(onStop = () => testActor ! "stop-c")) { downstream.cancel() expectMsg("stop-c") expectMsg("stop-b") @@ -64,7 +64,7 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "call preStart before postStop" in new OneBoundedSetup[String]( - PreStartAndPostStopIdentity(onStart = () ⇒ testActor ! "start-a", onStop = () ⇒ testActor ! "stop-a")) { + PreStartAndPostStopIdentity(onStart = () => testActor ! "start-a", onStop = () => testActor ! "stop-a")) { expectMsg("start-a") expectNoMsg(300.millis) upstream.onComplete() @@ -73,25 +73,25 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "onError when preStart fails" in new OneBoundedSetup[String]( - PreStartFailer(() ⇒ throw TE("Boom!"))) { + PreStartFailer(() => throw TE("Boom!"))) { lastEvents() should ===(Set(Cancel, OnError(TE("Boom!")))) } "not blow up when postStop fails" in new OneBoundedSetup[String]( - PostStopFailer(() ⇒ throw TE("Boom!"))) { + PostStopFailer(() => throw TE("Boom!"))) { upstream.onComplete() lastEvents() should ===(Set(OnComplete)) } "onError when preStart fails with stages after" in new OneBoundedSetup[String]( - Map((x: Int) ⇒ x), - PreStartFailer(() ⇒ throw TE("Boom!")), - Map((x: Int) ⇒ x)) { + Map((x: Int) => x), + PreStartFailer(() => throw TE("Boom!")), + Map((x: Int) => x)) { lastEvents() should ===(Set(Cancel, OnError(TE("Boom!")))) } "continue with stream shutdown when postStop fails" in new OneBoundedSetup[String]( - PostStopFailer(() ⇒ throw TE("Boom!"))) { + PostStopFailer(() => throw TE("Boom!"))) { lastEvents() should ===(Set()) upstream.onComplete() @@ -99,7 +99,7 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "postStop when pushAndFinish called if upstream completes with pushAndFinish" in new OneBoundedSetup[String]( - new PushFinishStage(onPostStop = () ⇒ testActor ! "stop")) { + new PushFinishStage(onPostStop = () => testActor ! "stop")) { lastEvents() should be(Set.empty) @@ -112,9 +112,9 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "postStop when pushAndFinish called with pushAndFinish if indirect upstream completes with pushAndFinish" in new OneBoundedSetup[String]( - Map((x: Any) ⇒ x), - new PushFinishStage(onPostStop = () ⇒ testActor ! "stop"), - Map((x: Any) ⇒ x)) { + Map((x: Any) => x), + new PushFinishStage(onPostStop = () => testActor ! "stop"), + Map((x: Any) => x)) { lastEvents() should be(Set.empty) @@ -127,8 +127,8 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } "postStop when pushAndFinish called with pushAndFinish if upstream completes with pushAndFinish and downstream immediately pulls" in new OneBoundedSetup[String]( - new PushFinishStage(onPostStop = () ⇒ testActor ! "stop"), - Fold("", (x: String, y: String) ⇒ x + y)) { + new PushFinishStage(onPostStop = () => testActor ! "stop"), + Fold("", (x: String, y: String) => x + y)) { lastEvents() should be(Set.empty) @@ -143,10 +143,10 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } private[akka] case class PreStartAndPostStopIdentity[T]( - onStart: () ⇒ Unit = () ⇒ (), - onStop: () ⇒ Unit = () ⇒ (), - onUpstreamCompleted: () ⇒ Unit = () ⇒ (), - onUpstreamFailed: Throwable ⇒ Unit = ex ⇒ ()) extends SimpleLinearGraphStage[T] { + onStart: () => Unit = () => (), + onStop: () => Unit = () => (), + onUpstreamCompleted: () => Unit = () => (), + onUpstreamFailed: Throwable => Unit = ex => ()) extends SimpleLinearGraphStage[T] { override def createLogic(attributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { @@ -172,7 +172,7 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { override def toString = "PreStartAndPostStopIdentity" } - private[akka] case class PreStartFailer[T](pleaseThrow: () ⇒ Unit) extends SimpleLinearGraphStage[T] { + private[akka] case class PreStartFailer[T](pleaseThrow: () => Unit) extends SimpleLinearGraphStage[T] { override def createLogic(attributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { @@ -187,7 +187,7 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { override def toString = "PreStartFailer" } - private[akka] case class PostStopFailer[T](pleaseThrow: () ⇒ Unit) extends SimpleLinearGraphStage[T] { + private[akka] case class PostStopFailer[T](pleaseThrow: () => Unit) extends SimpleLinearGraphStage[T] { override def createLogic(attributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { @@ -205,7 +205,7 @@ class LifecycleInterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } // This test is related to issue #17351 - private[akka] class PushFinishStage(onPostStop: () ⇒ Unit = () ⇒ ()) extends SimpleLinearGraphStage[Any] { + private[akka] class PushFinishStage(onPostStop: () => Unit = () => ()) extends SimpleLinearGraphStage[Any] { override def createLogic(attributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/FileSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/FileSinkSpec.scala index f771ae50ee..140ca55962 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/FileSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/FileSinkSpec.scala @@ -45,7 +45,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { "FileSink" must { "write lines to a file" in assertAllStagesStopped { - targetFile { f ⇒ + targetFile { f => val completion = Source(TestByteStrings) .runWith(FileIO.toPath(f)) @@ -56,7 +56,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } "create new file if not exists" in assertAllStagesStopped { - targetFile({ f ⇒ + targetFile({ f => val completion = Source(TestByteStrings) .runWith(FileIO.toPath(f)) @@ -67,7 +67,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } "write into existing file without wiping existing data" in assertAllStagesStopped { - targetFile { f ⇒ + targetFile { f => def write(lines: List[String]) = Source(lines) .map(ByteString(_)) @@ -86,7 +86,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } "by default replace the existing file" in assertAllStagesStopped { - targetFile { f ⇒ + targetFile { f => def write(lines: List[String]) = Source(lines) .map(ByteString(_)) @@ -105,7 +105,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } "allow appending to file" in assertAllStagesStopped { - targetFile { f ⇒ + targetFile { f => def write(lines: List[String] = TestLines) = Source(lines) .map(ByteString(_)) @@ -124,7 +124,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } "allow writing from specific position to the file" in assertAllStagesStopped { - targetFile { f ⇒ + targetFile { f => val TestLinesCommon = { val b = ListBuffer[String]() b.append("a" * 1000 + "\n") @@ -134,7 +134,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { b.toList } - val commonByteString = TestLinesCommon.map(ByteString(_)).foldLeft[ByteString](ByteString.empty)((acc, line) ⇒ acc ++ line).compact + val commonByteString = TestLinesCommon.map(ByteString(_)).foldLeft[ByteString](ByteString.empty)((acc, line) => acc ++ line).compact val startPosition = commonByteString.size val testLinesPart2: List[String] = { @@ -161,11 +161,11 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } "use dedicated blocking-io-dispatcher by default" in assertAllStagesStopped { - targetFile { f ⇒ + targetFile { f => val sys = ActorSystem("dispatcher-testing", UnboundedMailboxConfig) val materializer = ActorMaterializer()(sys) try { - Source.fromIterator(() ⇒ Iterator.continually(TestByteStrings.head)).runWith(FileIO.toPath(f))(materializer) + Source.fromIterator(() => Iterator.continually(TestByteStrings.head)).runWith(FileIO.toPath(f))(materializer) materializer.asInstanceOf[PhasedFusingActorMaterializer].supervisor.tell(StreamSupervisor.GetChildren, testActor) val ref = expectMsgType[Children].children.find(_.path.toString contains "fileSink").get @@ -175,12 +175,12 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } "allow overriding the dispatcher using Attributes" in assertAllStagesStopped { - targetFile { f ⇒ + targetFile { f => val sys = ActorSystem("dispatcher-testing", UnboundedMailboxConfig) val materializer = ActorMaterializer()(sys) try { - Source.fromIterator(() ⇒ Iterator.continually(TestByteStrings.head)) + Source.fromIterator(() => Iterator.continually(TestByteStrings.head)) .to(FileIO.toPath(f).addAttributes(ActorAttributes.dispatcher("akka.actor.default-dispatcher"))) .run()(materializer) @@ -193,14 +193,14 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { "write single line to a file from lazy sink" in assertAllStagesStopped { //LazySink must wait for result of initialization even if got upstreamComplete - targetFile { f ⇒ + targetFile { f => val completion = Source(List(TestByteStrings.head)) .runWith(Sink.lazyInitAsync( - () ⇒ Future.successful(FileIO.toPath(f))) + () => Future.successful(FileIO.toPath(f))) // map a Future[Option[Future[IOResult]]] into a Future[Option[IOResult]] .mapMaterializedValue(_.flatMap { - case Some(future) ⇒ future.map(Some(_))(ExecutionContexts.sameThreadExecutionContext) - case None ⇒ Future.successful(None) + case Some(future) => future.map(Some(_))(ExecutionContexts.sameThreadExecutionContext) + case None => Future.successful(None) }(ExecutionContexts.sameThreadExecutionContext))) Await.result(completion, 3.seconds) @@ -210,9 +210,9 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } "complete materialized future with an exception when upstream fails" in assertAllStagesStopped { - targetFile { f ⇒ + targetFile { f => val completion = Source(TestByteStrings) - .map { bytes ⇒ + .map { bytes => if (bytes.contains('b')) throw new Error("bees!") bytes } @@ -232,7 +232,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) { } } - private def targetFile(block: Path ⇒ Unit, create: Boolean = true): Unit = { + private def targetFile(block: Path => Unit, create: Boolean = true): Unit = { val targetFile = Files.createTempFile(fs.getPath("/"), "synchronous-file-sink", ".tmp") if (!create) Files.delete(targetFile) try block(targetFile) finally Files.delete(targetFile) diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/FileSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/FileSourceSpec.scala index 12181a4d5d..bcf307a440 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/FileSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/FileSourceSpec.scala @@ -64,7 +64,7 @@ class FileSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val manyLines = { val f = Files.createTempFile(fs.getPath("/"), s"file-source-spec-lines_$LinesCount", "tmp") val w = Files.newBufferedWriter(f, UTF_8) - (1 to LinesCount).foreach { l ⇒ + (1 to LinesCount).foreach { l => w.append("a" * l).append("\n") } w.close() @@ -140,7 +140,7 @@ class FileSourceSpec extends StreamSpec(UnboundedMailboxConfig) { sub.request(5000) - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { c.expectNext().utf8String should ===(nextChunk().toString) } c.expectComplete() @@ -178,7 +178,7 @@ class FileSourceSpec extends StreamSpec(UnboundedMailboxConfig) { } sub.request(demandAllButOneChunks) - for (i ← 1 to demandAllButOneChunks) c.expectNext().utf8String should ===(nextChunk()) + for (i <- 1 to demandAllButOneChunks) c.expectNext().utf8String should ===(nextChunk()) c.expectNoMessage(300.millis) sub.request(1) @@ -220,14 +220,14 @@ class FileSourceSpec extends StreamSpec(UnboundedMailboxConfig) { Settings(chunkSize = 512, readAhead = 2), Settings(chunkSize = 512, readAhead = 4), Settings(chunkSize = 2048, readAhead = 2), - Settings(chunkSize = 2048, readAhead = 4)) foreach { settings ⇒ + Settings(chunkSize = 2048, readAhead = 4)) foreach { settings => import settings._ s"count lines in real file (chunkSize = $chunkSize, readAhead = $readAhead)" in { val s = FileIO.fromPath(manyLines, chunkSize = chunkSize) .withAttributes(Attributes.inputBuffer(readAhead, readAhead)) - val f = s.runWith(Sink.fold(0) { case (acc, l) ⇒ acc + l.utf8String.count(_ == '\n') }) + val f = s.runWith(Sink.fold(0) { case (acc, l) => acc + l.utf8String.count(_ == '\n') }) f.futureValue should ===(LinesCount) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/InputStreamSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/InputStreamSinkSpec.scala index 21c26d520b..7ca11c65b7 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/InputStreamSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/InputStreamSinkSpec.scala @@ -143,7 +143,7 @@ class InputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) { val bytes = randomByteString(10) val inputStream = Source.single(bytes).runWith(StreamConverters.asInputStream()) - for (expect ← bytes.sliding(3, 3)) + for (expect <- bytes.sliding(3, 3)) readN(inputStream, 3) should ===((expect.size, expect)) inputStream.close() @@ -166,9 +166,9 @@ class InputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) { .runWith(testSink(sinkProbe)) //need to wait while all elements arrive to sink - bytes foreach { _ ⇒ sinkProbe.expectMsg(GraphStageMessages.Push) } + bytes foreach { _ => sinkProbe.expectMsg(GraphStageMessages.Push) } - for (i ← 0 to 1) + for (i <- 0 to 1) readN(inputStream, 8) should ===((8, bytes(i * 2) ++ bytes(i * 2 + 1))) inputStream.close() diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/InputStreamSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/InputStreamSourceSpec.scala index a934cc9346..8eb2e067b5 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/InputStreamSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/InputStreamSourceSpec.scala @@ -25,24 +25,24 @@ class InputStreamSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "InputStreamSource" must { "not signal when no demand" in { - val f = StreamConverters.fromInputStream(() ⇒ new InputStream { + val f = StreamConverters.fromInputStream(() => new InputStream { override def read(): Int = 42 }) Await.result(f .takeWithin(5.seconds) - .runForeach(it ⇒ ()), 10.seconds) + .runForeach(it => ()), 10.seconds) } "read bytes from InputStream" in assertAllStagesStopped { - val f = StreamConverters.fromInputStream(() ⇒ new InputStream { + val f = StreamConverters.fromInputStream(() => new InputStream { @volatile var buf = List("a", "b", "c").map(_.charAt(0).toInt) override def read(): Int = { buf match { - case head :: tail ⇒ + case head :: tail => buf = tail head - case Nil ⇒ + case Nil => -1 } @@ -55,7 +55,7 @@ class InputStreamSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "emit as soon as read" in assertAllStagesStopped { val latch = new CountDownLatch(1) - val probe = StreamConverters.fromInputStream(() ⇒ new InputStream { + val probe = StreamConverters.fromInputStream(() => new InputStream { @volatile var emitted = false override def read(): Int = { if (!emitted) { diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/OutputStreamSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/OutputStreamSinkSpec.scala index 81774dfddc..a69b3022f0 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/OutputStreamSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/OutputStreamSinkSpec.scala @@ -28,7 +28,7 @@ class OutputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) { val datas = List(ByteString("a"), ByteString("c"), ByteString("c")) val completion = Source(datas) - .runWith(StreamConverters.fromOutputStream(() ⇒ new OutputStream { + .runWith(StreamConverters.fromOutputStream(() => new OutputStream { override def write(i: Int): Unit = () override def write(bytes: Array[Byte]): Unit = p.ref ! ByteString(bytes).utf8String })) @@ -42,7 +42,7 @@ class OutputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) { "close underlying stream when error received" in assertAllStagesStopped { val p = TestProbe() Source.failed(TE("Boom!")) - .runWith(StreamConverters.fromOutputStream(() ⇒ new OutputStream { + .runWith(StreamConverters.fromOutputStream(() => new OutputStream { override def write(i: Int): Unit = () override def close() = p.ref ! "closed" })) @@ -52,7 +52,7 @@ class OutputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) { "complete materialized value with the error" in assertAllStagesStopped { val completion = Source.failed(TE("Boom!")) - .runWith(StreamConverters.fromOutputStream(() ⇒ new OutputStream { + .runWith(StreamConverters.fromOutputStream(() => new OutputStream { override def write(i: Int): Unit = () override def close() = () })) @@ -63,7 +63,7 @@ class OutputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) { "close underlying stream when completion received" in assertAllStagesStopped { val p = TestProbe() Source.empty - .runWith(StreamConverters.fromOutputStream(() ⇒ new OutputStream { + .runWith(StreamConverters.fromOutputStream(() => new OutputStream { override def write(i: Int): Unit = () override def write(bytes: Array[Byte]): Unit = p.ref ! ByteString(bytes).utf8String override def close() = p.ref ! "closed" diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/OutputStreamSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/OutputStreamSourceSpec.scala index 002a841695..c5aaff84a9 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/OutputStreamSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/OutputStreamSourceSpec.scala @@ -48,10 +48,10 @@ class OutputStreamSourceSpec extends StreamSpec(UnboundedMailboxConfig) { def assertNoBlockedThreads(): Unit = { def threadsBlocked = ManagementFactory.getThreadMXBean.dumpAllThreads(true, true).toSeq - .filter(t ⇒ t.getThreadName.startsWith("OutputStreamSourceSpec") && + .filter(t => t.getThreadName.startsWith("OutputStreamSourceSpec") && t.getLockName != null && t.getLockName.startsWith("java.util.concurrent.locks.AbstractQueuedSynchronizer") && - t.getStackTrace.exists(s ⇒ s.getClassName.startsWith(classOf[OutputStreamSourceStage].getName))) + t.getStackTrace.exists(s => s.getClassName.startsWith(classOf[OutputStreamSourceStage].getName))) awaitAssert(threadsBlocked should ===(Seq()), 5.seconds, interval = 500.millis) } @@ -70,7 +70,7 @@ class OutputStreamSourceSpec extends StreamSpec(UnboundedMailboxConfig) { // https://github.com/akka/akka/issues/25983 "not truncate the stream on close" in assertAllStagesStopped { - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { val (outputStream, result) = StreamConverters.asOutputStream() .toMat(Sink.fold[ByteString, ByteString](ByteString.empty)(_ ++ _))(Keep.both) @@ -104,7 +104,7 @@ class OutputStreamSourceSpec extends StreamSpec(UnboundedMailboxConfig) { .withAttributes(Attributes.inputBuffer(16, 16)).run val s = probe.expectSubscription() - (1 to 16).foreach { _ ⇒ outputStream.write(bytesArray) } + (1 to 16).foreach { _ => outputStream.write(bytesArray) } //blocked call val f = Future(outputStream.write(bytesArray)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/TcpHelper.scala b/akka-stream-tests/src/test/scala/akka/stream/io/TcpHelper.scala index 3bab4cc7b7..4291cf3b2a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/TcpHelper.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/TcpHelper.scala @@ -49,26 +49,26 @@ object TcpHelper { // FIXME: various close scenarios def receive = { - case ClientWrite(bytes) if !writePending ⇒ + case ClientWrite(bytes) if !writePending => writePending = true connection ! Tcp.Write(bytes, WriteAck) - case ClientWrite(bytes) ⇒ + case ClientWrite(bytes) => queuedWrites = queuedWrites.enqueue(bytes) - case WriteAck if queuedWrites.nonEmpty ⇒ + case WriteAck if queuedWrites.nonEmpty => val (next, remaining) = queuedWrites.dequeue queuedWrites = remaining connection ! Tcp.Write(next, WriteAck) - case WriteAck ⇒ + case WriteAck => writePending = false closeAfterWrite match { - case Some(cmd) ⇒ connection ! cmd - case None ⇒ + case Some(cmd) => connection ! cmd + case None => } - case ClientRead(count, requester) ⇒ + case ClientRead(count, requester) => readTo = requester toRead = count connection ! Tcp.ResumeReading - case Tcp.Received(bytes) ⇒ + case Tcp.Received(bytes) => readBuffer ++= bytes if (readBuffer.size >= toRead) { readTo ! ReadResult(readBuffer) @@ -76,13 +76,13 @@ object TcpHelper { toRead = 0 readTo = context.system.deadLetters } else connection ! Tcp.ResumeReading - case PingClose(requester) ⇒ + case PingClose(requester) => readTo = requester connection ! ResumeReading - case c: ConnectionClosed ⇒ + case c: ConnectionClosed => readTo ! c if (!c.isPeerClosed) context.stop(self) - case ClientClose(cmd) ⇒ + case ClientClose(cmd) => if (!writePending) connection ! cmd else closeAfterWrite = Some(cmd) } @@ -97,15 +97,15 @@ object TcpHelper { var listener: ActorRef = _ def receive = { - case b @ Tcp.Bound(_) ⇒ + case b @ Tcp.Bound(_) => listener = sender() listener ! Tcp.ResumeAccepting(1) probe ! b - case Tcp.Connected(_, _) ⇒ + case Tcp.Connected(_, _) => val handler = context.actorOf(testClientProps(sender())) listener ! Tcp.ResumeAccepting(1) probe ! handler - case ServerClose ⇒ + case ServerClose => listener ! Tcp.Unbind context.stop(self) } @@ -114,7 +114,7 @@ object TcpHelper { } -trait TcpHelper { this: TestKitBase ⇒ +trait TcpHelper { this: TestKitBase => import akka.stream.io.TcpHelper._ val settings = ActorMaterializerSettings(system) @@ -145,11 +145,11 @@ trait TcpHelper { this: TestKitBase ⇒ def expectClosed(expected: ConnectionClosed): Unit = expectClosed(_ == expected) - def expectClosed(p: (ConnectionClosed) ⇒ Boolean, max: Duration = 3.seconds): Unit = { + def expectClosed(p: (ConnectionClosed) => Boolean, max: Duration = 3.seconds): Unit = { connectionActor ! PingClose(connectionProbe.ref) connectionProbe.fishForMessage(max) { - case c: ConnectionClosed if p(c) ⇒ true - case other ⇒ false + case c: ConnectionClosed if p(c) => true + case other => false } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/TcpSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/TcpSpec.scala index dbad5f6dc4..615f76abe1 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/TcpSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/TcpSpec.scala @@ -77,10 +77,10 @@ class TcpSpec extends StreamSpec(""" val resultFuture = Source.fromPublisher(idle.publisherProbe) .via(Tcp().outgoingConnection(server.address)) - .runFold(ByteString.empty)((acc, in) ⇒ acc ++ in) + .runFold(ByteString.empty)((acc, in) => acc ++ in) val serverConnection = server.waitAccept() - for (in ← testInput) { + for (in <- testInput) { serverConnection.write(in) } @@ -370,7 +370,7 @@ class TcpSpec extends StreamSpec(""" Flow.fromSinkAndSourceMat(Sink.ignore, Source.single(ByteString("Early response")))(Keep.right) val binding = - Tcp().bind(serverAddress.getHostString, serverAddress.getPort, halfClose = false).toMat(Sink.foreach { conn ⇒ + Tcp().bind(serverAddress.getHostString, serverAddress.getPort, halfClose = false).toMat(Sink.foreach { conn => conn.flow.join(writeButIgnoreRead).run() })(Keep.left) .run() @@ -391,7 +391,7 @@ class TcpSpec extends StreamSpec(""" val serverAddress = temporaryServerAddress() val binding = - Tcp().bind(serverAddress.getHostString, serverAddress.getPort, halfClose = false).toMat(Sink.foreach { conn ⇒ + Tcp().bind(serverAddress.getHostString, serverAddress.getPort, halfClose = false).toMat(Sink.foreach { conn => conn.flow.join(Flow[ByteString]).run() })(Keep.left) .run() @@ -425,7 +425,7 @@ class TcpSpec extends StreamSpec(""" Source.single(testMsg) .concat(Source.maybe[ByteString]) .via(Tcp(system2).outgoingConnection(serverAddress)) - .runForeach { msg ⇒ probe.ref ! msg }(mat2) + .runForeach { msg => probe.ref ! msg }(mat2) // Ensure first that the actor is there probe.expectMsg(testMsg) @@ -438,7 +438,7 @@ class TcpSpec extends StreamSpec(""" try { probe.expectMsgType[ActorIdentity].ref.get } catch { - case _: AssertionError | _: NoSuchElementException ⇒ + case _: AssertionError | _: NoSuchElementException => val tree = system2.asInstanceOf[ExtendedActorSystem].printTree fail(s"No TCP selector actor running at [$path], actor tree: $tree") } @@ -486,7 +486,7 @@ class TcpSpec extends StreamSpec(""" val testInput = (0 to 255).map(ByteString(_)) val expectedOutput = ByteString(Array.tabulate(256)(_.asInstanceOf[Byte])) val resultFuture = - Source(testInput).via(Tcp().outgoingConnection(serverAddress)).runFold(ByteString.empty)((acc, in) ⇒ acc ++ in) + Source(testInput).via(Tcp().outgoingConnection(serverAddress)).runFold(ByteString.empty)((acc, in) => acc ++ in) binding.whenUnbound.value should be(None) resultFuture.futureValue should be(expectedOutput) @@ -518,7 +518,7 @@ class TcpSpec extends StreamSpec(""" .via(echoConnection) .via(echoConnection) .via(echoConnection) - .runFold(ByteString.empty)((acc, in) ⇒ acc ++ in) + .runFold(ByteString.empty)((acc, in) => acc ++ in) resultFuture.futureValue should be(expectedOutput) binding.unbind().futureValue @@ -589,8 +589,8 @@ class TcpSpec extends StreamSpec(""" serverSystem.log.info("port open") false } catch { - case _: SocketTimeoutException ⇒ true - case _: SocketException ⇒ true + case _: SocketTimeoutException => true + case _: SocketException => true } import serverSystem.dispatcher @@ -599,7 +599,7 @@ class TcpSpec extends StreamSpec(""" // accept one connection, then cancel .take(1) // keep the accepted request hanging - .map { connection ⇒ + .map { connection => serverGotRequest.success(Done) Future { Await.ready(completeRequest, remainingOrDefault) // wait for the port close below @@ -637,7 +637,7 @@ class TcpSpec extends StreamSpec(""" val (bindingFuture, connection) = Tcp(system).bind("localhost", 0).toMat(Sink.head)(Keep.both).run() - val proxy = connection.map { c ⇒ + val proxy = connection.map { c => c.handleWith(Flow[ByteString]) } @@ -658,12 +658,12 @@ class TcpSpec extends StreamSpec(""" val accept2ConnectionSink: Sink[IncomingConnection, NotUsed] = Flow[IncomingConnection].take(2) - .mapAsync(2) { incoming ⇒ + .mapAsync(2) { incoming => val connectionNr = connectionCounter.incrementAndGet() if (connectionNr == 1) { // echo incoming.flow.joinMat( - Flow[ByteString].mapMaterializedValue { mat ⇒ + Flow[ByteString].mapMaterializedValue { mat => firstClientConnected.trySuccess(()) mat }.watchTermination()(Keep.right) @@ -742,7 +742,7 @@ class TcpSpec extends StreamSpec(""" // also - byte is our framing Flow[ByteString].mapConcat(_.utf8String.toList) .takeWhile(_ != '\n') - .map(c ⇒ ByteString(c)), + .map(c => ByteString(c)), address.getHostName, address.getPort, sslContext, @@ -754,7 +754,7 @@ class TcpSpec extends StreamSpec(""" val chars = "hello\n".toList.map(_.toString) val (connectionF, result) = - Source(chars).map(c ⇒ ByteString(c)) + Source(chars).map(c => ByteString(c)) .concat(Source.maybe) // do not complete it from our side .viaMat(connectionFlow)(Keep.right) .map(_.utf8String) diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/TlsSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/TlsSpec.scala index cc87c6f998..89016bcfc4 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/TlsSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/TlsSpec.scala @@ -17,7 +17,7 @@ import scala.concurrent.Future import scala.concurrent.duration._ import scala.util.Random import akka.actor.ActorSystem -import akka.pattern.{ after ⇒ later } +import akka.pattern.{ after => later } import akka.stream._ import akka.stream.TLSProtocol._ import akka.stream.scaladsl._ @@ -107,10 +107,10 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing val sslContext = initSslContext() - val debug = Flow[SslTlsInbound].map { x ⇒ + val debug = Flow[SslTlsInbound].map { x => x match { - case SessionTruncated ⇒ system.log.debug(s" ----------- truncated ") - case SessionBytes(_, b) ⇒ system.log.debug(s" ----------- (${b.size}) ${b.take(32).utf8String}") + case SessionTruncated => system.log.debug(s" ----------- truncated ") + case SessionBytes(_, b) => system.log.debug(s" ----------- (${b.size}) ${b.take(32).utf8String}") } x } @@ -124,7 +124,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing def name: String = getClass.getName .reverse - .dropWhile(c ⇒ "$0123456789".indexOf(c) != -1) + .dropWhile(c => "$0123456789".indexOf(c) != -1) .takeWhile(_ != '$') .reverse } @@ -150,7 +150,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing def server(flow: Flow[ByteString, ByteString, Any]) = { val server = Tcp() .bind("localhost", 0) - .to(Sink.foreach(c ⇒ c.flow.join(flow).run())) + .to(Sink.foreach(c => c.flow.join(flow).run())) .run() Await.result(server, 2.seconds) } @@ -193,14 +193,14 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing } { - case SessionTruncated ⇒ SendBytes(ByteString("TRUNCATED")) - case SessionBytes(s, b) if session == null ⇒ + case SessionTruncated => SendBytes(ByteString("TRUNCATED")) + case SessionBytes(s, b) if session == null => setSession(s) SendBytes(b) - case SessionBytes(s, b) if s != session ⇒ + case SessionBytes(s, b) if s != session => setSession(s) SendBytes(ByteString("NEWSESSION") ++ b) - case SessionBytes(s, b) ⇒ SendBytes(b) + case SessionBytes(s, b) => SendBytes(b) } } def leftClosing: TLSClosing = IgnoreComplete @@ -215,20 +215,20 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing object SingleBytes extends PayloadScenario { val str = "0123456789" - def inputs = str.map(ch ⇒ SendBytes(ByteString(ch.toByte))) + def inputs = str.map(ch => SendBytes(ByteString(ch.toByte))) def output = ByteString(str) } object MediumMessages extends PayloadScenario { - val strs = "0123456789" map (d ⇒ d.toString * (rnd.nextInt(9000) + 1000)) - def inputs = strs map (s ⇒ SendBytes(ByteString(s))) + val strs = "0123456789" map (d => d.toString * (rnd.nextInt(9000) + 1000)) + def inputs = strs map (s => SendBytes(ByteString(s))) def output = ByteString(strs.foldRight("")(_ ++ _)) } object LargeMessages extends PayloadScenario { // TLS max packet size is 16384 bytes - val strs = "0123456789" map (d ⇒ d.toString * (rnd.nextInt(9000) + 17000)) - def inputs = strs map (s ⇒ SendBytes(ByteString(s))) + val strs = "0123456789" map (d => d.toString * (rnd.nextInt(9000) + 17000)) + def inputs = strs map (s => SendBytes(ByteString(s))) def output = ByteString(strs.foldRight("")(_ ++ _)) } @@ -252,11 +252,11 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing override def flow = Flow[SslTlsInbound] .mapConcat { - case SessionTruncated ⇒ SessionTruncated :: Nil - case SessionBytes(s, bytes) ⇒ bytes.map(b ⇒ SessionBytes(s, ByteString(b))) + case SessionTruncated => SessionTruncated :: Nil + case SessionBytes(s, bytes) => bytes.map(b => SessionBytes(s, ByteString(b))) } .take(5) - .mapAsync(5)(x ⇒ later(500.millis, system.scheduler)(Future.successful(x))) + .mapAsync(5)(x => later(500.millis, system.scheduler)(Future.successful(x))) .via(super.flow) override def rightClosing = IgnoreCancel @@ -269,11 +269,11 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing override def flow = Flow[SslTlsInbound] .mapConcat { - case SessionTruncated ⇒ SessionTruncated :: Nil - case SessionBytes(s, bytes) ⇒ bytes.map(b ⇒ SessionBytes(s, ByteString(b))) + case SessionTruncated => SessionTruncated :: Nil + case SessionBytes(s, bytes) => bytes.map(b => SessionBytes(s, ByteString(b))) } .take(5) - .mapAsync(5)(x ⇒ later(500.millis, system.scheduler)(Future.successful(x))) + .mapAsync(5)(x => later(500.millis, system.scheduler)(Future.successful(x))) .via(super.flow) override def rightClosing = IgnoreBoth @@ -285,7 +285,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing object LHSIgnoresBoth extends PayloadScenario { override def leftClosing = IgnoreBoth val str = "0123456789" - def inputs = str.map(ch ⇒ SendBytes(ByteString(ch.toByte))) + def inputs = str.map(ch => SendBytes(ByteString(ch.toByte))) def output = ByteString(str) } @@ -293,7 +293,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing override def leftClosing = IgnoreBoth override def rightClosing = IgnoreBoth val str = "0123456789" - def inputs = str.map(ch ⇒ SendBytes(ByteString(ch.toByte))) + def inputs = str.map(ch => SendBytes(ByteString(ch.toByte))) def output = ByteString(str) } @@ -318,11 +318,11 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing } { - case SessionTruncated ⇒ SendBytes(ByteString("TRUNCATED")) - case SessionBytes(s, b) if s != session ⇒ + case SessionTruncated => SendBytes(ByteString("TRUNCATED")) + case SessionBytes(s, b) if s != session => setSession(s) SendBytes(ByteString(s.getCipherSuite) ++ b) - case SessionBytes(s, b) ⇒ SendBytes(b) + case SessionBytes(s, b) => SendBytes(b) } } @@ -353,8 +353,8 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing SessionRenegotiationFirstTwo) for { - commPattern ← communicationPatterns - scenario ← scenarios + commPattern <- communicationPatterns + scenario <- scenarios } { s"work in mode ${commPattern.name} while sending ${scenario.name}" in assertAllStagesStopped { val onRHS = debug.via(scenario.flow) @@ -375,7 +375,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing } }) .via(debug) - .collect { case SessionBytes(_, b) ⇒ b } + .collect { case SessionBytes(_, b) => b } .scan(ByteString.empty)(_ ++ _) .via(new Timeout(6.seconds)) .dropWhile(_.size < scenario.output.size) @@ -389,9 +389,9 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing "emit an error if the TLS handshake fails certificate checks" in assertAllStagesStopped { val getError = Flow[SslTlsInbound] - .map[Either[SslTlsInbound, SSLException]](i ⇒ Left(i)) - .recover { case e: SSLException ⇒ Right(e) } - .collect { case Right(e) ⇒ e }.toMat(Sink.head)(Keep.right) + .map[Either[SslTlsInbound, SSLException]](i => Left(i)) + .recover { case e: SSLException => Right(e) } + .collect { case Right(e) => e }.toMat(Sink.head)(Keep.right) val simple = Flow.fromSinkAndSourceMat(getError, Source.maybe[SslTlsOutbound])(Keep.left) @@ -399,7 +399,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing // under error conditions, and has the bonus of matching most actual SSL deployments. val (server, serverErr) = Tcp() .bind("localhost", 0) - .mapAsync(1)(c ⇒ + .mapAsync(1)(c => c.flow.joinMat(serverTls(IgnoreBoth).reversed.joinMat(simple)(Keep.right))(Keep.right).run() ) .toMat(Sink.head)(Keep.both).run() @@ -418,7 +418,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing "reliably cancel subscriptions when TransportIn fails early" in assertAllStagesStopped { val ex = new Exception("hello") val (sub, out1, out2) = - RunnableGraph.fromGraph(GraphDSL.create(Source.asSubscriber[SslTlsOutbound], Sink.head[ByteString], Sink.head[SslTlsInbound])((_, _, _)) { implicit b ⇒ (s, o1, o2) ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Source.asSubscriber[SslTlsOutbound], Sink.head[ByteString], Sink.head[SslTlsInbound])((_, _, _)) { implicit b => (s, o1, o2) => val tls = b.add(clientTls(EagerClose)) s ~> tls.in1; tls.out1 ~> o1 o2 <~ tls.out2; tls.in2 <~ Source.failed(ex) @@ -435,7 +435,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing "reliably cancel subscriptions when UserIn fails early" in assertAllStagesStopped { val ex = new Exception("hello") val (sub, out1, out2) = - RunnableGraph.fromGraph(GraphDSL.create(Source.asSubscriber[ByteString], Sink.head[ByteString], Sink.head[SslTlsInbound])((_, _, _)) { implicit b ⇒ (s, o1, o2) ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Source.asSubscriber[ByteString], Sink.head[ByteString], Sink.head[SslTlsInbound])((_, _, _)) { implicit b => (s, o1, o2) => val tls = b.add(clientTls(EagerClose)) Source.failed[SslTlsOutbound](ex) ~> tls.in1; tls.out1 ~> o1 o2 <~ tls.out2; tls.in2 <~ s @@ -461,7 +461,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing } val inFlow = Flow[SslTlsInbound] - .collect { case SessionBytes(_, b) ⇒ b } + .collect { case SessionBytes(_, b) => b } .scan(ByteString.empty)(_ ++ _) .via(new Timeout(6.seconds)) .dropWhile(_.size < scenario.output.size) @@ -470,7 +470,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing Source(scenario.inputs) .via(outFlow) .via(inFlow) - .map(result ⇒ { + .map(result => { ks.shutdown(); result }) .runWith(Sink.last) @@ -482,8 +482,8 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing def run(hostName: String): Future[akka.Done] = { val rhs = Flow[SslTlsInbound] .map { - case SessionTruncated ⇒ SendBytes(ByteString.empty) - case SessionBytes(_, b) ⇒ SendBytes(b) + case SessionTruncated => SendBytes(ByteString.empty) + case SessionBytes(_, b) => SendBytes(b) } val clientTls = TLS(sslContext, None, cipherSuites, Client, EagerClose, Some((hostName, 80))) val flow = clientTls atop serverTls(EagerClose).reversed join rhs @@ -503,13 +503,13 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing "pass through data" in { val f = Source(1 to 3) - .map(b ⇒ SendBytes(ByteString(b.toByte))) + .map(b => SendBytes(ByteString(b.toByte))) .via(TLSPlacebo() join Flow.apply) .grouped(10) .runWith(Sink.head) val result = Await.result(f, 3.seconds) - result.map(_.bytes) should be((1 to 3).map(b ⇒ ByteString(b.toByte))) - result.map(_.session).foreach(s ⇒ s.getCipherSuite should be("SSL_NULL_WITH_NULL_NULL")) + result.map(_.bytes) should be((1 to 3).map(b => ByteString(b.toByte))) + result.map(_.session).foreach(s => s.getCipherSuite should be("SSL_NULL_WITH_NULL_NULL")) } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/compression/CodecSpecSupport.scala b/akka-stream-tests/src/test/scala/akka/stream/io/compression/CodecSpecSupport.scala index cc5e81c585..0f36b678ad 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/compression/CodecSpecSupport.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/compression/CodecSpecSupport.scala @@ -10,11 +10,11 @@ import akka.testkit.TestKit import akka.util.ByteString import org.scalatest.{ BeforeAndAfterAll, Matchers, Suite } -trait CodecSpecSupport extends Matchers with BeforeAndAfterAll { self: Suite ⇒ +trait CodecSpecSupport extends Matchers with BeforeAndAfterAll { self: Suite => def readAs(string: String, charset: String = "UTF8") = equal(string).matcher[String] compose { (_: ByteString).decodeString(charset) } def hexDump(bytes: ByteString) = bytes.map("%02x".format(_)).mkString - def fromHexDump(dump: String) = dump.grouped(2).toArray.map(chars ⇒ Integer.parseInt(new String(chars), 16).toByte) + def fromHexDump(dump: String) = dump.grouped(2).toArray.map(chars => Integer.parseInt(new String(chars), 16).toByte) def printBytes(i: Int, id: String) = { def byte(i: Int) = (i & 0xFF).toHexString diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/compression/CoderSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/io/compression/CoderSpec.scala index 31b66e5a95..f3e3d2314b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/compression/CoderSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/compression/CoderSpec.scala @@ -86,8 +86,8 @@ abstract class CoderSpec(codecName: String) extends WordSpec with CodecSpecSuppo "support chunked round-trip encoding/decoding" in { val chunks = largeTextBytes.grouped(512).toVector val comp = newCompressor() - val compressedChunks = chunks.map { chunk ⇒ comp.compressAndFlush(chunk) } :+ comp.finish() - val uncompressed = decodeFromIterator(() ⇒ compressedChunks.iterator) + val compressedChunks = chunks.map { chunk => comp.compressAndFlush(chunk) } :+ comp.finish() + val uncompressed = decodeFromIterator(() => compressedChunks.iterator) uncompressed should readAs(largeText) } @@ -119,7 +119,7 @@ abstract class CoderSpec(codecName: String) extends WordSpec with CodecSpecSuppo .limit(4200).runWith(Sink.seq) .awaitResult(3.seconds) - forAll(resultBs) { bs ⇒ + forAll(resultBs) { bs => bs.length should be < limit bs.forall(_ == 1) should equal(true) } @@ -136,7 +136,7 @@ abstract class CoderSpec(codecName: String) extends WordSpec with CodecSpecSuppo ByteString(Array.fill(size)(1.toByte)) val sizesAfterRoundtrip = - Source.fromIterator(() ⇒ sizes.toIterator.map(createByteString)) + Source.fromIterator(() => sizes.toIterator.map(createByteString)) .via(encoderFlow) .via(decoderFlow()) .runFold(Seq.empty[Int])(_ :+ _.size) @@ -187,6 +187,6 @@ abstract class CoderSpec(codecName: String) extends WordSpec with CodecSpecSuppo def decodeChunks(input: Source[ByteString, NotUsed]): ByteString = input.via(decoderFlow()).join.awaitResult(3.seconds) // TODO make it use remaining? - def decodeFromIterator(iterator: () ⇒ Iterator[ByteString]): ByteString = + def decodeFromIterator(iterator: () => Iterator[ByteString]): ByteString = Await.result(Source.fromIterator(iterator).via(decoderFlow()).join, 3.seconds) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/io/compression/CompressionTestingTools.scala b/akka-stream-tests/src/test/scala/akka/stream/io/compression/CompressionTestingTools.scala index 9a8d7ec893..cd9d24b31b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/io/compression/CompressionTestingTools.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/io/compression/CompressionTestingTools.scala @@ -21,8 +21,8 @@ object CompressionTestingTools { def awaitResult(atMost: Duration): T = { Await.ready(future, atMost) future.value.get match { - case Success(t) ⇒ t - case Failure(ex) ⇒ throw new RuntimeException("Trying to await result of failed Future, see the cause for the original problem.", ex) + case Success(t) => t + case Failure(ex) => throw new RuntimeException("Trying to await result of failed Future, see the cause for the original problem.", ex) } } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefBackpressureSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefBackpressureSinkSpec.scala index 265d7adeb3..ab07d19c8a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefBackpressureSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefBackpressureSinkSpec.scala @@ -22,12 +22,12 @@ object ActorRefBackpressureSinkSpec { class Fw(ref: ActorRef) extends Actor { def receive = { - case `initMessage` ⇒ + case `initMessage` => sender() ! ackMessage ref forward initMessage - case `completeMessage` ⇒ + case `completeMessage` => ref forward completeMessage - case msg: Int ⇒ + case msg: Int => sender() ! ackMessage ref forward msg } @@ -39,9 +39,9 @@ object ActorRefBackpressureSinkSpec { var actorRef: ActorRef = Actor.noSender def receive = { - case TriggerAckMessage ⇒ + case TriggerAckMessage => actorRef ! ackMessage - case msg ⇒ + case msg => actorRef = sender() ref forward msg } @@ -128,13 +128,13 @@ class ActorRefBackpressureSinkSpec extends StreamSpec { .withAttributes(inputBuffer(bufferSize, bufferSize)) val bufferFullProbe = Promise[akka.Done.type] Source(1 to streamElementCount) - .alsoTo(Flow[Int].drop(bufferSize - 1).to(Sink.foreach(_ ⇒ bufferFullProbe.trySuccess(akka.Done)))) + .alsoTo(Flow[Int].drop(bufferSize - 1).to(Sink.foreach(_ => bufferFullProbe.trySuccess(akka.Done)))) .to(sink) .run() bufferFullProbe.future.futureValue should ===(akka.Done) expectMsg(initMessage) fw ! TriggerAckMessage - for (i ← 1 to streamElementCount) { + for (i <- 1 to streamElementCount) { expectMsg(i) fw ! TriggerAckMessage } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefSinkSpec.scala index 8d2425b0a4..713009a718 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefSinkSpec.scala @@ -15,7 +15,7 @@ import akka.actor.Props object ActorRefSinkSpec { case class Fw(ref: ActorRef) extends Actor { def receive = { - case msg ⇒ ref forward msg + case msg => ref forward msg } } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefSourceSpec.scala index 702f75214a..3fc945b5bb 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ActorRefSourceSpec.scala @@ -36,29 +36,29 @@ class ActorRefSourceSpec extends StreamSpec { val s = TestSubscriber.manualProbe[Int]() val ref = Source.actorRef(100, OverflowStrategy.dropHead).to(Sink.fromSubscriber(s)).run() val sub = s.expectSubscription - for (n ← 1 to 20) ref ! n + for (n <- 1 to 20) ref ! n sub.request(10) - for (n ← 1 to 10) s.expectNext(n) + for (n <- 1 to 10) s.expectNext(n) sub.request(10) - for (n ← 11 to 20) s.expectNext(n) + for (n <- 11 to 20) s.expectNext(n) - for (n ← 200 to 399) ref ! n + for (n <- 200 to 399) ref ! n sub.request(100) - for (n ← 300 to 399) s.expectNext(n) + for (n <- 300 to 399) s.expectNext(n) } "drop new when full and with dropNew strategy" in { val (ref, sub) = Source.actorRef(100, OverflowStrategy.dropNew).toMat(TestSink.probe[Int])(Keep.both).run() - for (n ← 1 to 20) ref ! n + for (n <- 1 to 20) ref ! n sub.request(10) - for (n ← 1 to 10) sub.expectNext(n) + for (n <- 1 to 10) sub.expectNext(n) sub.request(10) - for (n ← 11 to 20) sub.expectNext(n) + for (n <- 11 to 20) sub.expectNext(n) - for (n ← 200 to 399) ref ! n + for (n <- 200 to 399) ref ! n sub.request(100) - for (n ← 200 to 299) sub.expectNext(n) + for (n <- 200 to 299) sub.expectNext(n) } "terminate when the stream is cancelled" in assertAllStagesStopped { diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/AttributesSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/AttributesSpec.scala index 706e6c8a25..c0789314b9 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/AttributesSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/AttributesSpec.scala @@ -83,7 +83,7 @@ object AttributesSpec { val out = Outlet[String]("out") override val shape = SourceShape.of(out) override protected def initialAttributes: Attributes = - initialDispatcher.fold(Attributes.none)(name ⇒ ActorAttributes.dispatcher(name)) + initialDispatcher.fold(Attributes.none)(name => ActorAttributes.dispatcher(name)) def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) { setHandler(out, new OutHandler { def onPull(): Unit = { diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/BidiFlowSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/BidiFlowSpec.scala index 1cea9ae762..874f522660 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/BidiFlowSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/BidiFlowSpec.scala @@ -20,17 +20,17 @@ class BidiFlowSpec extends StreamSpec { implicit val materializer = ActorMaterializer() val bidi = BidiFlow.fromFlows( - Flow[Int].map(x ⇒ x.toLong + 2).withAttributes(name("top")), + Flow[Int].map(x => x.toLong + 2).withAttributes(name("top")), Flow[ByteString].map(_.decodeString("UTF-8")).withAttributes(name("bottom"))) val inverse = BidiFlow.fromFlows( - Flow[Long].map(x ⇒ x.toInt + 2).withAttributes(name("top")), + Flow[Long].map(x => x.toInt + 2).withAttributes(name("top")), Flow[String].map(ByteString(_)).withAttributes(name("bottom"))) - val bidiMat = BidiFlow.fromGraph(GraphDSL.create(Sink.head[Int]) { implicit b ⇒ s ⇒ + val bidiMat = BidiFlow.fromGraph(GraphDSL.create(Sink.head[Int]) { implicit b => s => Source.single(42) ~> s - val top = b.add(Flow[Int].map(x ⇒ x.toLong + 2)) + val top = b.add(Flow[Int].map(x => x.toLong + 2)) val bottom = b.add(Flow[ByteString].map(_.decodeString("UTF-8"))) BidiShape(top.in, top.out, bottom.in, bottom.out) }) @@ -41,7 +41,7 @@ class BidiFlowSpec extends StreamSpec { "A BidiFlow" must { "work top/bottom in isolation" in { - val (top, bottom) = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Long], Sink.head[String])(Keep.both) { implicit b ⇒ (st, sb) ⇒ + val (top, bottom) = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Long], Sink.head[String])(Keep.both) { implicit b => (st, sb) => val s = b.add(bidi) Source.single(1) ~> s.in1; s.out1 ~> st @@ -54,7 +54,7 @@ class BidiFlowSpec extends StreamSpec { } "work as a Flow that is open on the left" in { - val f = bidi.join(Flow[Long].map(x ⇒ ByteString(s"Hello $x"))) + val f = bidi.join(Flow[Long].map(x => ByteString(s"Hello $x"))) val result = Source(List(1, 2, 3)).via(f).limit(10).runWith(Sink.seq) Await.result(result, 1.second) should ===(Seq("Hello 3", "Hello 4", "Hello 5")) } @@ -79,15 +79,15 @@ class BidiFlowSpec extends StreamSpec { } "materialize to its value" in { - val f = RunnableGraph.fromGraph(GraphDSL.create(bidiMat) { implicit b ⇒ bidi ⇒ - Flow[String].map(Integer.valueOf(_).toInt) <~> bidi <~> Flow[Long].map(x ⇒ ByteString(s"Hello $x")) + val f = RunnableGraph.fromGraph(GraphDSL.create(bidiMat) { implicit b => bidi => + Flow[String].map(Integer.valueOf(_).toInt) <~> bidi <~> Flow[Long].map(x => ByteString(s"Hello $x")) ClosedShape }).run() Await.result(f, 1.second) should ===(42) } "combine materialization values" in assertAllStagesStopped { - val left = Flow.fromGraph(GraphDSL.create(Sink.head[Int]) { implicit b ⇒ sink ⇒ + val left = Flow.fromGraph(GraphDSL.create(Sink.head[Int]) { implicit b => sink => val bcast = b.add(Broadcast[Int](2)) val merge = b.add(Merge[Int](2)) val flow = b.add(Flow[String].map(Integer.valueOf(_).toInt)) @@ -96,7 +96,7 @@ class BidiFlowSpec extends StreamSpec { flow ~> merge FlowShape(flow.in, merge.out) }) - val right = Flow.fromGraph(GraphDSL.create(Sink.head[immutable.Seq[Long]]) { implicit b ⇒ sink ⇒ + val right = Flow.fromGraph(GraphDSL.create(Sink.head[immutable.Seq[Long]]) { implicit b => sink => val flow = b.add(Flow[Long].grouped(10)) flow ~> sink FlowShape(flow.in, b.add(Source.single(ByteString("10"))).out) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/CollectionSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/CollectionSinkSpec.scala index 3d43e1be16..64a7bd9e68 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/CollectionSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/CollectionSinkSpec.scala @@ -28,7 +28,7 @@ class CollectionSinkSpec extends StreamSpec { "return an empty Seq[T] from an empty Source" in { val input: immutable.Seq[Int] = Nil - val future: Future[immutable.Seq[Int]] = Source.fromIterator(() ⇒ input.iterator).runWith(Sink.collection) + val future: Future[immutable.Seq[Int]] = Source.fromIterator(() => input.iterator).runWith(Sink.collection) val result: immutable.Seq[Int] = Await.result(future, remainingOrDefault) result should be(input) } @@ -51,7 +51,7 @@ class CollectionSinkSpec extends StreamSpec { "return an empty Vector[T] from an empty Source" in { val input = Nil - val future: Future[immutable.Vector[Int]] = Source.fromIterator(() ⇒ input.iterator).runWith(Sink.collection[Int, Vector[Int]]) + val future: Future[immutable.Vector[Int]] = Source.fromIterator(() => input.iterator).runWith(Sink.collection[Int, Vector[Int]]) val result: immutable.Vector[Int] = Await.result(future, remainingOrDefault) result should be(Vector.empty[Int]) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/CoupledTerminationFlowSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/CoupledTerminationFlowSpec.scala index 6d15f3a65c..e2c82abe3b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/CoupledTerminationFlowSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/CoupledTerminationFlowSpec.scala @@ -63,7 +63,7 @@ class CoupledTerminationFlowSpec extends StreamSpec with ScriptedTest { "Completion" must { - (effectsTable \ "tr").foreach { testCase ⇒ + (effectsTable \ "tr").foreach { testCase => val rules = testCase \\ "td" val outerRule = rules.head.toString() val innerSinkRule = rules.drop(1).head.toString() @@ -87,7 +87,7 @@ class CoupledTerminationFlowSpec extends StreamSpec with ScriptedTest { "completed out:Source => complete in:Sink" in { val probe = TestProbe() val f = Flow.fromSinkAndSourceCoupledMat( - Sink.onComplete(d ⇒ probe.ref ! "done"), + Sink.onComplete(d => probe.ref ! "done"), Source.empty)(Keep.none) // completes right away, should complete the sink as well f.runWith(Source.maybe, Sink.ignore) // these do nothing. @@ -117,7 +117,7 @@ class CoupledTerminationFlowSpec extends StreamSpec with ScriptedTest { "error wrapped Sink when wrapped Source errors " in { val probe = TestProbe() val f = Flow.fromSinkAndSourceCoupledMat( - Sink.onComplete(e ⇒ probe.ref ! e.failed.get.getMessage), + Sink.onComplete(e => probe.ref ! e.failed.get.getMessage), Source.failed(new Exception("BOOM!")))(Keep.none) // completes right away, should complete the sink as well f.runWith(Source.maybe, Sink.ignore) // these do nothing. @@ -139,13 +139,13 @@ class CoupledTerminationFlowSpec extends StreamSpec with ScriptedTest { } - def interpretOuter(rule: String): (Source[String, NotUsed], Sink[String, NotUsed], () ⇒ Any) = { + def interpretOuter(rule: String): (Source[String, NotUsed], Sink[String, NotUsed], () => Any) = { val probe = TestProbe() val causeUpstreamCompletes = Source.empty[String] val causeUpstreamErrors = Source.failed(new Exception("Boom")) val causeDownstreamCancels = Sink.cancelled[String] - val downstreamEffect = Sink.onComplete(s ⇒ probe.ref ! s) + val downstreamEffect = Sink.onComplete(s => probe.ref ! s) val upstreamEffect = Source.fromPublisher(new Publisher[String] { override def subscribe(s: Subscriber[_ >: String]): Unit = s.onSubscribe(new Subscription { override def cancel(): Unit = probe.ref ! "cancel-received" @@ -153,37 +153,37 @@ class CoupledTerminationFlowSpec extends StreamSpec with ScriptedTest { override def request(n: Long): Unit = () }) }) - val assertCancel = () ⇒ { + val assertCancel = () => { val m = probe.expectMsgType[String] m should ===("cancel-received") } - val assertComplete = () ⇒ { + val assertComplete = () => { val m = probe.expectMsgType[Try[Done]] m.isFailure should ===(false) } - val assertCompleteAndCancel = () ⇒ { + val assertCompleteAndCancel = () => { probe.expectMsgPF() { - case Success(v) ⇒ // good - case "cancel-received" ⇒ // good + case Success(v) => // good + case "cancel-received" => // good } probe.expectMsgPF() { - case Success(v) ⇒ // good - case "cancel-received" ⇒ // good + case Success(v) => // good + case "cancel-received" => // good } } - val assertError = () ⇒ { + val assertError = () => { val m = probe.expectMsgType[Try[Done]] m.isFailure should ===(true) m.failed.get.getMessage should include("Boom") } - val assertErrorAndCancel = () ⇒ { + val assertErrorAndCancel = () => { probe.expectMsgPF() { - case Failure(ex) ⇒ // good - case "cancel-received" ⇒ // good + case Failure(ex) => // good + case "cancel-received" => // good } probe.expectMsgPF() { - case Failure(ex) ⇒ // good - case "cancel-received" ⇒ // good + case Failure(ex) => // good + case "cancel-received" => // good } } @@ -205,21 +205,21 @@ class CoupledTerminationFlowSpec extends StreamSpec with ScriptedTest { } else throw UnableToInterpretRule(rule) } - def interpretInnerSink(rule: String): (Sink[String, NotUsed], () ⇒ Assertion) = { + def interpretInnerSink(rule: String): (Sink[String, NotUsed], () => Assertion) = { val probe = TestProbe() val causeCancel = Sink.cancelled[String] - val catchEffect = Sink.onComplete(s ⇒ probe.ref ! s) - val assertComplete = () ⇒ { + val catchEffect = Sink.onComplete(s => probe.ref ! s) + val assertComplete = () => { val m = probe.expectMsgType[Try[Done]] m.isFailure should ===(false) } - val assertError = () ⇒ { + val assertError = () => { val m = probe.expectMsgType[Try[Done]] m.isFailure should ===(true) m.failed.get.getMessage should include("Boom") } - val assertionOK = () ⇒ 1 should ===(1) + val assertionOK = () => 1 should ===(1) if (rule contains "cause") { if (rule.contains("cancels")) (causeCancel, assertionOK) @@ -231,21 +231,21 @@ class CoupledTerminationFlowSpec extends StreamSpec with ScriptedTest { } else throw UnableToInterpretRule(rule) } - def interpretInnerSource(rule: String): (Source[String, NotUsed], () ⇒ Assertion) = { + def interpretInnerSource(rule: String): (Source[String, NotUsed], () => Assertion) = { val probe = TestProbe() val causeComplete = Source.empty[String] val causeError = Source.failed(new Exception("Boom")) - val catchEffect = Source.maybe[String].mapMaterializedValue(p ⇒ { - p.future.onComplete(t ⇒ probe.ref ! t) + val catchEffect = Source.maybe[String].mapMaterializedValue(p => { + p.future.onComplete(t => probe.ref ! t) NotUsed }) - val assertCancel = () ⇒ { + val assertCancel = () => { val m = probe.expectMsgType[Try[Option[String]]] m.isFailure should ===(false) m.get should ===(None) // downstream cancelled } - val assertionOK = () ⇒ 1 should ===(1) + val assertionOK = () => 1 should ===(1) if (rule contains "cause") { if (rule.contains("complete")) (causeComplete, assertionOK) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowAppendSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowAppendSpec.scala index eea314dc02..72d8ec0cdf 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowAppendSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowAppendSpec.scala @@ -17,25 +17,25 @@ class FlowAppendSpec extends StreamSpec with River { implicit val materializer = ActorMaterializer(settings) "Flow" should { - "append Flow" in riverOf[String] { subscriber ⇒ + "append Flow" in riverOf[String] { subscriber => val flow = Flow[Int].via(otherFlow) Source(elements).via(flow).to(Sink.fromSubscriber(subscriber)).run() } - "append Sink" in riverOf[String] { subscriber ⇒ + "append Sink" in riverOf[String] { subscriber => val sink = Flow[Int].to(otherFlow.to(Sink.fromSubscriber(subscriber))) Source(elements).to(sink).run() } } "Source" should { - "append Flow" in riverOf[String] { subscriber ⇒ + "append Flow" in riverOf[String] { subscriber => Source(elements) .via(otherFlow) .to(Sink.fromSubscriber(subscriber)).run() } - "append Sink" in riverOf[String] { subscriber ⇒ + "append Sink" in riverOf[String] { subscriber => Source(elements) .to(otherFlow.to(Sink.fromSubscriber(subscriber))) .run() @@ -44,19 +44,19 @@ class FlowAppendSpec extends StreamSpec with River { } -trait River { self: Matchers ⇒ +trait River { self: Matchers => val elements = 1 to 10 val otherFlow = Flow[Int].map(_.toString) - def riverOf[T](flowConstructor: Subscriber[T] ⇒ Unit)(implicit system: ActorSystem) = { + def riverOf[T](flowConstructor: Subscriber[T] => Unit)(implicit system: ActorSystem) = { val subscriber = TestSubscriber.manualProbe[T]() flowConstructor(subscriber) val subscription = subscriber.expectSubscription() subscription.request(elements.size) - elements.foreach { el ⇒ + elements.foreach { el => subscriber.expectNext() shouldBe el.toString } subscription.request(1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowAskSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowAskSpec.scala index 9623c52467..e74d6e9135 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowAskSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowAskSpec.scala @@ -23,13 +23,13 @@ object FlowAskSpec { class Replier extends Actor { override def receive: Receive = { - case msg: Int ⇒ sender() ! Reply(msg) + case msg: Int => sender() ! Reply(msg) } } class ReplyAndProxy(to: ActorRef) extends Actor { override def receive: Receive = { - case msg: Int ⇒ + case msg: Int => to ! msg sender() ! Reply(msg) } @@ -37,7 +37,7 @@ object FlowAskSpec { class RandomDelaysReplier extends Actor { override def receive: Receive = { - case msg: Int ⇒ + case msg: Int => import context.dispatcher val replyTo = sender() @@ -50,21 +50,21 @@ object FlowAskSpec { class StatusReplier extends Actor { override def receive: Receive = { - case msg: Int ⇒ sender() ! akka.actor.Status.Success(Reply(msg)) + case msg: Int => sender() ! akka.actor.Status.Success(Reply(msg)) } } class FailOn(n: Int) extends Actor { override def receive: Receive = { - case `n` ⇒ sender() ! akka.actor.Status.Failure(new Exception(s"Booming for $n!")) - case msg: Int ⇒ sender() ! akka.actor.Status.Success(Reply(msg)) + case `n` => sender() ! akka.actor.Status.Failure(new Exception(s"Booming for $n!")) + case msg: Int => sender() ! akka.actor.Status.Success(Reply(msg)) } } class FailOnAllExcept(n: Int) extends Actor { override def receive: Receive = { - case `n` ⇒ sender() ! akka.actor.Status.Success(Reply(n)) - case msg: Int ⇒ sender() ! akka.actor.Status.Failure(new Exception(s"Booming for $n!")) + case `n` => sender() ! akka.actor.Status.Success(Reply(n)) + case msg: Int => sender() ! akka.actor.Status.Failure(new Exception(s"Booming for $n!")) } } @@ -140,7 +140,7 @@ class FlowAskSpec extends StreamSpec { val p = Source(1 to 50).ask[Reply](4)(replyRandomDelays).to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(1000) - for (n ← 1 to 50) c.expectNext(Reply(n)) + for (n <- 1 to 50) c.expectNext(Reply(n)) c.expectComplete() } @@ -180,7 +180,7 @@ class FlowAskSpec extends StreamSpec { val input = "a" :: "b" :: "c" :: "d" :: "e" :: "f" :: Nil - val elements = Source.fromIterator(() ⇒ input.iterator) + val elements = Source.fromIterator(() => input.iterator) .ask[String](5)(p.ref) .withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider)) .runWith(Sink.seq) @@ -219,7 +219,7 @@ class FlowAskSpec extends StreamSpec { .to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) - for (n ← List(1, 2, 4, 5)) c.expectNext(Reply(n)) + for (n <- List(1, 2, 4, 5)) c.expectNext(Reply(n)) c.expectComplete() } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBatchSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBatchSpec.scala index 28c41da824..3362e27fd8 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBatchSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBatchSpec.scala @@ -23,10 +23,10 @@ class FlowBatchSpec extends StreamSpec { val publisher = TestPublisher.probe[Int]() val subscriber = TestSubscriber.manualProbe[Int]() - Source.fromPublisher(publisher).batch(max = 2, seed = i ⇒ i)(aggregate = _ + _).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).batch(max = 2, seed = i => i)(aggregate = _ + _).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() - for (i ← 1 to 100) { + for (i <- 1 to 100) { sub.request(1) publisher.sendNext(i) subscriber.expectNext(i) @@ -39,10 +39,10 @@ class FlowBatchSpec extends StreamSpec { val publisher = TestPublisher.probe[Int]() val subscriber = TestSubscriber.manualProbe[List[Int]]() - Source.fromPublisher(publisher).batch(max = Long.MaxValue, seed = i ⇒ List(i))(aggregate = (ints, i) ⇒ i :: ints).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).batch(max = Long.MaxValue, seed = i => List(i))(aggregate = (ints, i) => i :: ints).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() - for (i ← 1 to 10) { + for (i <- 1 to 10) { publisher.sendNext(i) } subscriber.expectNoMsg(1.second) @@ -53,8 +53,8 @@ class FlowBatchSpec extends StreamSpec { "work on a variable rate chain" in { val future = Source(1 to 1000) - .batch(max = 100, seed = i ⇒ i)(aggregate = (sum, i) ⇒ sum + i) - .map { i ⇒ if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } + .batch(max = 100, seed = i => i)(aggregate = (sum, i) => sum + i) + .map { i => if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } .runFold(0)(_ + _) Await.result(future, 10.seconds) should be(500500) } @@ -63,7 +63,7 @@ class FlowBatchSpec extends StreamSpec { val publisher = TestPublisher.probe[Int]() val subscriber = TestSubscriber.manualProbe[Int]() - Source.fromPublisher(publisher).batch(max = 2, seed = i ⇒ i)(aggregate = _ + _).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).batch(max = 2, seed = i => i)(aggregate = _ + _).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() sub.request(1) @@ -90,7 +90,7 @@ class FlowBatchSpec extends StreamSpec { "work with a buffer and fold" in { val future = Source(1 to 50) - .batch(max = Long.MaxValue, seed = i ⇒ i)(aggregate = _ + _) + .batch(max = Long.MaxValue, seed = i => i)(aggregate = _ + _) .buffer(50, OverflowStrategy.backpressure) .runFold(0)(_ + _) Await.result(future, 3.seconds) should be((1 to 50).sum) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBatchWeightedSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBatchWeightedSpec.scala index fbaf1d6aa2..d2a649a048 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBatchWeightedSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBatchWeightedSpec.scala @@ -20,7 +20,7 @@ class FlowBatchWeightedSpec extends StreamSpec { val publisher = TestPublisher.probe[Int]() val subscriber = TestSubscriber.manualProbe[Int]() - Source.fromPublisher(publisher).batchWeighted(max = 3, _ ⇒ 4, seed = i ⇒ i)(aggregate = _ + _).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).batchWeighted(max = 3, _ => 4, seed = i => i)(aggregate = _ + _).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() publisher.sendNext(1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBufferSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBufferSpec.scala index 9934aec504..8b15a4ce16 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBufferSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowBufferSpec.scala @@ -55,10 +55,10 @@ class FlowBufferSpec extends StreamSpec { val sub = subscriber.expectSubscription() // Fill up buffer - for (i ← 1 to 100) publisher.sendNext(i) + for (i <- 1 to 100) publisher.sendNext(i) // drain - for (i ← 1 to 100) { + for (i <- 1 to 100) { sub.request(1) subscriber.expectNext(i) } @@ -73,13 +73,13 @@ class FlowBufferSpec extends StreamSpec { val sub = subscriber.expectSubscription() // Fill up buffer - for (i ← 1 to 200) publisher.sendNext(i) + for (i <- 1 to 200) publisher.sendNext(i) // The next request would be otherwise in race with the last onNext in the above loop subscriber.expectNoMsg(500.millis) // drain - for (i ← 101 to 200) { + for (i <- 101 to 200) { sub.request(1) subscriber.expectNext(i) } @@ -102,13 +102,13 @@ class FlowBufferSpec extends StreamSpec { val sub = subscriber.expectSubscription() // Fill up buffer - for (i ← 1 to 200) publisher.sendNext(i) + for (i <- 1 to 200) publisher.sendNext(i) // The next request would be otherwise in race with the last onNext in the above loop subscriber.expectNoMsg(500.millis) // drain - for (i ← 1 to 99) { + for (i <- 1 to 99) { sub.request(1) subscriber.expectNext(i) } @@ -134,13 +134,13 @@ class FlowBufferSpec extends StreamSpec { val sub = subscriber.expectSubscription() // Fill up buffer - for (i ← 1 to 150) publisher.sendNext(i) + for (i <- 1 to 150) publisher.sendNext(i) // The next request would be otherwise in race with the last onNext in the above loop subscriber.expectNoMsg(500.millis) // drain - for (i ← 101 to 150) { + for (i <- 101 to 150) { sub.request(1) subscriber.expectNext(i) } @@ -161,13 +161,13 @@ class FlowBufferSpec extends StreamSpec { subscriber.ensureSubscription() // Fill up buffer - for (i ← 1 to 150) publisher.sendNext(i) + for (i <- 1 to 150) publisher.sendNext(i) // The next request would be otherwise in race with the last onNext in the above loop subscriber.expectNoMsg(500.millis) // drain - for (i ← 1 to 100) { + for (i <- 1 to 100) { subscriber.requestNext(i) } @@ -188,23 +188,23 @@ class FlowBufferSpec extends StreamSpec { val sub = subscriber.expectSubscription() // Fill up buffer - for (i ← 1 to 100) publisher.sendNext(i) + for (i <- 1 to 100) publisher.sendNext(i) // drain - for (i ← 1 to 10) { + for (i <- 1 to 10) { sub.request(1) subscriber.expectNext(i) } // overflow the buffer - for (i ← 101 to 111) publisher.sendNext(i) + for (i <- 101 to 111) publisher.sendNext(i) publisher.expectCancellation() val error = new BufferOverflowException("Buffer overflow (max capacity was: 100)!") subscriber.expectError(error) } - for (strategy ← List(OverflowStrategy.dropHead, OverflowStrategy.dropTail, OverflowStrategy.dropBuffer)) { + for (strategy <- List(OverflowStrategy.dropHead, OverflowStrategy.dropTail, OverflowStrategy.dropBuffer)) { s"work with $strategy if buffer size of one" in { @@ -215,7 +215,7 @@ class FlowBufferSpec extends StreamSpec { val sub = subscriber.expectSubscription() // Fill up buffer - for (i ← 1 to 200) publisher.sendNext(i) + for (i <- 1 to 200) publisher.sendNext(i) // The request below is in race otherwise with the onNext(200) above subscriber.expectNoMsg(500.millis) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowCollectSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowCollectSpec.scala index 09011c9e98..456e24da9c 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowCollectSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowCollectSpec.scala @@ -9,7 +9,7 @@ import akka.stream.Supervision._ import akka.stream.testkit.Utils.TE import akka.stream.testkit.scaladsl.TestSink -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ random } +import java.util.concurrent.ThreadLocalRandom.{ current => random } import akka.stream.{ ActorMaterializer, ActorMaterializerSettings } import akka.stream.testkit.{ StreamSpec, ScriptedTest } @@ -22,16 +22,16 @@ class FlowCollectSpec extends StreamSpec with ScriptedTest { "A Collect" must { "collect" in { - def script = Script(TestConfig.RandomTestRange map { _ ⇒ + def script = Script(TestConfig.RandomTestRange map { _ => val x = random.nextInt(0, 10000) - Seq(x) → (if ((x & 1) == 0) Seq((x * x).toString) else Seq.empty[String]) + Seq(x) -> (if ((x & 1) == 0) Seq((x * x).toString) else Seq.empty[String]) }: _*) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.collect { case x if x % 2 == 0 ⇒ (x * x).toString })) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.collect { case x if x % 2 == 0 => (x * x).toString })) } "restart when Collect throws" in { val pf: PartialFunction[Int, Int] = - { case x: Int ⇒ if (x == 2) throw TE("") else x } + { case x: Int => if (x == 2) throw TE("") else x } Source(1 to 3).collect(pf).withAttributes(supervisionStrategy(restartingDecider)) .runWith(TestSink.probe[Int]) .request(1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConcatAllSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConcatAllSpec.scala index ca442257e7..4ef0aa2060 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConcatAllSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConcatAllSpec.scala @@ -37,7 +37,7 @@ class FlowConcatAllSpec extends StreamSpec { main.flatMapConcat(ConstantFun.scalaIdentityFunction).to(Sink.fromSubscriber(subscriber)).run() val subscription = subscriber.expectSubscription() subscription.request(10) - for (i ← 1 to 10) + for (i <- 1 to 10) subscriber.expectNext() shouldBe i subscription.request(1) subscriber.expectComplete() @@ -53,7 +53,7 @@ class FlowConcatAllSpec extends StreamSpec { .flatMapConcat(ConstantFun.scalaIdentityFunction) .runWith(Sink.fromSubscriber(subscriber)) - for (i ← 1 to 10) + for (i <- 1 to 10) subscriber.requestNext() shouldBe i subscriber.request(1) @@ -106,7 +106,7 @@ class FlowConcatAllSpec extends StreamSpec { "on onError on opening substream, cancel the master stream and signal error " in assertAllStagesStopped { val publisher = TestPublisher.manualProbe[Source[Int, _]]() val subscriber = TestSubscriber.manualProbe[Int]() - Source.fromPublisher(publisher).flatMapConcat(_ ⇒ throw testException).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).flatMapConcat(_ => throw testException).to(Sink.fromSubscriber(subscriber)).run() val upstream = publisher.expectSubscription() val downstream = subscriber.expectSubscription() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConcatSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConcatSpec.scala index 5619566277..26bb7d3944 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConcatSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConcatSpec.scala @@ -38,7 +38,7 @@ class FlowConcatSpec extends BaseTwoStreamsSetup { res.subscribe(subs) val sub = subs.expectSubscription() sub.request(9) - (1 to 6).foreach(e ⇒ subs.expectNext(e.toString + "-s")) + (1 to 6).foreach(e => subs.expectNext(e.toString + "-s")) subs.expectComplete() } @@ -55,7 +55,7 @@ class FlowConcatSpec extends BaseTwoStreamsSetup { res.subscribe(subs) val sub = subs.expectSubscription() sub.request(9) - (1 to 6).foreach(e ⇒ subs.expectNext(e.toString + "-s")) + (1 to 6).foreach(e => subs.expectNext(e.toString + "-s")) subs.expectComplete() } @@ -98,7 +98,7 @@ class FlowConcatSpec extends BaseTwoStreamsSetup { val subscriber = setup(nonemptyPublisher(1 to 4), failedPublisher) subscriber.expectSubscription().request(5) - val errorSignalled = (1 to 4).foldLeft(false)((errorSignalled, e) ⇒ + val errorSignalled = (1 to 4).foldLeft(false)((errorSignalled, e) => if (!errorSignalled) subscriber.expectNextOrError(e, TestException).isLeft else true) if (!errorSignalled) subscriber.expectSubscriptionAndError(TestException) } @@ -112,7 +112,7 @@ class FlowConcatSpec extends BaseTwoStreamsSetup { val subscriber = setup(nonemptyPublisher(1 to 4), soonToFailPublisher) subscriber.expectSubscription().request(5) - val errorSignalled = (1 to 4).foldLeft(false)((errorSignalled, e) ⇒ + val errorSignalled = (1 to 4).foldLeft(false)((errorSignalled, e) => if (!errorSignalled) subscriber.expectNextOrError(e, TestException).isLeft else true) if (!errorSignalled) subscriber.expectSubscriptionAndError(TestException) } @@ -138,7 +138,7 @@ class FlowConcatSpec extends BaseTwoStreamsSetup { m1.isInstanceOf[NotUsed] should be(true) m2.isInstanceOf[NotUsed] should be(true) - runnable.mapMaterializedValue((_) ⇒ "boo").run() should be("boo") + runnable.mapMaterializedValue((_) => "boo").run() should be("boo") } "work with Flow DSL" in { @@ -152,7 +152,7 @@ class FlowConcatSpec extends BaseTwoStreamsSetup { m2.isInstanceOf[NotUsed] should be(true) m3.isInstanceOf[NotUsed] should be(true) - runnable.mapMaterializedValue((_) ⇒ "boo").run() should be("boo") + runnable.mapMaterializedValue((_) => "boo").run() should be("boo") } "work with Flow DSL2" in { @@ -160,7 +160,7 @@ class FlowConcatSpec extends BaseTwoStreamsSetup { Await.result(Source(1 to 5).viaMat(testFlow)(Keep.both).runWith(Sink.head), 3.seconds) should ===(1 to 10) val sink = testFlow.concatMat(Source(1 to 5))(Keep.both).to(Sink.ignore).mapMaterializedValue[String] { - case ((m1, m2), m3) ⇒ + case ((m1, m2), m3) => m1.isInstanceOf[NotUsed] should be(true) m2.isInstanceOf[NotUsed] should be(true) m3.isInstanceOf[NotUsed] should be(true) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConflateSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConflateSpec.scala index 9b42e8f620..8ab9d1bd42 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConflateSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowConflateSpec.scala @@ -28,10 +28,10 @@ class FlowConflateSpec extends StreamSpec { val publisher = TestPublisher.probe[Int]() val subscriber = TestSubscriber.manualProbe[Int]() - Source.fromPublisher(publisher).conflateWithSeed(seed = i ⇒ i)(aggregate = (sum, i) ⇒ sum + i).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).conflateWithSeed(seed = i => i)(aggregate = (sum, i) => sum + i).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() - for (i ← 1 to 100) { + for (i <- 1 to 100) { sub.request(1) publisher.sendNext(i) subscriber.expectNext(i) @@ -47,7 +47,7 @@ class FlowConflateSpec extends StreamSpec { Source.fromPublisher(publisher).conflate(_ + _).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() - for (i ← 1 to 100) { + for (i <- 1 to 100) { sub.request(1) publisher.sendNext(i) subscriber.expectNext(i) @@ -60,10 +60,10 @@ class FlowConflateSpec extends StreamSpec { val publisher = TestPublisher.probe[Int]() val subscriber = TestSubscriber.manualProbe[Int]() - Source.fromPublisher(publisher).conflateWithSeed(seed = i ⇒ i)(aggregate = (sum, i) ⇒ sum + i).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).conflateWithSeed(seed = i => i)(aggregate = (sum, i) => sum + i).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() - for (i ← 1 to 100) { + for (i <- 1 to 100) { publisher.sendNext(i) } subscriber.expectNoMessage(1.second) @@ -79,7 +79,7 @@ class FlowConflateSpec extends StreamSpec { Source.fromPublisher(publisher).conflate(_ + _).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() - for (i ← 1 to 100) { + for (i <- 1 to 100) { publisher.sendNext(i) } subscriber.expectNoMessage(1.second) @@ -90,8 +90,8 @@ class FlowConflateSpec extends StreamSpec { "work on a variable rate chain" in { val future = Source(1 to 1000) - .conflateWithSeed(seed = i ⇒ i)(aggregate = (sum, i) ⇒ sum + i) - .map { i ⇒ if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } + .conflateWithSeed(seed = i => i)(aggregate = (sum, i) => sum + i) + .map { i => if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } .runFold(0)(_ + _) Await.result(future, 10.seconds) should be(500500) } @@ -99,7 +99,7 @@ class FlowConflateSpec extends StreamSpec { "work on a variable rate chain (simple conflate)" in { val future = Source(1 to 1000) .conflate(_ + _) - .map { i ⇒ if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } + .map { i => if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } .runFold(0)(_ + _) Await.result(future, 10.seconds) should be(500500) } @@ -108,7 +108,7 @@ class FlowConflateSpec extends StreamSpec { val publisher = TestPublisher.probe[Int]() val subscriber = TestSubscriber.manualProbe[Int]() - Source.fromPublisher(publisher).conflateWithSeed(seed = i ⇒ i)(aggregate = (sum, i) ⇒ sum + i).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).conflateWithSeed(seed = i => i)(aggregate = (sum, i) => sum + i).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() sub.request(1) @@ -135,7 +135,7 @@ class FlowConflateSpec extends StreamSpec { "work with a buffer and fold" in { val future = Source(1 to 50) - .conflateWithSeed(seed = i ⇒ i)(aggregate = (sum, i) ⇒ sum + i) + .conflateWithSeed(seed = i => i)(aggregate = (sum, i) => sum + i) .buffer(50, OverflowStrategy.backpressure) .runFold(0)(_ + _) Await.result(future, 3.seconds) should be((1 to 50).sum) @@ -147,12 +147,12 @@ class FlowConflateSpec extends StreamSpec { val exceptionLatch = TestLatch() val future = Source.fromPublisher(sourceProbe) - .conflateWithSeed { i ⇒ + .conflateWithSeed { i => if (i % 2 == 0) { exceptionLatch.open() throw TE("I hate even seed numbers") } else i - } { (sum, i) ⇒ + } { (sum, i) => sum + i } .withAttributes(supervisionStrategy(restartingDecider)) @@ -190,7 +190,7 @@ class FlowConflateSpec extends StreamSpec { "restart when `aggregate` throws and a restartingDecider is used" in { val latch = TestLatch() val conflate = Flow[String] - .conflateWithSeed(seed = i ⇒ i)((state, elem) ⇒ + .conflateWithSeed(seed = i => i)((state, elem) => if (elem == "two") { latch.open() throw TE("two is a three letter word") @@ -227,7 +227,7 @@ class FlowConflateSpec extends StreamSpec { val saw4Latch = TestLatch() val future = Source.fromPublisher(sourceProbe) - .conflateWithSeed(seed = i ⇒ Vector(i))((state, elem) ⇒ + .conflateWithSeed(seed = i => Vector(i))((state, elem) => if (elem == 2) { throw TE("three is a four letter word") } else { diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDelaySpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDelaySpec.scala index 689380e2be..c3cba3179b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDelaySpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDelaySpec.scala @@ -141,7 +141,7 @@ class FlowDelaySpec extends StreamSpec { val pSub = p.expectSubscription() cSub.request(20) - for (i ← 1 to 16) pSub.sendNext(i) + for (i <- 1 to 16) pSub.sendNext(i) c.expectNoMsg(300.millis) pSub.sendNext(17) c.expectNext(100.millis, 1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDetacherSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDetacherSpec.scala index 887091949f..dba86e0d68 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDetacherSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDetacherSpec.scala @@ -27,7 +27,7 @@ class FlowDetacherSpec extends StreamSpec { "pass through failure" in assertAllStagesStopped { val ex = new Exception("buh") val result = Source(1 to 100) - .map(x ⇒ if (x == 50) throw ex else x) + .map(x => if (x == 50) throw ex else x) .detach .runWith(Sink.seq) intercept[Exception] { diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDispatcherSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDispatcherSpec.scala index 9f0425ccd6..fe7ae66003 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDispatcherSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDispatcherSpec.scala @@ -18,11 +18,11 @@ class FlowDispatcherSpec extends StreamSpec(s"my-dispatcher = $${akka.test.strea implicit val materializer = ActorMaterializer(settings) val probe = TestProbe() - val p = Source(List(1, 2, 3)).map(i ⇒ + val p = Source(List(1, 2, 3)).map(i => { probe.ref ! Thread.currentThread().getName(); i }). to(Sink.ignore).run() probe.receiveN(3) foreach { - case s: String ⇒ s should startWith(system.name + "-" + dispatcher) + case s: String => s should startWith(system.name + "-" + dispatcher) } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropSpec.scala index 8f30e106e0..8c3f55c9a1 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropSpec.scala @@ -4,7 +4,7 @@ package akka.stream.scaladsl -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ random } +import java.util.concurrent.ThreadLocalRandom.{ current => random } import akka.stream.ActorMaterializer import akka.stream.ActorMaterializerSettings import akka.stream.testkit._ @@ -19,8 +19,8 @@ class FlowDropSpec extends StreamSpec with ScriptedTest { "A Drop" must { "drop" in { - def script(d: Int) = Script(TestConfig.RandomTestRange map { n ⇒ Seq(n) → (if (n <= d) Nil else Seq(n)) }: _*) - TestConfig.RandomTestRange foreach { _ ⇒ + def script(d: Int) = Script(TestConfig.RandomTestRange map { n => Seq(n) -> (if (n <= d) Nil else Seq(n)) }: _*) + TestConfig.RandomTestRange foreach { _ => val d = Math.min(Math.max(random.nextInt(-10, 60), 0), 50) runScript(script(d), settings)(_.drop(d)) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropWhileSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropWhileSpec.scala index cc53fcf412..9d9331cb1a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropWhileSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropWhileSpec.scala @@ -35,7 +35,7 @@ class FlowDropWhileSpec extends StreamSpec { } "continue if error" in assertAllStagesStopped { - Source(1 to 4).dropWhile(a ⇒ if (a < 3) true else throw TE("")).withAttributes(supervisionStrategy(resumingDecider)) + Source(1 to 4).dropWhile(a => if (a < 3) true else throw TE("")).withAttributes(supervisionStrategy(resumingDecider)) .runWith(TestSink.probe[Int]) .request(1) .expectComplete() @@ -43,9 +43,9 @@ class FlowDropWhileSpec extends StreamSpec { "restart with strategy" in assertAllStagesStopped { Source(1 to 4).dropWhile { - case 1 | 3 ⇒ true - case 4 ⇒ false - case 2 ⇒ throw TE("") + case 1 | 3 => true + case 4 => false + case 2 => throw TE("") }.withAttributes(supervisionStrategy(restartingDecider)) .runWith(TestSink.probe[Int]) .request(1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropWithinSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropWithinSpec.scala index 0804ac031a..cbf1966946 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropWithinSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowDropWithinSpec.scala @@ -23,13 +23,13 @@ class FlowDropWithinSpec extends StreamSpec { val cSub = c.expectSubscription cSub.request(100) val demand1 = pSub.expectRequest - (1 to demand1.toInt) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand1.toInt) foreach { _ => pSub.sendNext(input.next()) } val demand2 = pSub.expectRequest - (1 to demand2.toInt) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand2.toInt) foreach { _ => pSub.sendNext(input.next()) } val demand3 = pSub.expectRequest c.expectNoMsg(1500.millis) - (1 to demand3.toInt) foreach { _ ⇒ pSub.sendNext(input.next()) } - ((demand1 + demand2 + 1).toInt to (demand1 + demand2 + demand3).toInt) foreach { n ⇒ c.expectNext(n) } + (1 to demand3.toInt) foreach { _ => pSub.sendNext(input.next()) } + ((demand1 + demand2 + 1).toInt to (demand1 + demand2 + demand3).toInt) foreach { n => c.expectNext(n) } pSub.sendComplete() c.expectComplete c.expectNoMsg(200.millis) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowExpandSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowExpandSpec.scala index 8f54942daa..af7090409a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowExpandSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowExpandSpec.scala @@ -31,7 +31,7 @@ class FlowExpandSpec extends StreamSpec { // Simply repeat the last element as an extrapolation step Source.fromPublisher(publisher).expand(Iterator.single).to(Sink.fromSubscriber(subscriber)).run() - for (i ← 1 to 100) { + for (i <- 1 to 100) { // Order is important here: If the request comes first it will be extrapolated! publisher.sendNext(i) subscriber.requestNext(i) @@ -49,7 +49,7 @@ class FlowExpandSpec extends StreamSpec { publisher.sendNext(42) - for (_ ← 1 to 100) { + for (_ <- 1 to 100) { subscriber.requestNext(42) } @@ -84,7 +84,7 @@ class FlowExpandSpec extends StreamSpec { "work on a variable rate chain" in { val future = Source(1 to 100) - .map { i ⇒ if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } + .map { i => if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } .expand(Iterator.continually(_)) .runFold(Set.empty[Int])(_ + _) @@ -130,20 +130,20 @@ class FlowExpandSpec extends StreamSpec { "work properly with finite extrapolations" in { val (source, sink) = TestSource.probe[Int] - .expand(i ⇒ Iterator.from(0).map(i → _).take(3)) + .expand(i => Iterator.from(0).map(i -> _).take(3)) .toMat(TestSink.probe)(Keep.both) .run() source .sendNext(1) sink .request(4) - .expectNext(1 → 0, 1 → 1, 1 → 2) + .expectNext(1 -> 0, 1 -> 1, 1 -> 2) .expectNoMsg(100.millis) source .sendNext(2) .sendComplete() sink - .expectNext(2 → 0) + .expectNext(2 -> 0) .expectComplete() } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowExtrapolateSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowExtrapolateSpec.scala index 87625eb348..bd4f8f604a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowExtrapolateSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowExtrapolateSpec.scala @@ -30,9 +30,9 @@ class FlowExtrapolateSpec extends StreamSpec { val subscriber = TestSubscriber.probe[Int]() // Provide an empty stream - Source.fromPublisher(publisher).extrapolate(_ ⇒ Iterator.empty).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).extrapolate(_ => Iterator.empty).to(Sink.fromSubscriber(subscriber)).run() - for (i ← 1 to 100) { + for (i <- 1 to 100) { // Order is important here: If the request comes first it will be extrapolated! publisher.sendNext(i) subscriber.requestNext(i) @@ -46,12 +46,12 @@ class FlowExtrapolateSpec extends StreamSpec { val subscriber = TestSubscriber.probe[Int]() // Simply repeat the last element as an extrapolation step - Source.fromPublisher(publisher).extrapolate(e ⇒ Iterator.continually(e + 1)).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).extrapolate(e => Iterator.continually(e + 1)).to(Sink.fromSubscriber(subscriber)).run() publisher.sendNext(42) subscriber.requestNext(42) - for (_ ← 1 to 100) { + for (_ <- 1 to 100) { subscriber.requestNext(42 + 1) } @@ -85,7 +85,7 @@ class FlowExtrapolateSpec extends StreamSpec { val subscriber = TestSubscriber.probe[Int]() // Simply repeat the last element as an extrapolation step - Source.fromPublisher(publisher).extrapolate(_ ⇒ Iterator.empty).to(Sink.fromSubscriber(subscriber)).run() + Source.fromPublisher(publisher).extrapolate(_ => Iterator.empty).to(Sink.fromSubscriber(subscriber)).run() publisher.sendNext(1) subscriber.requestNext(1) @@ -102,7 +102,7 @@ class FlowExtrapolateSpec extends StreamSpec { "work on a variable rate chain" in { val future = Source(1 to 100) - .map { i ⇒ if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } + .map { i => if (ThreadLocalRandom.current().nextBoolean()) Thread.sleep(10); i } .extrapolate(Iterator.continually(_)) .runFold(Set.empty[Int])(_ + _) @@ -148,20 +148,20 @@ class FlowExtrapolateSpec extends StreamSpec { "work properly with finite extrapolations" in { val (source, sink) = TestSource.probe[Int] - .expand(i ⇒ Iterator.from(0).map(i → _).take(3)) + .expand(i => Iterator.from(0).map(i -> _).take(3)) .toMat(TestSink.probe)(Keep.both) .run() source .sendNext(1) sink .request(4) - .expectNext(1 → 0, 1 → 1, 1 → 2) + .expectNext(1 -> 0, 1 -> 1, 1 -> 2) .expectNoMsg(100.millis) source .sendNext(2) .sendComplete() sink - .expectNext(2 → 0) + .expectNext(2 -> 0) .expectComplete() } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFilterSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFilterSpec.scala index 073c9dbf52..9078dd60da 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFilterSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFilterSpec.scala @@ -6,7 +6,7 @@ package akka.stream.scaladsl import akka.stream.testkit.scaladsl.TestSink -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ random } +import java.util.concurrent.ThreadLocalRandom.{ current => random } import akka.stream.ActorAttributes._ import akka.stream.Supervision._ import akka.stream.testkit.scaladsl.StreamTestKit._ @@ -26,8 +26,8 @@ class FlowFilterSpec extends StreamSpec with ScriptedTest { "A Filter" must { "filter" in { - def script = Script(TestConfig.RandomTestRange map { _ ⇒ val x = random.nextInt(); Seq(x) → (if ((x & 1) == 0) Seq(x) else Seq()) }: _*) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.filter(_ % 2 == 0))) + def script = Script(TestConfig.RandomTestRange map { _ => val x = random.nextInt(); Seq(x) -> (if ((x & 1) == 0) Seq(x) else Seq()) }: _*) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.filter(_ % 2 == 0))) } "not blow up with high request counts" in { @@ -39,7 +39,7 @@ class FlowFilterSpec extends StreamSpec with ScriptedTest { Source(List.fill(1000)(0) ::: List(1)).filter(_ != 0).runWith(Sink.fromSubscriber(probe)) val subscription = probe.expectSubscription() - for (_ ← 1 to 10000) { + for (_ <- 1 to 10000) { subscription.request(Int.MaxValue) } @@ -52,7 +52,7 @@ class FlowFilterSpec extends StreamSpec with ScriptedTest { override def toString = "TE" } - Source(1 to 3).filter((x: Int) ⇒ if (x == 2) throw TE else true).withAttributes(supervisionStrategy(resumingDecider)) + Source(1 to 3).filter((x: Int) => if (x == 2) throw TE else true).withAttributes(supervisionStrategy(resumingDecider)) .runWith(TestSink.probe[Int]) .request(3) .expectNext(1, 3) @@ -64,11 +64,11 @@ class FlowFilterSpec extends StreamSpec with ScriptedTest { "A FilterNot" must { "filter based on inverted predicate" in { def script = Script(TestConfig.RandomTestRange map - { _ ⇒ + { _ => val x = random.nextInt() - Seq(x) → (if ((x & 1) == 1) Seq(x) else Seq()) + Seq(x) -> (if ((x & 1) == 1) Seq(x) else Seq()) }: _*) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.filterNot(_ % 2 == 0))) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.filterNot(_ % 2 == 0))) } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFlattenMergeSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFlattenMergeSpec.scala index 620d63b01c..2786f7320f 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFlattenMergeSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFlattenMergeSpec.scala @@ -83,7 +83,7 @@ class FlowFlattenMergeSpec extends StreamSpec { val ex = new Exception("buh") intercept[TestFailedException] { Source(1 to 3) - .flatMapMerge(10, i ⇒ if (i == 3) throw ex else blocked) + .flatMapMerge(10, i => if (i == 3) throw ex else blocked) .runWith(Sink.head) .futureValue }.cause.get should ===(ex) @@ -109,7 +109,7 @@ class FlowFlattenMergeSpec extends StreamSpec { } } - val result = Source.single(()).flatMapMerge(4, _ ⇒ Source.fromGraph(FailingInnerMat)).runWith(Sink.ignore) + val result = Source.single(()).flatMapMerge(4, _ => Source.fromGraph(FailingInnerMat)).runWith(Sink.ignore) result.failed.futureValue should ===(matFail) @@ -151,8 +151,8 @@ class FlowFlattenMergeSpec extends StreamSpec { val latch = TestLatch() Source(1 to 3) .flatMapMerge(10, { - case 1 ⇒ Source.fromPublisher(p) - case 2 ⇒ + case 1 => Source.fromPublisher(p) + case 2 => Await.ready(latch, 3.seconds) throw ex }) @@ -177,14 +177,14 @@ class FlowFlattenMergeSpec extends StreamSpec { } "work with many concurrently queued events" in assertAllStagesStopped { - val p = Source((0 until 100).map(i ⇒ src10(10 * i))) + val p = Source((0 until 100).map(i => src10(10 * i))) .flatMapMerge(Int.MaxValue, identity) .runWith(TestSink.probe) p.within(1.second) { p.ensureSubscription() p.expectNoMsg() } - val elems = p.within(1.second)((1 to 1000).map(i ⇒ p.requestNext()).toSet) + val elems = p.within(1.second)((1 to 1000).map(i => p.requestNext()).toSet) p.expectComplete() elems should ===((0 until 1000).toSet) } @@ -291,7 +291,7 @@ class FlowFlattenMergeSpec extends StreamSpec { TraversalBuilder.getSingleSource(singleSourceA) should be(OptionVal.Some(singleSourceA)) TraversalBuilder.getSingleSource(Source.single("c").async) should be(OptionVal.None) - TraversalBuilder.getSingleSource(Source.single("d").mapMaterializedValue(_ ⇒ "Mat")) should be(OptionVal.None) + TraversalBuilder.getSingleSource(Source.single("d").mapMaterializedValue(_ => "Mat")) should be(OptionVal.None) } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFoldAsyncSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFoldAsyncSpec.scala index cd285af9fa..edb6a41d35 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFoldAsyncSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFoldAsyncSpec.scala @@ -28,14 +28,14 @@ class FlowFoldAsyncSpec extends StreamSpec { val input = 1 to 100 val expected = input.sum val inputSource = Source(input) - val foldSource = inputSource.foldAsync[Int](0) { (a, b) ⇒ + val foldSource = inputSource.foldAsync[Int](0) { (a, b) => Future(a + b) } val flowDelayMS = 100L val foldFlow = Flow[Int].foldAsync(0) { - (a, b) ⇒ Future { Thread.sleep(flowDelayMS); a + b } + (a, b) => Future { Thread.sleep(flowDelayMS); a + b } } - val foldSink = Sink.foldAsync[Int, Int](0) { (a, b) ⇒ Future(a + b) } + val foldSink = Sink.foldAsync[Int, Int](0) { (a, b) => Future(a + b) } "work when using Source.foldAsync" in assertAllStagesStopped { foldSource.runWith(Sink.head).futureValue(timeout) should ===(expected) @@ -60,13 +60,13 @@ class FlowFoldAsyncSpec extends StreamSpec { "propagate an error" in assertAllStagesStopped { val error = TE("Boom!") - val future = inputSource.map(x ⇒ if (x > 50) throw error else x).runFoldAsync[NotUsed](NotUsed)(noneAsync) + val future = inputSource.map(x => if (x > 50) throw error else x).runFoldAsync[NotUsed](NotUsed)(noneAsync) the[Exception] thrownBy Await.result(future, 3.seconds) should be(error) } "complete future with failure when folding function throws" in assertAllStagesStopped { val error = TE("Boom!") - val future = inputSource.runFoldAsync(0) { (x, y) ⇒ + val future = inputSource.runFoldAsync(0) { (x, y) => if (x > 50) Future.failed(error) else Future(x + y) } @@ -77,8 +77,8 @@ class FlowFoldAsyncSpec extends StreamSpec { val probe = TestSubscriber.manualProbe[Long]() var i = 0 - Source.fromIterator(() ⇒ Iterator.fill[Int](10000) { i += 1; i }). - foldAsync(1L) { (a, b) ⇒ Future(a + b) }. + Source.fromIterator(() => Iterator.fill[Int](10000) { i += 1; i }). + foldAsync(1L) { (a, b) => Future(a + b) }. runWith(Sink.asPublisher(true)).subscribe(probe) val subscription = probe.expectSubscription() @@ -91,7 +91,7 @@ class FlowFoldAsyncSpec extends StreamSpec { "signal future failure" in assertAllStagesStopped { val probe = TestSubscriber.probe[Int]() implicit val ec = system.dispatcher - Source(1 to 5).foldAsync(0) { (_, n) ⇒ + Source(1 to 5).foldAsync(0) { (_, n) => Future(if (n == 3) throw TE("err1") else n) }.to(Sink.fromSubscriber(probe)).run() @@ -103,7 +103,7 @@ class FlowFoldAsyncSpec extends StreamSpec { "signal error from foldAsync" in assertAllStagesStopped { val probe = TestSubscriber.probe[Int]() implicit val ec = system.dispatcher - Source(1 to 5).foldAsync(0) { (_, n) ⇒ + Source(1 to 5).foldAsync(0) { (_, n) => if (n == 3) throw new RuntimeException("err2") with NoStackTrace Future(n + 1) }.to(Sink.fromSubscriber(probe)).run() @@ -116,36 +116,36 @@ class FlowFoldAsyncSpec extends StreamSpec { "resume after future failure" in assertAllStagesStopped { val probe = TestSubscriber.probe[(Int, Int)]() implicit val ec = system.dispatcher - Source(1 to 5).foldAsync(0 → 1) { - case ((i, res), n) ⇒ + Source(1 to 5).foldAsync(0 -> 1) { + case ((i, res), n) => Future { if (n == 3) throw new RuntimeException("err3") with NoStackTrace - else n → (i + (res * n)) + else n -> (i + (res * n)) } }.withAttributes(supervisionStrategy(resumingDecider)). to(Sink.fromSubscriber(probe)).run() val sub = probe.expectSubscription() sub.request(10) - probe.expectNext(5 → 74) + probe.expectNext(5 -> 74) probe.expectComplete() } "restart after future failure" in assertAllStagesStopped { val probe = TestSubscriber.probe[(Int, Int)]() implicit val ec = system.dispatcher - Source(1 to 5).foldAsync(0 → 1) { - case ((i, res), n) ⇒ + Source(1 to 5).foldAsync(0 -> 1) { + case ((i, res), n) => Future { if (n == 3) throw new RuntimeException("err3") with NoStackTrace - else n → (i + (res * n)) + else n -> (i + (res * n)) } }.withAttributes(supervisionStrategy(restartingDecider)). to(Sink.fromSubscriber(probe)).run() val sub = probe.expectSubscription() sub.request(10) - probe.expectNext(5 → 24) + probe.expectNext(5 -> 24) probe.expectComplete() } @@ -158,13 +158,13 @@ class FlowFoldAsyncSpec extends StreamSpec { Future.failed(Utils.TE("failure5")), Future.successful("happy!")) - Source(futures).foldAsync("") { (_, s) ⇒ s }. + Source(futures).foldAsync("") { (_, s) => s }. withAttributes(supervisionStrategy(resumingDecider)).runWith(Sink.head). futureValue(timeout) should ===("happy!") } "finish after future failure" in assertAllStagesStopped { - Source(1 to 3).foldAsync(1) { (_, n) ⇒ + Source(1 to 3).foldAsync(1) { (_, n) => Future { if (n == 3) throw new RuntimeException("err3b") with NoStackTrace else n @@ -177,36 +177,36 @@ class FlowFoldAsyncSpec extends StreamSpec { "resume when foldAsync throws" in { val c = TestSubscriber.manualProbe[(Int, Int)]() implicit val ec = system.dispatcher - val p = Source(1 to 5).foldAsync(0 → 1) { - case ((i, res), n) ⇒ + val p = Source(1 to 5).foldAsync(0 -> 1) { + case ((i, res), n) => if (n == 3) throw new RuntimeException("err4") with NoStackTrace - else Future(n → (i + (res * n))) + else Future(n -> (i + (res * n))) }.withAttributes(supervisionStrategy(resumingDecider)). to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) - c.expectNext(5 → 74) + c.expectNext(5 -> 74) c.expectComplete() } "restart when foldAsync throws" in { val c = TestSubscriber.manualProbe[(Int, Int)]() implicit val ec = system.dispatcher - val p = Source(1 to 5).foldAsync(0 → 1) { - case ((i, res), n) ⇒ + val p = Source(1 to 5).foldAsync(0 -> 1) { + case ((i, res), n) => if (n == 3) throw new RuntimeException("err4") with NoStackTrace - else Future(n → (i + (res * n))) + else Future(n -> (i + (res * n))) }.withAttributes(supervisionStrategy(restartingDecider)). to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) - c.expectNext(5 → 24) + c.expectNext(5 -> 24) c.expectComplete() } "signal NPE when future is completed with null" in { val c = TestSubscriber.manualProbe[String]() - val p = Source(List("a", "b")).foldAsync("") { (_, elem) ⇒ + val p = Source(List("a", "b")).foldAsync("") { (_, elem) => Future.successful(null.asInstanceOf[String]) }.to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() @@ -216,7 +216,7 @@ class FlowFoldAsyncSpec extends StreamSpec { "resume when future is completed with null" in { val c = TestSubscriber.manualProbe[String]() - val p = Source(List("a", "b", "c")).foldAsync("") { (str, elem) ⇒ + val p = Source(List("a", "b", "c")).foldAsync("") { (str, elem) => if (elem == "b") Future.successful(null.asInstanceOf[String]) else Future.successful(str + elem) }.withAttributes(supervisionStrategy(resumingDecider)). @@ -229,7 +229,7 @@ class FlowFoldAsyncSpec extends StreamSpec { "restart when future is completed with null" in { val c = TestSubscriber.manualProbe[String]() - val p = Source(List("a", "b", "c")).foldAsync("") { (str, elem) ⇒ + val p = Source(List("a", "b", "c")).foldAsync("") { (str, elem) => if (elem == "b") Future.successful(null.asInstanceOf[String]) else Future.successful(str + elem) }.withAttributes(supervisionStrategy(restartingDecider)). @@ -245,7 +245,7 @@ class FlowFoldAsyncSpec extends StreamSpec { val sub = TestSubscriber.manualProbe[Int]() Source.fromPublisher(pub). - foldAsync(0) { (_, n) ⇒ Future.successful(n) }. + foldAsync(0) { (_, n) => Future.successful(n) }. runWith(Sink.fromSubscriber(sub)) val upstream = pub.expectSubscription() @@ -258,8 +258,8 @@ class FlowFoldAsyncSpec extends StreamSpec { "complete future and return zero given an empty stream" in assertAllStagesStopped { val futureValue = - Source.fromIterator[Int](() ⇒ Iterator.empty) - .runFoldAsync(0)((acc, elem) ⇒ Future.successful(acc + elem)) + Source.fromIterator[Int](() => Iterator.empty) + .runFoldAsync(0)((acc, elem) => Future.successful(acc + elem)) Await.result(futureValue, remainingOrDefault) should be(0) } @@ -267,15 +267,15 @@ class FlowFoldAsyncSpec extends StreamSpec { "complete future and return zero + item given a stream of one item" in assertAllStagesStopped { val futureValue = Source.single(100) - .runFoldAsync(5)((acc, elem) ⇒ Future.successful(acc + elem)) + .runFoldAsync(5)((acc, elem) => Future.successful(acc + elem)) Await.result(futureValue, remainingOrDefault) should be(105) } } // Keep - def noneAsync[L, R]: (L, R) ⇒ Future[NotUsed] = { (_: Any, _: Any) ⇒ + def noneAsync[L, R]: (L, R) => Future[NotUsed] = { (_: Any, _: Any) => Future.successful(NotUsed) - }.asInstanceOf[(L, R) ⇒ Future[NotUsed]] + }.asInstanceOf[(L, R) => Future[NotUsed]] } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFoldSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFoldSpec.scala index 22be94ae65..252879f2a1 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFoldSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowFoldSpec.scala @@ -47,19 +47,19 @@ class FlowFoldSpec extends StreamSpec { "propagate an error" in assertAllStagesStopped { val error = TE("Boom!") - val future = inputSource.map(x ⇒ if (x > 50) throw error else x).runFold[NotUsed](NotUsed)(Keep.none) + val future = inputSource.map(x => if (x > 50) throw error else x).runFold[NotUsed](NotUsed)(Keep.none) the[Exception] thrownBy Await.result(future, 3.seconds) should be(error) } "complete future with failure when the folding function throws and the supervisor strategy decides to stop" in assertAllStagesStopped { val error = TE("Boom!") - val future = inputSource.runFold(0)((x, y) ⇒ if (x > 50) throw error else x + y) + val future = inputSource.runFold(0)((x, y) => if (x > 50) throw error else x + y) the[Exception] thrownBy Await.result(future, 3.seconds) should be(error) } "resume with the accumulated state when the folding function throws and the supervisor strategy decides to resume" in assertAllStagesStopped { val error = TE("Boom!") - val fold = Sink.fold[Int, Int](0)((x, y) ⇒ if (y == 50) throw error else x + y) + val fold = Sink.fold[Int, Int](0)((x, y) => if (y == 50) throw error else x + y) val future = inputSource.runWith(fold.withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider))) Await.result(future, 3.seconds) should be(expected - 50) @@ -67,7 +67,7 @@ class FlowFoldSpec extends StreamSpec { "resume and reset the state when the folding function throws when the supervisor strategy decides to restart" in assertAllStagesStopped { val error = TE("Boom!") - val fold = Sink.fold[Int, Int](0)((x, y) ⇒ if (y == 50) throw error else x + y) + val fold = Sink.fold[Int, Int](0)((x, y) => if (y == 50) throw error else x + y) val future = inputSource.runWith(fold.withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider))) Await.result(future, 3.seconds) should be((51 to 100).sum) @@ -75,7 +75,7 @@ class FlowFoldSpec extends StreamSpec { "complete future and return zero given an empty stream" in assertAllStagesStopped { val futureValue = - Source.fromIterator[Int](() ⇒ Iterator.empty) + Source.fromIterator[Int](() => Iterator.empty) .runFold(0)(_ + _) Await.result(futureValue, 3.seconds) should be(0) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowForeachSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowForeachSpec.scala index a498dfce8d..59970cb6eb 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowForeachSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowForeachSpec.scala @@ -21,7 +21,7 @@ class FlowForeachSpec extends StreamSpec { "call the procedure for each element" in assertAllStagesStopped { Source(1 to 3).runForeach(testActor ! _) foreach { - _ ⇒ testActor ! "done" + _ => testActor ! "done" } expectMsg(1) expectMsg(2) @@ -31,7 +31,7 @@ class FlowForeachSpec extends StreamSpec { "complete the future for an empty stream" in assertAllStagesStopped { Source.empty[String].runForeach(testActor ! _) foreach { - _ ⇒ testActor ! "done" + _ => testActor ! "done" } expectMsg("done") } @@ -39,7 +39,7 @@ class FlowForeachSpec extends StreamSpec { "yield the first error" in assertAllStagesStopped { val p = TestPublisher.manualProbe[Int]() Source.fromPublisher(p).runForeach(testActor ! _).failed foreach { - ex ⇒ testActor ! ex + ex => testActor ! ex } val proc = p.expectSubscription() proc.expectRequest() @@ -50,7 +50,7 @@ class FlowForeachSpec extends StreamSpec { "complete future with failure when function throws" in assertAllStagesStopped { val error = TE("Boom!") - val future = Source.single(1).runForeach(_ ⇒ throw error) + val future = Source.single(1).runForeach(_ => throw error) the[Exception] thrownBy Await.result(future, 3.seconds) should be(error) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupBySpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupBySpec.scala index 546be1a344..0d7c0d3e66 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupBySpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupBySpec.scala @@ -32,7 +32,7 @@ import akka.testkit.TestLatch object FlowGroupBySpec { implicit class Lift[M](val f: SubFlow[Int, M, Source[Int, M]#Repr, RunnableGraph[M]]) extends AnyVal { - def lift(key: Int ⇒ Int) = f.prefixAndTail(1).map(p ⇒ key(p._1.head) → (Source.single(p._1.head) ++ p._2)).concatSubstreams + def lift(key: Int => Int) = f.prefixAndTail(1).map(p => key(p._1.head) -> (Source.single(p._1.head) ++ p._2)).concatSubstreams } } @@ -138,7 +138,7 @@ class FlowGroupBySpec extends StreamSpec { "fail when key function return null" in { val down = Source(List("Aaa", "Abb", "Bcc", "Cdd", "Cee")) - .groupBy(3, e ⇒ if (e.startsWith("A")) null else e.substring(0, 1)) + .groupBy(3, e => if (e.startsWith("A")) null else e.substring(0, 1)) .grouped(10) .mergeSubstreams .runWith(TestSink.probe[Seq[String]]) @@ -235,7 +235,7 @@ class FlowGroupBySpec extends StreamSpec { val publisherProbeProbe = TestPublisher.manualProbe[Int]() val exc = TE("test") val publisher = Source.fromPublisher(publisherProbeProbe) - .groupBy(2, elem ⇒ if (elem == 2) throw exc else elem % 2) + .groupBy(2, elem => if (elem == 2) throw exc else elem % 2) .lift(_ % 2) .runWith(Sink.asPublisher(false)) val subscriber = TestSubscriber.manualProbe[(Int, Source[Int, NotUsed])]() @@ -265,7 +265,7 @@ class FlowGroupBySpec extends StreamSpec { val publisherProbeProbe = TestPublisher.manualProbe[Int]() val exc = TE("test") val publisher = Source.fromPublisher(publisherProbeProbe) - .groupBy(2, elem ⇒ if (elem == 2) throw exc else elem % 2) + .groupBy(2, elem => if (elem == 2) throw exc else elem % 2) .lift(_ % 2) .withAttributes(ActorAttributes.supervisionStrategy(resumingDecider)) .runWith(Sink.asPublisher(false)) @@ -352,7 +352,7 @@ class FlowGroupBySpec extends StreamSpec { "emit subscribe before completed" in assertAllStagesStopped { val futureGroupSource = Source.single(0) - .groupBy(1, elem ⇒ "all") + .groupBy(1, elem => "all") .prefixAndTail(0) .map(_._2) .concatSubstreams @@ -372,8 +372,8 @@ class FlowGroupBySpec extends StreamSpec { val subscriber = TestSubscriber.manualProbe[ByteString]() val publisher = Source.fromPublisher[ByteString](publisherProbe) - .groupBy(256, elem ⇒ elem.head).map(_.reverse).mergeSubstreams - .groupBy(256, elem ⇒ elem.head).map(_.reverse).mergeSubstreams + .groupBy(256, elem => elem.head).map(_.reverse).mergeSubstreams + .groupBy(256, elem => elem.head).map(_.reverse).mergeSubstreams .runWith(Sink.asPublisher(false)) publisher.subscribe(subscriber) @@ -381,7 +381,7 @@ class FlowGroupBySpec extends StreamSpec { val downstreamSubscription = subscriber.expectSubscription() downstreamSubscription.request(300) - for (i ← 1 to 300) { + for (i <- 1 to 300) { val byteString = randomByteString(10) upstreamSubscription.expectRequest() upstreamSubscription.sendNext(byteString) @@ -396,7 +396,7 @@ class FlowGroupBySpec extends StreamSpec { Source .fromPublisher(upstream) - .via(new GroupBy[Int, Boolean](2, elem ⇒ elem == 0)) + .via(new GroupBy[Int, Boolean](2, elem => elem == 0)) .runWith(Sink.fromSubscriber(downstreamMaster)) val substream = TestSubscriber.probe[Int]() @@ -427,7 +427,7 @@ class FlowGroupBySpec extends StreamSpec { Source .fromPublisher(upstream) - .via(new GroupBy[Int, Int](10, elem ⇒ elem)) + .via(new GroupBy[Int, Int](10, elem => elem)) .runWith(Sink.fromSubscriber(downstreamMaster)) val substream1 = TestSubscriber.probe[Int]() @@ -508,7 +508,7 @@ class FlowGroupBySpec extends StreamSpec { Source .fromPublisher(upstream) - .via(new GroupBy[Int, Int](10, elem ⇒ elem)) + .via(new GroupBy[Int, Int](10, elem => elem)) .runWith(Sink.fromSubscriber(downstreamMaster)) val substream1 = TestSubscriber.probe[Int]() @@ -549,7 +549,7 @@ class FlowGroupBySpec extends StreamSpec { var blockingNextElement: ByteString = null.asInstanceOf[ByteString] val probes = new java.util.ArrayList[Promise[TestSubscriber.Probe[ByteString]]](100) - (0 to 99).foreach(_ ⇒ probes.add(Promise[TestSubscriber.Probe[ByteString]]())) + (0 to 99).foreach(_ => probes.add(Promise[TestSubscriber.Probe[ByteString]]())) var probesWriterTop = 0 var probesReaderTop = 0 @@ -596,11 +596,11 @@ class FlowGroupBySpec extends StreamSpec { val publisherProbe = TestPublisher.manualProbe[ByteString]() Source.fromPublisher[ByteString](publisherProbe) - .groupBy(100, elem ⇒ Math.abs(elem.head % 100)).to(Sink.fromGraph(new ProbeSink(none, SinkShape(Inlet("ProbeSink.in"))))).run()(mat) + .groupBy(100, elem => Math.abs(elem.head % 100)).to(Sink.fromGraph(new ProbeSink(none, SinkShape(Inlet("ProbeSink.in"))))).run()(mat) val upstreamSubscription = publisherProbe.expectSubscription() - for (i ← 1 to 400) { + for (i <- 1 to 400) { val byteString = randomByteString(10) val index = Math.abs(byteString.head % 100) @@ -633,7 +633,7 @@ class FlowGroupBySpec extends StreamSpec { } "not block all substreams when one is blocked but has a buffer in front" in assertAllStagesStopped { - case class Elem(id: Int, substream: Int, f: () ⇒ Any) + case class Elem(id: Int, substream: Int, f: () => Any) val queue = Source.queue[Elem](3, OverflowStrategy.backpressure) .groupBy(2, _.substream) .buffer(2, OverflowStrategy.backpressure) @@ -644,13 +644,13 @@ class FlowGroupBySpec extends StreamSpec { val threeProcessed = Promise[Done]() val blockSubStream1 = TestLatch() List( - Elem(1, 1, () ⇒ { + Elem(1, 1, () => { // timeout just to not wait forever if something is wrong, not really relevant for test Await.result(blockSubStream1, 10.seconds) 1 }), - Elem(2, 1, () ⇒ 2), - Elem(3, 2, () ⇒ { + Elem(2, 1, () => 2), + Elem(3, 2, () => { threeProcessed.success(Done) 3 })).foreach(queue.offer) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupedSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupedSpec.scala index ba84c15950..f6cb4128a8 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupedSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupedSpec.scala @@ -5,7 +5,7 @@ package akka.stream.scaladsl import scala.collection.immutable -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ random } +import java.util.concurrent.ThreadLocalRandom.{ current => random } import akka.stream.ActorMaterializerSettings import akka.stream.testkit.{ StreamSpec, ScriptedTest } @@ -18,18 +18,18 @@ class FlowGroupedSpec extends StreamSpec with ScriptedTest { "A Grouped" must { def randomSeq(n: Int) = immutable.Seq.fill(n)(random.nextInt()) - def randomTest(n: Int) = { val s = randomSeq(n); s → immutable.Seq(s) } + def randomTest(n: Int) = { val s = randomSeq(n); s -> immutable.Seq(s) } "group evenly" in { val testLen = random.nextInt(1, 16) - def script = Script(TestConfig.RandomTestRange map { _ ⇒ randomTest(testLen) }: _*) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.grouped(testLen))) + def script = Script(TestConfig.RandomTestRange map { _ => randomTest(testLen) }: _*) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.grouped(testLen))) } "group with rest" in { val testLen = random.nextInt(1, 16) - def script = Script(TestConfig.RandomTestRange.map { _ ⇒ randomTest(testLen) } :+ randomTest(1): _*) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.grouped(testLen))) + def script = Script(TestConfig.RandomTestRange.map { _ => randomTest(testLen) } :+ randomTest(1): _*) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.grouped(testLen))) } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupedWithinSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupedWithinSpec.scala index 957865a99b..772d4f8405 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupedWithinSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowGroupedWithinSpec.scala @@ -6,7 +6,7 @@ package akka.stream.scaladsl import scala.collection.immutable import scala.concurrent.duration._ -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ random } +import java.util.concurrent.ThreadLocalRandom.{ current => random } import akka.stream.{ ActorMaterializer, ActorMaterializerSettings, ThrottleMode } import akka.stream.testkit._ @@ -32,12 +32,12 @@ class FlowGroupedWithinSpec extends StreamSpec with ScriptedTest { val cSub = c.expectSubscription cSub.request(100) val demand1 = pSub.expectRequest.toInt - (1 to demand1) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand1) foreach { _ => pSub.sendNext(input.next()) } val demand2 = pSub.expectRequest.toInt - (1 to demand2) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand2) foreach { _ => pSub.sendNext(input.next()) } val demand3 = pSub.expectRequest.toInt c.expectNext((1 to (demand1 + demand2).toInt).toVector) - (1 to demand3) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand3) foreach { _ => pSub.sendNext(input.next()) } c.expectNoMsg(300.millis) c.expectNext(((demand1 + demand2 + 1).toInt to (demand1 + demand2 + demand3).toInt).toVector) c.expectNoMsg(300.millis) @@ -69,10 +69,10 @@ class FlowGroupedWithinSpec extends StreamSpec with ScriptedTest { val cSub = c.expectSubscription cSub.request(1) val demand1 = pSub.expectRequest.toInt - (1 to demand1) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand1) foreach { _ => pSub.sendNext(input.next()) } c.expectNext((1 to demand1).toVector) val demand2 = pSub.expectRequest.toInt - (1 to demand2) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand2) foreach { _ => pSub.sendNext(input.next()) } c.expectNoMsg(300.millis) cSub.request(1) c.expectNext(((demand1 + 1) to (demand1 + demand2)).toVector) @@ -154,14 +154,14 @@ class FlowGroupedWithinSpec extends StreamSpec with ScriptedTest { } "group evenly" taggedAs TimingTest in { - def script = Script(TestConfig.RandomTestRange map { _ ⇒ val x, y, z = random.nextInt(); Seq(x, y, z) → Seq(immutable.Seq(x, y, z)) }: _*) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.groupedWithin(3, 10.minutes))) + def script = Script(TestConfig.RandomTestRange map { _ => val x, y, z = random.nextInt(); Seq(x, y, z) -> Seq(immutable.Seq(x, y, z)) }: _*) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.groupedWithin(3, 10.minutes))) } "group with rest" taggedAs TimingTest in { - def script = Script((TestConfig.RandomTestRange.map { _ ⇒ val x, y, z = random.nextInt(); Seq(x, y, z) → Seq(immutable.Seq(x, y, z)) } - :+ { val x = random.nextInt(); Seq(x) → Seq(immutable.Seq(x)) }): _*) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.groupedWithin(3, 10.minutes))) + def script = Script((TestConfig.RandomTestRange.map { _ => val x, y, z = random.nextInt(); Seq(x, y, z) -> Seq(immutable.Seq(x, y, z)) } + :+ { val x = random.nextInt(); Seq(x) -> Seq(immutable.Seq(x)) }): _*) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.groupedWithin(3, 10.minutes))) } "group with small groups with backpressure" taggedAs TimingTest in { diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowIdleInjectSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowIdleInjectSpec.scala index 2aa2e2f8d0..5e584adde3 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowIdleInjectSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowIdleInjectSpec.scala @@ -21,7 +21,7 @@ class FlowIdleInjectSpec extends StreamSpec { "not emit additional elements if upstream is fast enough" in assertAllStagesStopped { Await.result( - Source(1 to 10).keepAlive(1.second, () ⇒ 0).grouped(1000).runWith(Sink.head), + Source(1 to 10).keepAlive(1.second, () => 0).grouped(1000).runWith(Sink.head), 3.seconds) should ===(1 to 10) } @@ -29,7 +29,7 @@ class FlowIdleInjectSpec extends StreamSpec { val sourceWithIdleGap = Source(1 to 5) ++ Source(6 to 10).initialDelay(2.second) val result = Await.result( - sourceWithIdleGap.keepAlive(0.6.seconds, () ⇒ 0).grouped(1000).runWith(Sink.head), + sourceWithIdleGap.keepAlive(0.6.seconds, () => 0).grouped(1000).runWith(Sink.head), 3.seconds) should ===(List(1, 2, 3, 4, 5, 0, 0, 0, 6, 7, 8, 9, 10)) } @@ -37,7 +37,7 @@ class FlowIdleInjectSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - Source.fromPublisher(upstream).keepAlive(1.second, () ⇒ 0).runWith(Sink.fromSubscriber(downstream)) + Source.fromPublisher(upstream).keepAlive(1.second, () => 0).runWith(Sink.fromSubscriber(downstream)) downstream.request(1) @@ -52,7 +52,7 @@ class FlowIdleInjectSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - (Source(1 to 10) ++ Source.fromPublisher(upstream)).keepAlive(1.second, () ⇒ 0).runWith(Sink.fromSubscriber(downstream)) + (Source(1 to 10) ++ Source.fromPublisher(upstream)).keepAlive(1.second, () => 0).runWith(Sink.fromSubscriber(downstream)) downstream.request(10) downstream.expectNextN(1 to 10) @@ -70,7 +70,7 @@ class FlowIdleInjectSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - Source.fromPublisher(upstream).keepAlive(1.second, () ⇒ 0).runWith(Sink.fromSubscriber(downstream)) + Source.fromPublisher(upstream).keepAlive(1.second, () => 0).runWith(Sink.fromSubscriber(downstream)) downstream.ensureSubscription() downstream.expectNoMsg(1.5.second) @@ -85,7 +85,7 @@ class FlowIdleInjectSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - (Source(1 to 10) ++ Source.fromPublisher(upstream)).keepAlive(1.second, () ⇒ 0).runWith(Sink.fromSubscriber(downstream)) + (Source(1 to 10) ++ Source.fromPublisher(upstream)).keepAlive(1.second, () => 0).runWith(Sink.fromSubscriber(downstream)) downstream.request(10) downstream.expectNextN(1 to 10) @@ -102,7 +102,7 @@ class FlowIdleInjectSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - Source.fromPublisher(upstream).keepAlive(1.second, () ⇒ 0).runWith(Sink.fromSubscriber(downstream)) + Source.fromPublisher(upstream).keepAlive(1.second, () => 0).runWith(Sink.fromSubscriber(downstream)) downstream.ensureSubscription() downstream.expectNoMsg(1.5.second) @@ -119,7 +119,7 @@ class FlowIdleInjectSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - (Source(1 to 10) ++ Source.fromPublisher(upstream)).keepAlive(1.second, () ⇒ 0).runWith(Sink.fromSubscriber(downstream)) + (Source(1 to 10) ++ Source.fromPublisher(upstream)).keepAlive(1.second, () => 0).runWith(Sink.fromSubscriber(downstream)) downstream.request(10) downstream.expectNextN(1 to 10) @@ -138,7 +138,7 @@ class FlowIdleInjectSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - Source.fromPublisher(upstream).keepAlive(1.second, () ⇒ 0).runWith(Sink.fromSubscriber(downstream)) + Source.fromPublisher(upstream).keepAlive(1.second, () => 0).runWith(Sink.fromSubscriber(downstream)) downstream.request(2) downstream.expectNoMsg(500.millis) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowInterleaveSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowInterleaveSpec.scala index 680dfc87f5..ddaf738576 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowInterleaveSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowInterleaveSpec.scala @@ -27,7 +27,7 @@ class FlowInterleaveSpec extends BaseTwoStreamsSetup { val subscription = probe.expectSubscription() var collected = Seq.empty[Int] - for (_ ← 1 to 12) { + for (_ <- 1 to 12) { subscription.request(1) collected :+= probe.expectNext() } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowIteratorSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowIteratorSpec.scala index a7cd5d9e87..69e67d5a05 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowIteratorSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowIteratorSpec.scala @@ -15,7 +15,7 @@ import akka.stream.testkit.scaladsl.StreamTestKit._ class FlowIteratorSpec extends AbstractFlowIteratorSpec { override def testName = "A Flow based on an iterator producing function" override def createSource(elements: Int): Source[Int, NotUsed] = - Source.fromIterator(() ⇒ (1 to elements).iterator) + Source.fromIterator(() => (1 to elements).iterator) } class FlowIterableSpec extends AbstractFlowIteratorSpec { @@ -28,7 +28,7 @@ class FlowIterableSpec extends AbstractFlowIteratorSpec { "produce onError when iterator throws" in { val iterable = new immutable.Iterable[Int] { override def iterator: Iterator[Int] = - (1 to 3).iterator.map(x ⇒ if (x == 2) throw new IllegalStateException("not two") else x) + (1 to 3).iterator.map(x => if (x == 2) throw new IllegalStateException("not two") else x) } val p = Source(iterable).runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[Int]() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowJoinSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowJoinSpec.scala index 4f26b0f295..ebc6e2f50d 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowJoinSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowJoinSpec.scala @@ -31,7 +31,7 @@ class FlowJoinSpec extends StreamSpec(ConfigFactory.parseString("akka.loglevel=I val source = Source(0 to end) val probe = TestSubscriber.manualProbe[Seq[Int]]() - val flow1 = Flow.fromGraph(GraphDSL.create() { implicit b ⇒ + val flow1 = Flow.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val merge = b.add(Merge[Int](2)) val broadcast = b.add(Broadcast[Int](2)) @@ -59,7 +59,7 @@ class FlowJoinSpec extends StreamSpec(ConfigFactory.parseString("akka.loglevel=I "allow for merge cycle" in assertAllStagesStopped { val source = Source.single("lonely traveler") - val flow1 = Flow.fromGraph(GraphDSL.create(Sink.head[String]) { implicit b ⇒ sink ⇒ + val flow1 = Flow.fromGraph(GraphDSL.create(Sink.head[String]) { implicit b => sink => import GraphDSL.Implicits._ val merge = b.add(Merge[String](2)) val broadcast = b.add(Broadcast[String](2, eagerCancel = true)) @@ -76,7 +76,7 @@ class FlowJoinSpec extends StreamSpec(ConfigFactory.parseString("akka.loglevel=I "allow for merge preferred cycle" in assertAllStagesStopped { val source = Source.single("lonely traveler") - val flow1 = Flow.fromGraph(GraphDSL.create(Sink.head[String]) { implicit b ⇒ sink ⇒ + val flow1 = Flow.fromGraph(GraphDSL.create(Sink.head[String]) { implicit b => sink => import GraphDSL.Implicits._ val merge = b.add(MergePreferred[String](1)) val broadcast = b.add(Broadcast[String](2, eagerCancel = true)) @@ -93,7 +93,7 @@ class FlowJoinSpec extends StreamSpec(ConfigFactory.parseString("akka.loglevel=I "allow for zip cycle" in assertAllStagesStopped { val source = Source(immutable.Seq("traveler1", "traveler2")) - val flow = Flow.fromGraph(GraphDSL.create(TestSink.probe[(String, String)]) { implicit b ⇒ sink ⇒ + val flow = Flow.fromGraph(GraphDSL.create(TestSink.probe[(String, String)]) { implicit b => sink => import GraphDSL.Implicits._ val zip = b.add(Zip[String, String]) val broadcast = b.add(Broadcast[(String, String)](2)) @@ -104,7 +104,7 @@ class FlowJoinSpec extends StreamSpec(ConfigFactory.parseString("akka.loglevel=I FlowShape(zip.in1, broadcast.out(1)) }) - val feedback = Flow.fromGraph(GraphDSL.create(Source.single("ignition")) { implicit b ⇒ ignition ⇒ + val feedback = Flow.fromGraph(GraphDSL.create(Source.single("ignition")) { implicit b => ignition => import GraphDSL.Implicits._ val flow = b.add(Flow[(String, String)].map(_._1)) val merge = b.add(Merge[String](2)) @@ -121,7 +121,7 @@ class FlowJoinSpec extends StreamSpec(ConfigFactory.parseString("akka.loglevel=I } "allow for concat cycle" in assertAllStagesStopped { - val flow = Flow.fromGraph(GraphDSL.create(TestSource.probe[String](system), Sink.head[String])(Keep.both) { implicit b ⇒ (source, sink) ⇒ + val flow = Flow.fromGraph(GraphDSL.create(TestSource.probe[String](system), Sink.head[String])(Keep.both) { implicit b => (source, sink) => import GraphDSL.Implicits._ val concat = b.add(Concat[String](2)) val broadcast = b.add(Broadcast[String](2, eagerCancel = true)) @@ -134,7 +134,7 @@ class FlowJoinSpec extends StreamSpec(ConfigFactory.parseString("akka.loglevel=I val (probe, result) = flow.join(Flow[String]).run() probe.sendNext("lonely traveler") - whenReady(result) { r ⇒ + whenReady(result) { r => r shouldBe "lonely traveler" probe.sendComplete() } @@ -143,7 +143,7 @@ class FlowJoinSpec extends StreamSpec(ConfigFactory.parseString("akka.loglevel=I "allow for interleave cycle" in assertAllStagesStopped { val source = Source.single("lonely traveler") - val flow1 = Flow.fromGraph(GraphDSL.create(Sink.head[String]) { implicit b ⇒ sink ⇒ + val flow1 = Flow.fromGraph(GraphDSL.create(Sink.head[String]) { implicit b => sink => import GraphDSL.Implicits._ val merge = b.add(Interleave[String](2, 1)) val broadcast = b.add(Broadcast[String](2, eagerCancel = true)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowKillSwitchSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowKillSwitchSpec.scala index d754f5f850..a5982bcf5a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowKillSwitchSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowKillSwitchSpec.scala @@ -49,7 +49,7 @@ class FlowKillSwitchSpec extends StreamSpec { val (((upstream, switch1), switch2), downstream) = TestSource.probe[Int] .viaMat(KillSwitches.single)(Keep.both) - .recover { case TE(_) ⇒ -1 } + .recover { case TE(_) => -1 } .viaMat(KillSwitches.single)(Keep.both) .toMat(TestSink.probe)(Keep.both).run() @@ -274,7 +274,7 @@ class FlowKillSwitchSpec extends StreamSpec { val switch1 = KillSwitches.shared("switch") val switch2 = KillSwitches.shared("switch") - val downstream = RunnableGraph.fromGraph(GraphDSL.create(TestSink.probe[Int]) { implicit b ⇒ snk ⇒ + val downstream = RunnableGraph.fromGraph(GraphDSL.create(TestSink.probe[Int]) { implicit b => snk => import GraphDSL.Implicits._ val merge = b.add(Merge[Int](2)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowLogSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowLogSpec.scala index 9370a862dc..df2e75ad34 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowLogSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowLogSpec.scala @@ -80,11 +80,11 @@ class FlowLogSpec extends StreamSpec(""" var finishCounter = 0 import scala.concurrent.duration._ logProbe.fishForMessage(3.seconds) { - case Logging.Debug(_, _, msg: String) if msg contains "Element: 1" ⇒ + case Logging.Debug(_, _, msg: String) if msg contains "Element: 1" => counter += 1 counter == 4 && finishCounter == 4 - case Logging.Debug(_, _, msg: String) if msg contains "Upstream finished" ⇒ + case Logging.Debug(_, _, msg: String) if msg contains "Upstream finished" => finishCounter += 1 counter == 4 && finishCounter == 4 } @@ -152,7 +152,7 @@ class FlowLogSpec extends StreamSpec(""" "follow supervision strategy when exception thrown" in { val ex = new RuntimeException() with NoStackTrace - val future = Source(1 to 5).log("hi", n ⇒ throw ex) + val future = Source(1 to 5).log("hi", n => throw ex) .withAttributes(supervisionStrategy(resumingDecider)).runWith(Sink.fold(0)(_ + _)) Await.result(future, 500.millis) shouldEqual 0 } @@ -172,11 +172,11 @@ class FlowLogSpec extends StreamSpec(""" var counter = 1 import scala.concurrent.duration._ logProbe.fishForMessage(3.seconds) { - case Logging.Debug(_, _, msg: String) if msg contains "Element: 1" ⇒ + case Logging.Debug(_, _, msg: String) if msg contains "Element: 1" => counter += 1 counter == 4 - case Logging.Debug(_, _, msg: String) if msg contains "Upstream finished" ⇒ + case Logging.Debug(_, _, msg: String) if msg contains "Upstream finished" => false } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapAsyncSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapAsyncSpec.scala index b97dc3ebf8..50683640c1 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapAsyncSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapAsyncSpec.scala @@ -32,7 +32,7 @@ class FlowMapAsyncSpec extends StreamSpec { "produce future elements" in assertAllStagesStopped { val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 3).mapAsync(4)(n ⇒ Future(n)).runWith(Sink.fromSubscriber(c)) + val p = Source(1 to 3).mapAsync(4)(n => Future(n)).runWith(Sink.fromSubscriber(c)) val sub = c.expectSubscription() sub.request(2) c.expectNext(1) @@ -46,7 +46,7 @@ class FlowMapAsyncSpec extends StreamSpec { "produce future elements in order" in { val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 50).mapAsync(4)(n ⇒ + val p = Source(1 to 50).mapAsync(4)(n => if (n % 3 == 0) Future.successful(n) else Future { Thread.sleep(ThreadLocalRandom.current().nextInt(1, 10)) @@ -54,7 +54,7 @@ class FlowMapAsyncSpec extends StreamSpec { }).to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(1000) - for (n ← 1 to 50) c.expectNext(n) + for (n <- 1 to 50) c.expectNext(n) c.expectComplete() } @@ -62,7 +62,7 @@ class FlowMapAsyncSpec extends StreamSpec { val probe = TestProbe() val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 20).mapAsync(8)(n ⇒ Future { + val p = Source(1 to 20).mapAsync(8)(n => Future { probe.ref ! n n }).to(Sink.fromSubscriber(c)).run() @@ -78,7 +78,7 @@ class FlowMapAsyncSpec extends StreamSpec { probe.receiveN(9).toSet should be((12 to 20).toSet) probe.expectNoMsg(200.millis) - for (n ← 1 to 13) c.expectNext(n) + for (n <- 1 to 13) c.expectNext(n) c.expectNoMsg(200.millis) } @@ -86,7 +86,7 @@ class FlowMapAsyncSpec extends StreamSpec { val latch = TestLatch(1) val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 5).mapAsync(4)(n ⇒ + val p = Source(1 to 5).mapAsync(4)(n => if (n == 3) Future.failed[Int](new TE("err1")) else Future { Await.ready(latch, 10.seconds) @@ -103,7 +103,7 @@ class FlowMapAsyncSpec extends StreamSpec { val latch = TestLatch(1) val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 5).mapAsync(4)(n ⇒ Future { + val p = Source(1 to 5).mapAsync(4)(n => Future { if (n == 3) throw new RuntimeException("err1") with NoStackTrace else { Await.ready(latch, 10.seconds) @@ -119,7 +119,7 @@ class FlowMapAsyncSpec extends StreamSpec { "signal future failure asap" in assertAllStagesStopped { val latch = TestLatch(1) val done = Source(1 to 5) - .map { n ⇒ + .map { n => if (n == 1) n else { // slow upstream should not block the error @@ -127,7 +127,7 @@ class FlowMapAsyncSpec extends StreamSpec { n } } - .mapAsync(4) { n ⇒ + .mapAsync(4) { n => if (n == 1) Future.failed(new RuntimeException("err1") with NoStackTrace) else Future.successful(n) }.runWith(Sink.ignore) @@ -148,16 +148,16 @@ class FlowMapAsyncSpec extends StreamSpec { val input = pa :: pb :: pc :: pd :: pe :: pf :: Nil - val probe = Source.fromIterator(() ⇒ input.iterator) - .mapAsync(5)(p ⇒ p.future.map(_.toUpperCase)) + val probe = Source.fromIterator(() => input.iterator) + .mapAsync(5)(p => p.future.map(_.toUpperCase)) .runWith(TestSink.probe) import TestSubscriber._ var gotErrorAlready = false val elementOrErrorOk: PartialFunction[SubscriberEvent, Unit] = { - case OnNext("A") ⇒ () // is fine - case OnNext("B") ⇒ () // is fine - case OnError(ex) if ex.getMessage == "Boom at C" && !gotErrorAlready ⇒ + case OnNext("A") => () // is fine + case OnNext("B") => () // is fine + case OnError(ex) if ex.getMessage == "Boom at C" && !gotErrorAlready => gotErrorAlready = true // fine, error can over-take elements } probe.request(100) @@ -174,14 +174,14 @@ class FlowMapAsyncSpec extends StreamSpec { pf.success("f") probe.expectNextOrError() match { - case Left(ex) ⇒ ex.getMessage should ===("Boom at C") // fine, error can over-take elements - case Right("A") ⇒ + case Left(ex) => ex.getMessage should ===("Boom at C") // fine, error can over-take elements + case Right("A") => probe.expectNextOrError() match { - case Left(ex) ⇒ ex.getMessage should ===("Boom at C") // fine, error can over-take elements - case Right("B") ⇒ + case Left(ex) => ex.getMessage should ===("Boom at C") // fine, error can over-take elements + case Right("B") => probe.expectNextOrError() match { - case Left(ex) ⇒ ex.getMessage should ===("Boom at C") // fine, error can over-take elements - case Right(element) ⇒ fail(s"Got [$element] yet it caused an exception, should not have happened!") + case Left(ex) => ex.getMessage should ===("Boom at C") // fine, error can over-take elements + case Right(element) => fail(s"Got [$element] yet it caused an exception, should not have happened!") } } } @@ -197,8 +197,8 @@ class FlowMapAsyncSpec extends StreamSpec { val input = pa :: pb :: pc :: pd :: pe :: pf :: Nil - val elements = Source.fromIterator(() ⇒ input.iterator) - .mapAsync(5)(p ⇒ p.future) + val elements = Source.fromIterator(() => input.iterator) + .mapAsync(5)(p => p.future) .withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider)) .runWith(Sink.seq) @@ -217,7 +217,7 @@ class FlowMapAsyncSpec extends StreamSpec { val latch = TestLatch(1) val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 5).mapAsync(4)(n ⇒ + val p = Source(1 to 5).mapAsync(4)(n => if (n == 3) throw new RuntimeException("err2") with NoStackTrace else { Future { @@ -236,7 +236,7 @@ class FlowMapAsyncSpec extends StreamSpec { val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher val p = Source(1 to 5) - .mapAsync(4)(n ⇒ Future { + .mapAsync(4)(n => Future { if (n == 3) throw new RuntimeException("err3") with NoStackTrace else n }) @@ -244,7 +244,7 @@ class FlowMapAsyncSpec extends StreamSpec { .to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) - for (n ← List(1, 2, 4, 5)) c.expectNext(n) + for (n <- List(1, 2, 4, 5)) c.expectNext(n) c.expectComplete() } @@ -252,7 +252,7 @@ class FlowMapAsyncSpec extends StreamSpec { val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher val p = Source(1 to 5) - .mapAsync(4)(n ⇒ + .mapAsync(4)(n => if (n == 3) Future.failed(new TE("err3")) else Future.successful(n) ) @@ -260,7 +260,7 @@ class FlowMapAsyncSpec extends StreamSpec { .to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) - for (n ← List(1, 2, 4, 5)) c.expectNext(n) + for (n <- List(1, 2, 4, 5)) c.expectNext(n) c.expectComplete() } @@ -281,7 +281,7 @@ class FlowMapAsyncSpec extends StreamSpec { "finish after future failure" in assertAllStagesStopped { import system.dispatcher - Await.result(Source(1 to 3).mapAsync(1)(n ⇒ Future { + Await.result(Source(1 to 3).mapAsync(1)(n => Future { if (n == 3) throw new RuntimeException("err3b") with NoStackTrace else n }).withAttributes(supervisionStrategy(resumingDecider)) @@ -293,20 +293,20 @@ class FlowMapAsyncSpec extends StreamSpec { val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher val p = Source(1 to 5) - .mapAsync(4)(n ⇒ + .mapAsync(4)(n => if (n == 3) throw new RuntimeException("err4") with NoStackTrace else Future(n)) .withAttributes(supervisionStrategy(resumingDecider)) .to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) - for (n ← List(1, 2, 4, 5)) c.expectNext(n) + for (n <- List(1, 2, 4, 5)) c.expectNext(n) c.expectComplete() } "signal NPE when future is completed with null" in { val c = TestSubscriber.manualProbe[String]() - val p = Source(List("a", "b")).mapAsync(4)(elem ⇒ Future.successful(null)).to(Sink.fromSubscriber(c)).run() + val p = Source(List("a", "b")).mapAsync(4)(elem => Future.successful(null)).to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) c.expectError().getMessage should be(ReactiveStreamsCompliance.ElementMustNotBeNullMsg) @@ -315,12 +315,12 @@ class FlowMapAsyncSpec extends StreamSpec { "resume when future is completed with null" in { val c = TestSubscriber.manualProbe[String]() val p = Source(List("a", "b", "c")) - .mapAsync(4)(elem ⇒ if (elem == "b") Future.successful(null) else Future.successful(elem)) + .mapAsync(4)(elem => if (elem == "b") Future.successful(null) else Future.successful(elem)) .withAttributes(supervisionStrategy(resumingDecider)) .to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) - for (elem ← List("a", "c")) c.expectNext(elem) + for (elem <- List("a", "c")) c.expectNext(elem) c.expectComplete() } @@ -358,7 +358,7 @@ class FlowMapAsyncSpec extends StreamSpec { count += 1 true } catch { - case _: InterruptedException ⇒ false + case _: InterruptedException => false } if (cont) run() } @@ -369,7 +369,7 @@ class FlowMapAsyncSpec extends StreamSpec { if (counter.incrementAndGet() > parallelism) Future.failed(new Exception("parallelism exceeded")) else { val p = Promise[Int] - queue.offer(p → System.nanoTime()) + queue.offer(p -> System.nanoTime()) p.future } } @@ -377,8 +377,8 @@ class FlowMapAsyncSpec extends StreamSpec { try { val N = 10000 Source(1 to N) - .mapAsync(parallelism)(i ⇒ deferred()) - .runFold(0)((c, _) ⇒ c + 1) + .mapAsync(parallelism)(i => deferred()) + .runFold(0)((c, _) => c + 1) .futureValue(Timeout(3.seconds)) should ===(N) } finally { timer.interrupt() @@ -389,16 +389,16 @@ class FlowMapAsyncSpec extends StreamSpec { import system.dispatcher val failCount = new AtomicInteger(0) val result = Source(List(true, false)) - .mapAsync(1)(elem ⇒ + .mapAsync(1)(elem => Future { if (elem) throw TE("this has gone too far") else elem } ).addAttributes(supervisionStrategy { - case TE("this has gone too far") ⇒ + case TE("this has gone too far") => failCount.incrementAndGet() Supervision.resume - case _ ⇒ Supervision.stop + case _ => Supervision.stop }) .runWith(Sink.seq) @@ -409,14 +409,14 @@ class FlowMapAsyncSpec extends StreamSpec { "not invoke the decider twice for the same already failed future" in { val failCount = new AtomicInteger(0) val result = Source(List(true, false)) - .mapAsync(1)(elem ⇒ + .mapAsync(1)(elem => if (elem) Future.failed(TE("this has gone too far")) else Future.successful(elem) ).addAttributes(supervisionStrategy { - case TE("this has gone too far") ⇒ + case TE("this has gone too far") => failCount.incrementAndGet() Supervision.resume - case _ ⇒ Supervision.stop + case _ => Supervision.stop }) .runWith(Sink.seq) @@ -428,16 +428,16 @@ class FlowMapAsyncSpec extends StreamSpec { import system.dispatcher val failCount = new AtomicInteger(0) val result = Source(List(true, false)) - .mapAsync(1)(elem ⇒ + .mapAsync(1)(elem => if (elem) throw TE("this has gone too far") else Future { elem } ).addAttributes(supervisionStrategy { - case TE("this has gone too far") ⇒ + case TE("this has gone too far") => failCount.incrementAndGet() Supervision.resume - case _ ⇒ Supervision.stop + case _ => Supervision.stop }) .runWith(Sink.seq) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapAsyncUnorderedSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapAsyncUnorderedSpec.scala index 97754e1795..85c73d0802 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapAsyncUnorderedSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapAsyncUnorderedSpec.scala @@ -34,8 +34,8 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { "produce future elements in the order they are ready" in assertAllStagesStopped { val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val latch = (1 to 4).map(_ → TestLatch(1)).toMap - val p = Source(1 to 4).mapAsyncUnordered(4)(n ⇒ Future { + val latch = (1 to 4).map(_ -> TestLatch(1)).toMap + val p = Source(1 to 4).mapAsyncUnordered(4)(n => Future { Await.ready(latch(n), 5.seconds) n }).to(Sink.fromSubscriber(c)).run() @@ -56,7 +56,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { val probe = TestProbe() val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 20).mapAsyncUnordered(4)(n ⇒ + val p = Source(1 to 20).mapAsyncUnordered(4)(n => if (n % 3 == 0) { probe.ref ! n Future.successful(n) @@ -75,7 +75,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { sub.request(25) probe.expectMsgAllOf(6 to 20: _*) c.within(3.seconds) { - for (_ ← 2 to 20) got += c.expectNext() + for (_ <- 2 to 20) got += c.expectNext() } got should be((1 to 20).toSet) @@ -86,7 +86,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { val latch = TestLatch(1) val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 5).mapAsyncUnordered(4)(n ⇒ Future { + val p = Source(1 to 5).mapAsyncUnordered(4)(n => Future { if (n == 3) throw new RuntimeException("err1") with NoStackTrace else { Await.ready(latch, 10.seconds) @@ -102,7 +102,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { "signal future failure asap" in assertAllStagesStopped { val latch = TestLatch(1) val done = Source(1 to 5) - .map { n ⇒ + .map { n => if (n == 1) n else { // slow upstream should not block the error @@ -110,7 +110,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { n } } - .mapAsyncUnordered(4) { n ⇒ + .mapAsyncUnordered(4) { n => if (n == 1) Future.failed(new RuntimeException("err1") with NoStackTrace) else Future.successful(n) }.runWith(Sink.ignore) @@ -124,7 +124,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { val latch = TestLatch(1) val c = TestSubscriber.manualProbe[Int]() implicit val ec = system.dispatcher - val p = Source(1 to 5).mapAsyncUnordered(4)(n ⇒ + val p = Source(1 to 5).mapAsyncUnordered(4)(n => if (n == 3) throw new RuntimeException("err2") with NoStackTrace else { Future { @@ -142,7 +142,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { "resume after future failure" in { implicit val ec = system.dispatcher Source(1 to 5) - .mapAsyncUnordered(4)(n ⇒ Future { + .mapAsyncUnordered(4)(n => Future { if (n == 3) throw new RuntimeException("err3") with NoStackTrace else n }) @@ -170,7 +170,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { "finish after future failure" in assertAllStagesStopped { import system.dispatcher - Await.result(Source(1 to 3).mapAsyncUnordered(1)(n ⇒ Future { + Await.result(Source(1 to 3).mapAsyncUnordered(1)(n => Future { if (n == 3) throw new RuntimeException("err3b") with NoStackTrace else n }).withAttributes(supervisionStrategy(resumingDecider)) @@ -181,7 +181,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { "resume when mapAsyncUnordered throws" in { implicit val ec = system.dispatcher Source(1 to 5) - .mapAsyncUnordered(4)(n ⇒ + .mapAsyncUnordered(4)(n => if (n == 3) throw new RuntimeException("err4") with NoStackTrace else Future(n)) .withAttributes(supervisionStrategy(resumingDecider)) @@ -193,7 +193,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { "signal NPE when future is completed with null" in { val c = TestSubscriber.manualProbe[String]() - val p = Source(List("a", "b")).mapAsyncUnordered(4)(elem ⇒ Future.successful(null)).to(Sink.fromSubscriber(c)).run() + val p = Source(List("a", "b")).mapAsyncUnordered(4)(elem => Future.successful(null)).to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() sub.request(10) c.expectError.getMessage should be(ReactiveStreamsCompliance.ElementMustNotBeNullMsg) @@ -202,7 +202,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { "resume when future is completed with null" in { val c = TestSubscriber.manualProbe[String]() val p = Source(List("a", "b", "c")) - .mapAsyncUnordered(4)(elem ⇒ if (elem == "b") Future.successful(null) else Future.successful(elem)) + .mapAsyncUnordered(4)(elem => if (elem == "b") Future.successful(null) else Future.successful(elem)) .withAttributes(supervisionStrategy(resumingDecider)) .to(Sink.fromSubscriber(c)).run() val sub = c.expectSubscription() @@ -245,7 +245,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { count += 1 true } catch { - case _: InterruptedException ⇒ false + case _: InterruptedException => false } if (cont) run() } @@ -256,7 +256,7 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { if (counter.incrementAndGet() > parallelism) Future.failed(new Exception("parallelism exceeded")) else { val p = Promise[Int] - queue.offer(p → System.nanoTime()) + queue.offer(p -> System.nanoTime()) p.future } } @@ -264,8 +264,8 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { try { val N = 10000 Source(1 to N) - .mapAsyncUnordered(parallelism)(i ⇒ deferred()) - .runFold(0)((c, _) ⇒ c + 1) + .mapAsyncUnordered(parallelism)(i => deferred()) + .runFold(0)((c, _) => c + 1) .futureValue(Timeout(3.seconds)) should ===(N) } finally { timer.interrupt() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapConcatSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapConcatSpec.scala index 443be37fcc..53402e012e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapConcatSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapConcatSpec.scala @@ -20,29 +20,29 @@ class FlowMapConcatSpec extends StreamSpec with ScriptedTest { "map and concat" in { val script = Script( - Seq(0) → Seq(), - Seq(1) → Seq(1), - Seq(2) → Seq(2, 2), - Seq(3) → Seq(3, 3, 3), - Seq(2) → Seq(2, 2), - Seq(1) → Seq(1)) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.mapConcat(x ⇒ (1 to x) map (_ ⇒ x)))) + Seq(0) -> Seq(), + Seq(1) -> Seq(1), + Seq(2) -> Seq(2, 2), + Seq(3) -> Seq(3, 3, 3), + Seq(2) -> Seq(2, 2), + Seq(1) -> Seq(1)) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.mapConcat(x => (1 to x) map (_ => x)))) } "map and concat grouping with slow downstream" in assertAllStagesStopped { val s = TestSubscriber.manualProbe[Int] val input = (1 to 20).grouped(5).toList - Source(input).mapConcat(identity).map(x ⇒ { Thread.sleep(10); x }).runWith(Sink.fromSubscriber(s)) + Source(input).mapConcat(identity).map(x => { Thread.sleep(10); x }).runWith(Sink.fromSubscriber(s)) val sub = s.expectSubscription() sub.request(100) - for (i ← 1 to 20) s.expectNext(i) + for (i <- 1 to 20) s.expectNext(i) s.expectComplete() } "be able to resume" in assertAllStagesStopped { val ex = new Exception("TEST") with NoStackTrace - Source(1 to 5).mapConcat(x ⇒ if (x == 3) throw ex else List(x)) + Source(1 to 5).mapConcat(x => if (x == 3) throw ex else List(x)) .withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider)) .runWith(TestSink.probe[Int]) .request(4).expectNext(1, 2, 4, 5) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapErrorSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapErrorSpec.scala index 094a75a95f..8a1bf124d7 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapErrorSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapErrorSpec.scala @@ -22,8 +22,8 @@ class FlowMapErrorSpec extends StreamSpec { "A MapError" must { "mapError when there is a handler" in assertAllStagesStopped { - Source(1 to 4).map { a ⇒ if (a == 3) throw ex else a } - .mapError { case t: Throwable ⇒ boom } + Source(1 to 4).map { a => if (a == 3) throw ex else a } + .mapError { case t: Throwable => boom } .runWith(TestSink.probe[Int]) .request(3) .expectNext(1) @@ -32,8 +32,8 @@ class FlowMapErrorSpec extends StreamSpec { } "fail the stream with exception thrown in handler (and log it)" in assertAllStagesStopped { - Source(1 to 3).map { a ⇒ if (a == 2) throw ex else a } - .mapError { case t: Exception ⇒ throw boom } + Source(1 to 3).map { a => if (a == 2) throw ex else a } + .mapError { case t: Exception => throw boom } .runWith(TestSink.probe[Int]) .requestNext(1) .request(1) @@ -41,8 +41,8 @@ class FlowMapErrorSpec extends StreamSpec { } "pass through the original exception if partial function does not handle it" in assertAllStagesStopped { - Source(1 to 3).map { a ⇒ if (a == 2) throw ex else a } - .mapError { case t: IndexOutOfBoundsException ⇒ boom } + Source(1 to 3).map { a => if (a == 2) throw ex else a } + .mapError { case t: IndexOutOfBoundsException => boom } .runWith(TestSink.probe[Int]) .requestNext(1) .request(1) @@ -51,7 +51,7 @@ class FlowMapErrorSpec extends StreamSpec { "not influence stream when there is no exceptions" in assertAllStagesStopped { Source(1 to 3).map(identity) - .mapError { case t: Throwable ⇒ boom } + .mapError { case t: Throwable => boom } .runWith(TestSink.probe[Int]) .request(3) .expectNextN(1 to 3) @@ -60,7 +60,7 @@ class FlowMapErrorSpec extends StreamSpec { "finish stream if it's empty" in assertAllStagesStopped { Source.empty.map(identity) - .mapError { case t: Throwable ⇒ boom } + .mapError { case t: Throwable => boom } .runWith(TestSink.probe[Int]) .request(1) .expectComplete() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapSpec.scala index ce718400f1..4e74e8bb87 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMapSpec.scala @@ -4,7 +4,7 @@ package akka.stream.scaladsl -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ random } +import java.util.concurrent.ThreadLocalRandom.{ current => random } import akka.stream.{ ActorMaterializer, ActorMaterializerSettings } import akka.stream.testkit._ @@ -19,8 +19,8 @@ class FlowMapSpec extends StreamSpec with ScriptedTest { "A Map" must { "map" in { - def script = Script(TestConfig.RandomTestRange map { _ ⇒ val x = random.nextInt(); Seq(x) → Seq(x.toString) }: _*) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.map(_.toString))) + def script = Script(TestConfig.RandomTestRange map { _ => val x = random.nextInt(); Seq(x) -> Seq(x.toString) }: _*) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.map(_.toString))) } "not blow up with high request counts" in { @@ -30,7 +30,7 @@ class FlowMapSpec extends StreamSpec with ScriptedTest { runWith(Sink.asPublisher(false)).subscribe(probe) val subscription = probe.expectSubscription() - for (_ ← 1 to 10000) { + for (_ <- 1 to 10000) { subscription.request(Int.MaxValue) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMergeSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMergeSpec.scala index d25f37fd40..7485404055 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMergeSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowMergeSpec.scala @@ -33,7 +33,7 @@ class FlowMergeSpec extends BaseTwoStreamsSetup { val subscription = probe.expectSubscription() var collected = Set.empty[Int] - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { subscription.request(1) collected += probe.expectNext() } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowOnCompleteSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowOnCompleteSpec.scala index cd31bbf5d1..78190872cd 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowOnCompleteSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowOnCompleteSpec.scala @@ -63,9 +63,9 @@ class FlowOnCompleteSpec extends StreamSpec with ScriptedTest { val p = TestPublisher.manualProbe[Int]() import system.dispatcher // for the Future.onComplete val foreachSink = Sink.foreach[Int] { - x ⇒ onCompleteProbe.ref ! ("foreach-" + x) + x => onCompleteProbe.ref ! ("foreach-" + x) } - val future = Source.fromPublisher(p).map { x ⇒ + val future = Source.fromPublisher(p).map { x => onCompleteProbe.ref ! ("map-" + x) x }.runWith(foreachSink) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowRecoverSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowRecoverSpec.scala index 374cf38ccf..c42400fec1 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowRecoverSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowRecoverSpec.scala @@ -21,8 +21,8 @@ class FlowRecoverSpec extends StreamSpec { "A Recover" must { "recover when there is a handler" in assertAllStagesStopped { - Source(1 to 4).map { a ⇒ if (a == 3) throw ex else a } - .recover { case t: Throwable ⇒ 0 } + Source(1 to 4).map { a => if (a == 3) throw ex else a } + .recover { case t: Throwable => 0 } .runWith(TestSink.probe[Int]) .requestNext(1) .requestNext(2) @@ -32,8 +32,8 @@ class FlowRecoverSpec extends StreamSpec { } "failed stream if handler is not for such exception type" in assertAllStagesStopped { - Source(1 to 3).map { a ⇒ if (a == 2) throw ex else a } - .recover { case t: IndexOutOfBoundsException ⇒ 0 } + Source(1 to 3).map { a => if (a == 2) throw ex else a } + .recover { case t: IndexOutOfBoundsException => 0 } .runWith(TestSink.probe[Int]) .requestNext(1) .request(1) @@ -42,7 +42,7 @@ class FlowRecoverSpec extends StreamSpec { "not influence stream when there is no exceptions" in assertAllStagesStopped { Source(1 to 3).map(identity) - .recover { case t: Throwable ⇒ 0 } + .recover { case t: Throwable => 0 } .runWith(TestSink.probe[Int]) .request(3) .expectNextN(1 to 3) @@ -51,7 +51,7 @@ class FlowRecoverSpec extends StreamSpec { "finish stream if it's empty" in assertAllStagesStopped { Source.empty.map(identity) - .recover { case t: Throwable ⇒ 0 } + .recover { case t: Throwable => 0 } .runWith(TestSink.probe[Int]) .request(1) .expectComplete() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowRecoverWithSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowRecoverWithSpec.scala index f2510b0741..dc37ceb682 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowRecoverWithSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowRecoverWithSpec.scala @@ -23,8 +23,8 @@ class FlowRecoverWithSpec extends StreamSpec { "A RecoverWith" must { "recover when there is a handler" in assertAllStagesStopped { - Source(1 to 4).map { a ⇒ if (a == 3) throw ex else a } - .recoverWith { case t: Throwable ⇒ Source(List(0, -1)) } + Source(1 to 4).map { a => if (a == 3) throw ex else a } + .recoverWith { case t: Throwable => Source(List(0, -1)) } .runWith(TestSink.probe[Int]) .request(2) .expectNextN(1 to 2) @@ -36,8 +36,8 @@ class FlowRecoverWithSpec extends StreamSpec { } "cancel substream if parent is terminated when there is a handler" in assertAllStagesStopped { - Source(1 to 4).map { a ⇒ if (a == 3) throw ex else a } - .recoverWith { case t: Throwable ⇒ Source(List(0, -1)) } + Source(1 to 4).map { a => if (a == 3) throw ex else a } + .recoverWith { case t: Throwable => Source(List(0, -1)) } .runWith(TestSink.probe[Int]) .request(2) .expectNextN(1 to 2) @@ -47,8 +47,8 @@ class FlowRecoverWithSpec extends StreamSpec { } "failed stream if handler is not for such exception type" in assertAllStagesStopped { - Source(1 to 3).map { a ⇒ if (a == 2) throw ex else a } - .recoverWith { case t: IndexOutOfBoundsException ⇒ Source.single(0) } + Source(1 to 3).map { a => if (a == 2) throw ex else a } + .recoverWith { case t: IndexOutOfBoundsException => Source.single(0) } .runWith(TestSink.probe[Int]) .request(1) .expectNext(1) @@ -57,8 +57,8 @@ class FlowRecoverWithSpec extends StreamSpec { } "be able to recover with the same unmaterialized source if configured" in assertAllStagesStopped { - val src = Source(1 to 3).map { a ⇒ if (a == 3) throw ex else a } - src.recoverWith { case t: Throwable ⇒ src } + val src = Source(1 to 3).map { a => if (a == 3) throw ex else a } + src.recoverWith { case t: Throwable => src } .runWith(TestSink.probe[Int]) .request(2) .expectNextN(1 to 2) @@ -71,7 +71,7 @@ class FlowRecoverWithSpec extends StreamSpec { "not influence stream when there is no exceptions" in assertAllStagesStopped { Source(1 to 3).map(identity) - .recoverWith { case t: Throwable ⇒ Source.single(0) } + .recoverWith { case t: Throwable => Source.single(0) } .runWith(TestSink.probe[Int]) .request(3) .expectNextN(1 to 3) @@ -80,18 +80,18 @@ class FlowRecoverWithSpec extends StreamSpec { "finish stream if it's empty" in assertAllStagesStopped { Source.empty.map(identity) - .recoverWith { case t: Throwable ⇒ Source.single(0) } + .recoverWith { case t: Throwable => Source.single(0) } .runWith(TestSink.probe[Int]) .request(3) .expectComplete() } "switch the second time if alternative source throws exception" in assertAllStagesStopped { - val k = Source(1 to 3).map { a ⇒ if (a == 3) throw new IndexOutOfBoundsException() else a } + val k = Source(1 to 3).map { a => if (a == 3) throw new IndexOutOfBoundsException() else a } .recoverWith { - case t: IndexOutOfBoundsException ⇒ - Source(List(11, 22)).map(m ⇒ if (m == 22) throw new IllegalArgumentException() else m) - case t: IllegalArgumentException ⇒ Source(List(33, 44)) + case t: IndexOutOfBoundsException => + Source(List(11, 22)).map(m => if (m == 22) throw new IllegalArgumentException() else m) + case t: IllegalArgumentException => Source(List(33, 44)) }.runWith(TestSink.probe[Int]) .request(2) .expectNextN(List(1, 2)) @@ -103,10 +103,10 @@ class FlowRecoverWithSpec extends StreamSpec { } "terminate with exception if partial function fails to match after an alternative source failure" in assertAllStagesStopped { - Source(1 to 3).map { a ⇒ if (a == 3) throw new IndexOutOfBoundsException() else a } + Source(1 to 3).map { a => if (a == 3) throw new IndexOutOfBoundsException() else a } .recoverWith { - case t: IndexOutOfBoundsException ⇒ - Source(List(11, 22)).map(m ⇒ if (m == 22) throw ex else m) + case t: IndexOutOfBoundsException => + Source(List(11, 22)).map(m => if (m == 22) throw ex else m) }.runWith(TestSink.probe[Int]) .request(2) .expectNextN(List(1, 2)) @@ -117,10 +117,10 @@ class FlowRecoverWithSpec extends StreamSpec { } "terminate with exception after set number of retries" in assertAllStagesStopped { - Source(1 to 3).map { a ⇒ if (a == 3) throw new IndexOutOfBoundsException() else a } + Source(1 to 3).map { a => if (a == 3) throw new IndexOutOfBoundsException() else a } .recoverWithRetries(3, { - case t: Throwable ⇒ - Source(List(11, 22, 33)).map(m ⇒ if (m == 33) throw ex else m) + case t: Throwable => + Source(List(11, 22, 33)).map(m => if (m == 33) throw ex else m) }).runWith(TestSink.probe[Int]) .request(100) .expectNextN(List(1, 2)) @@ -131,8 +131,8 @@ class FlowRecoverWithSpec extends StreamSpec { } "not attempt recovering when attempts is zero" in assertAllStagesStopped { - Source(1 to 3).map { a ⇒ if (a == 3) throw ex else a } - .recoverWithRetries(0, { case t: Throwable ⇒ Source(List(22, 33)) }) + Source(1 to 3).map { a => if (a == 3) throw ex else a } + .recoverWithRetries(0, { case t: Throwable => Source(List(22, 33)) }) .runWith(TestSink.probe[Int]) .request(100) .expectNextN(List(1, 2)) @@ -140,24 +140,24 @@ class FlowRecoverWithSpec extends StreamSpec { } "recover infinitely when negative (-1) number of attempts given" in assertAllStagesStopped { - val oneThenBoom = Source(1 to 2).map { a ⇒ if (a == 2) throw ex else a } + val oneThenBoom = Source(1 to 2).map { a => if (a == 2) throw ex else a } oneThenBoom - .recoverWithRetries(-1, { case t: Throwable ⇒ oneThenBoom }) + .recoverWithRetries(-1, { case t: Throwable => oneThenBoom }) .runWith(TestSink.probe[Int]) .request(5) - .expectNextN(List(1, 2, 3, 4, 5).map(_ ⇒ 1)) + .expectNextN(List(1, 2, 3, 4, 5).map(_ => 1)) .cancel() } "recover infinitely when negative (smaller than -1) number of attempts given" in assertAllStagesStopped { - val oneThenBoom = Source(1 to 2).map { a ⇒ if (a == 2) throw ex else a } + val oneThenBoom = Source(1 to 2).map { a => if (a == 2) throw ex else a } oneThenBoom - .recoverWithRetries(-10, { case t: Throwable ⇒ oneThenBoom }) + .recoverWithRetries(-10, { case t: Throwable => oneThenBoom }) .runWith(TestSink.probe[Int]) .request(5) - .expectNextN(List(1, 2, 3, 4, 5).map(_ ⇒ 1)) + .expectNextN(List(1, 2, 3, 4, 5).map(_ => 1)) .cancel() } @@ -172,7 +172,7 @@ class FlowRecoverWithSpec extends StreamSpec { } val result = Source.failed(TE("trigger")).recoverWithRetries(1, { - case _: TE ⇒ Source.fromGraph(FailingInnerMat) + case _: TE => Source.fromGraph(FailingInnerMat) }).runWith(Sink.ignore) result.failed.futureValue should ===(matFail) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowReduceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowReduceSpec.scala index 12cddc9af8..7a4bad862a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowReduceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowReduceSpec.scala @@ -19,9 +19,9 @@ class FlowReduceSpec extends StreamSpec { "A Reduce" must { val input = 1 to 100 val expected = input.sum - val inputSource = Source(input).filter(_ ⇒ true).map(identity) - val reduceSource = inputSource.reduce[Int](_ + _).filter(_ ⇒ true).map(identity) - val reduceFlow = Flow[Int].filter(_ ⇒ true).map(identity).reduce(_ + _).filter(_ ⇒ true).map(identity) + val inputSource = Source(input).filter(_ => true).map(identity) + val reduceSource = inputSource.reduce[Int](_ + _).filter(_ => true).map(identity) + val reduceFlow = Flow[Int].filter(_ => true).map(identity).reduce(_ + _).filter(_ => true).map(identity) val reduceSink = Sink.reduce[Int](_ + _) "work when using Source.runReduce" in assertAllStagesStopped { @@ -46,26 +46,26 @@ class FlowReduceSpec extends StreamSpec { "propagate an error" in assertAllStagesStopped { val error = TE("Boom!") - val future = inputSource.map(x ⇒ if (x > 50) throw error else x).runReduce(Keep.none) + val future = inputSource.map(x => if (x > 50) throw error else x).runReduce(Keep.none) the[Exception] thrownBy Await.result(future, 3.seconds) should be(error) } "complete future with failure when reducing function throws and the supervisor strategy decides to stop" in assertAllStagesStopped { val error = TE("Boom!") - val future = inputSource.runReduce[Int]((x, y) ⇒ if (x > 50) throw error else x + y) + val future = inputSource.runReduce[Int]((x, y) => if (x > 50) throw error else x + y) the[Exception] thrownBy Await.result(future, 3.seconds) should be(error) } "resume with the accumulated state when the folding function throws and the supervisor strategy decides to resume" in assertAllStagesStopped { val error = TE("Boom!") - val reduce = Sink.reduce[Int]((x, y) ⇒ if (y == 50) throw error else x + y) + val reduce = Sink.reduce[Int]((x, y) => if (y == 50) throw error else x + y) val future = inputSource.runWith(reduce.withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider))) Await.result(future, 3.seconds) should be(expected - 50) } "resume and reset the state when the folding function throws when the supervisor strategy decides to restart" in assertAllStagesStopped { val error = TE("Boom!") - val reduce = Sink.reduce[Int]((x, y) ⇒ if (y == 50) throw error else x + y) + val reduce = Sink.reduce[Int]((x, y) => if (y == 50) throw error else x + y) val future = inputSource.runWith(reduce.withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider))) Await.result(future, 3.seconds) should be((51 to 100).sum) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowScanAsyncSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowScanAsyncSpec.scala index 37e3edbb30..86ee221e8f 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowScanAsyncSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowScanAsyncSpec.scala @@ -25,7 +25,7 @@ class FlowScanAsyncSpec extends StreamSpec { "A ScanAsync" must { - val sumScanFlow = Flow[Int].scanAsync(0) { (accumulator, next) ⇒ + val sumScanFlow = Flow[Int].scanAsync(0) { (accumulator, next) => Future(accumulator + next) } @@ -40,7 +40,7 @@ class FlowScanAsyncSpec extends StreamSpec { "complete after zero-element has been consumed" in { val (pub, sub) = TestSource.probe[Int] - .via(Flow[Int].scanAsync(0)((acc, in) ⇒ Future.successful(acc + in))) + .via(Flow[Int].scanAsync(0)((acc, in) => Future.successful(acc + in))) .toMat(TestSink.probe)(Keep.both) .run() @@ -53,7 +53,7 @@ class FlowScanAsyncSpec extends StreamSpec { "complete after stream has been consumed and pending futures resolved" in { val (pub, sub) = TestSource.probe[Int] - .via(Flow[Int].scanAsync(0)((acc, in) ⇒ Future.successful(acc + in))) + .via(Flow[Int].scanAsync(0)((acc, in) => Future.successful(acc + in))) .toMat(TestSink.probe)(Keep.both) .run() @@ -68,7 +68,7 @@ class FlowScanAsyncSpec extends StreamSpec { "fail after zero-element has been consumed" in { val (pub, sub) = TestSource.probe[Int] - .via(Flow[Int].scanAsync(0)((acc, in) ⇒ Future.successful(acc + in))) + .via(Flow[Int].scanAsync(0)((acc, in) => Future.successful(acc + in))) .toMat(TestSink.probe)(Keep.both) .run() @@ -93,12 +93,12 @@ class FlowScanAsyncSpec extends StreamSpec { val eventualActual: Future[Int] = Source(elements) .via(sumScanFlow) .runWith(Sink.last) - whenReady(eventualActual) { actual ⇒ assert(actual === expectedSum) } + whenReady(eventualActual) { actual => assert(actual === expectedSum) } } "work with slow futures" in { val delay = 500.milliseconds - val delayedFutureScanFlow = Flow[Int].scanAsync(0) { (accumulator, next) ⇒ + val delayedFutureScanFlow = Flow[Int].scanAsync(0) { (accumulator, next) => pattern.after(delay, system.scheduler)(Future.successful(accumulator + next)) } val elements = 1 :: 1 :: Nil @@ -227,7 +227,7 @@ class FlowScanAsyncSpec extends StreamSpec { zero: Int, throwable: Throwable = new Exception("non fatal exception"), decider: Supervision.Decider = Supervision.stoppingDecider): Probe[Int] = { - val failedScanFlow = Flow[Int].scanAsync(zero) { (accumulator: Int, next: Int) ⇒ + val failedScanFlow = Flow[Int].scanAsync(zero) { (accumulator: Int, next: Int) => if (next >= 0) Future(accumulator + next) else throw throwable } @@ -245,7 +245,7 @@ class FlowScanAsyncSpec extends StreamSpec { decider: Supervision.Decider = Supervision.stoppingDecider ): (TestPublisher.Probe[Int], TestSubscriber.Probe[Int]) = { require(promises.nonEmpty, "must be at least one promise") - val promiseScanFlow = Flow[Int].scanAsync(zero) { (accumulator: Int, next: Int) ⇒ + val promiseScanFlow = Flow[Int].scanAsync(zero) { (accumulator: Int, next: Int) => promises(next).future } @@ -265,7 +265,7 @@ class FlowScanAsyncSpec extends StreamSpec { zero: Int, throwable: Throwable = new Exception("non fatal exception"), decider: Supervision.Decider = Supervision.stoppingDecider): Probe[Int] = { - val failedFutureScanFlow = Flow[Int].scanAsync(zero) { (accumulator: Int, next: Int) ⇒ + val failedFutureScanFlow = Flow[Int].scanAsync(zero) { (accumulator: Int, next: Int) => if (next >= 0) Future(accumulator + next) else Future.failed(throwable) } @@ -281,7 +281,7 @@ class FlowScanAsyncSpec extends StreamSpec { elements: immutable.Seq[String], zero: String, decider: Supervision.Decider = Supervision.stoppingDecider): Probe[String] = { - val nullFutureScanFlow: Flow[String, String, _] = Flow[String].scanAsync(zero) { (_: String, next: String) ⇒ + val nullFutureScanFlow: Flow[String, String, _] = Flow[String].scanAsync(zero) { (_: String, next: String) => if (next != "null") Future(next) else Future(null) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowScanSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowScanSpec.scala index b3bef6c95a..7d3abd8f38 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowScanSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowScanSpec.scala @@ -14,7 +14,7 @@ import akka.stream.testkit.scaladsl.StreamTestKit._ import scala.collection.immutable import scala.concurrent.Await import scala.concurrent.duration._ -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ random } +import java.util.concurrent.ThreadLocalRandom.{ current => random } class FlowScanSpec extends StreamSpec { @@ -49,7 +49,7 @@ class FlowScanSpec extends StreamSpec { "restart properly" in { import ActorAttributes._ - val scan = Flow[Int].scan(0) { (old, current) ⇒ + val scan = Flow[Int].scan(0) { (old, current) => require(current > 0) old + current }.withAttributes(supervisionStrategy(Supervision.restartingDecider)) @@ -59,7 +59,7 @@ class FlowScanSpec extends StreamSpec { "resume properly" in { import ActorAttributes._ - val scan = Flow[Int].scan(0) { (old, current) ⇒ + val scan = Flow[Int].scan(0) { (old, current) => require(current > 0) old + current }.withAttributes(supervisionStrategy(Supervision.resumingDecider)) @@ -68,7 +68,7 @@ class FlowScanSpec extends StreamSpec { } "scan normally for empty source" in { - Source.empty[Int].scan(0) { case (a, b) ⇒ a + b }.runWith(TestSink.probe[Int]) + Source.empty[Int].scan(0) { case (a, b) => a + b }.runWith(TestSink.probe[Int]) .request(2) .expectNext(0) .expectComplete() @@ -77,7 +77,7 @@ class FlowScanSpec extends StreamSpec { "fail when upstream failed" in { val ex = TE("") Source.failed[Int](ex) - .scan(0) { case (a, b) ⇒ a + b } + .scan(0) { case (a, b) => a + b } .runWith(TestSink.probe[Int]) .request(2) .expectNextOrError(0, ex) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSectionSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSectionSpec.scala index ceb2ca3b36..9b36fd472f 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSectionSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSectionSpec.scala @@ -70,17 +70,17 @@ class FlowSectionSpec extends StreamSpec(FlowSectionSpec.config) { val customDispatcher = TestProbe() val f1 = Flow[Int].map(sendThreadNameTo(defaultDispatcher.ref)) - val f2 = Flow[Int].map(sendThreadNameTo(customDispatcher.ref)).map(x ⇒ x) + val f2 = Flow[Int].map(sendThreadNameTo(customDispatcher.ref)).map(x => x) .withAttributes(dispatcher("my-dispatcher1") and name("separate-disptacher")) Source(0 to 2).via(f1).via(f2).runWith(Sink.ignore) defaultDispatcher.receiveN(3).foreach { - case s: String ⇒ s should include("akka.test.stream-dispatcher") + case s: String => s should include("akka.test.stream-dispatcher") } customDispatcher.receiveN(3).foreach { - case s: String ⇒ s should include("my-dispatcher1") + case s: String => s should include("my-dispatcher1") } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSlidingSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSlidingSpec.scala index 4589b88502..458fa5eb35 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSlidingSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSlidingSpec.scala @@ -22,38 +22,38 @@ class FlowSlidingSpec extends StreamSpec with GeneratorDrivenPropertyChecks { import org.scalacheck.Shrink.shrinkAny def check(gen: Gen[(Int, Int, Int)]): Unit = forAll(gen, MinSize(1000), MaxSize(1000)) { - case (len, win, step) ⇒ - val af = Source.fromIterator(() ⇒ Iterator.from(0).take(len)).sliding(win, step).runFold(Seq.empty[Seq[Int]])(_ :+ _) - val cf = Source.fromIterator(() ⇒ Iterator.from(0).take(len).sliding(win, step)).runFold(Seq.empty[Seq[Int]])(_ :+ _) + case (len, win, step) => + val af = Source.fromIterator(() => Iterator.from(0).take(len)).sliding(win, step).runFold(Seq.empty[Seq[Int]])(_ :+ _) + val cf = Source.fromIterator(() => Iterator.from(0).take(len).sliding(win, step)).runFold(Seq.empty[Seq[Int]])(_ :+ _) af.futureValue should be(cf.futureValue) } "behave just like collections sliding with step < window" in assertAllStagesStopped { check(for { - len ← Gen.choose(0, 31) - win ← Gen.choose(1, 61) - step ← Gen.choose(1, (win - 1) max 1) + len <- Gen.choose(0, 31) + win <- Gen.choose(1, 61) + step <- Gen.choose(1, (win - 1) max 1) } yield (len, win, step)) } "behave just like collections sliding with step == window" in assertAllStagesStopped { check(for { - len ← Gen.choose(0, 31) - win ← Gen.choose(1, 61) - step ← Gen.const(win) + len <- Gen.choose(0, 31) + win <- Gen.choose(1, 61) + step <- Gen.const(win) } yield (len, win, step)) } "behave just like collections sliding with step > window" in assertAllStagesStopped { check(for { - len ← Gen.choose(0, 31) - win ← Gen.choose(1, 61) - step ← Gen.choose(win + 1, 127) + len <- Gen.choose(0, 31) + win <- Gen.choose(1, 61) + step <- Gen.choose(win + 1, 127) } yield (len, win, step)) } "work with empty sources" in assertAllStagesStopped { - Source.empty.sliding(1).runForeach(testActor ! _).map(_ ⇒ "done") pipeTo testActor + Source.empty.sliding(1).runForeach(testActor ! _).map(_ => "done") pipeTo testActor expectMsg("done") } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSpec.scala index 4d93e65048..585a3837aa 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSpec.scala @@ -25,7 +25,7 @@ object FlowSpec { class Fruit class Apple extends Fruit class Orange extends Fruit - val fruits = () ⇒ new Iterator[Fruit] { + val fruits = () => new Iterator[Fruit] { override def hasNext: Boolean = true override def next(): Fruit = if (ThreadLocalRandom.current().nextBoolean()) new Apple else new Orange } @@ -40,14 +40,14 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("akka.actor.debug.re implicit val materializer = ActorMaterializer(settings) - val identity: Flow[Any, Any, NotUsed] ⇒ Flow[Any, Any, NotUsed] = in ⇒ in.map(e ⇒ e) - val identity2: Flow[Any, Any, NotUsed] ⇒ Flow[Any, Any, NotUsed] = in ⇒ identity(in) + val identity: Flow[Any, Any, NotUsed] => Flow[Any, Any, NotUsed] = in => in.map(e => e) + val identity2: Flow[Any, Any, NotUsed] => Flow[Any, Any, NotUsed] = in => identity(in) - val toPublisher: (Source[Any, _], ActorMaterializer) ⇒ Publisher[Any] = - (f, m) ⇒ f.runWith(Sink.asPublisher(false))(m) + val toPublisher: (Source[Any, _], ActorMaterializer) => Publisher[Any] = + (f, m) => f.runWith(Sink.asPublisher(false))(m) - def toFanoutPublisher[In, Out](elasticity: Int): (Source[Out, _], ActorMaterializer) ⇒ Publisher[Out] = - (f, m) ⇒ f.runWith(Sink.asPublisher(true).withAttributes(Attributes.inputBuffer(elasticity, elasticity)))(m) + def toFanoutPublisher[In, Out](elasticity: Int): (Source[Out, _], ActorMaterializer) => Publisher[Out] = + (f, m) => f.runWith(Sink.asPublisher(true).withAttributes(Attributes.inputBuffer(elasticity, elasticity)))(m) def materializeIntoSubscriberAndPublisher[In, Out](flow: Flow[In, Out, _]): (Subscriber[In], Publisher[Out]) = { flow.runWith(Source.asSubscriber[In], Sink.asPublisher[Out](false)) @@ -55,7 +55,7 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("akka.actor.debug.re "A Flow" must { - for ((name, op) ← List("identity" → identity, "identity2" → identity2); n ← List(1, 2, 4)) { + for ((name, op) <- List("identity" -> identity, "identity2" -> identity2); n <- List(1, 2, 4)) { s"request initial elements from upstream ($name, $n)" in { new ChainSetup(op, settings.withInputBuffer(initialSize = n, maxSize = n), toPublisher) { upstream.expectRequest(upstreamSubscription, settings.maxInputBufferSize) @@ -143,7 +143,7 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("akka.actor.debug.re } "materialize into Publisher/Subscriber and transformation processor" in { - val flow = Flow[Int].map((i: Int) ⇒ i.toString) + val flow = Flow[Int].map((i: Int) => i.toString) val (flowIn: Subscriber[Int], flowOut: Publisher[String]) = materializeIntoSubscriberAndPublisher(flow) val c1 = TestSubscriber.manualProbe[String]() @@ -196,7 +196,7 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("akka.actor.debug.re } "perform transformation operation" in { - val flow = Flow[Int].map(i ⇒ { testActor ! i.toString; i.toString }) + val flow = Flow[Int].map(i => { testActor ! i.toString; i.toString }) val publisher = Source(List(1, 2, 3)).runWith(Sink.asPublisher(false)) Source.fromPublisher(publisher).via(flow).to(Sink.ignore).run() @@ -257,17 +257,17 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("akka.actor.debug.re "be covariant" in { val f1: Source[Fruit, _] = Source.fromIterator[Fruit](fruits) val p1: Publisher[Fruit] = Source.fromIterator[Fruit](fruits).runWith(Sink.asPublisher(false)) - val f2: SubFlow[Fruit, _, Source[Fruit, NotUsed]#Repr, _] = Source.fromIterator[Fruit](fruits).splitWhen(_ ⇒ true) - val f3: SubFlow[Fruit, _, Source[Fruit, NotUsed]#Repr, _] = Source.fromIterator[Fruit](fruits).groupBy(2, _ ⇒ true) + val f2: SubFlow[Fruit, _, Source[Fruit, NotUsed]#Repr, _] = Source.fromIterator[Fruit](fruits).splitWhen(_ => true) + val f3: SubFlow[Fruit, _, Source[Fruit, NotUsed]#Repr, _] = Source.fromIterator[Fruit](fruits).groupBy(2, _ => true) val f4: Source[(immutable.Seq[Fruit], Source[Fruit, _]), _] = Source.fromIterator[Fruit](fruits).prefixAndTail(1) - val d1: SubFlow[Fruit, _, Flow[String, Fruit, NotUsed]#Repr, _] = Flow[String].map(_ ⇒ new Apple).splitWhen(_ ⇒ true) - val d2: SubFlow[Fruit, _, Flow[String, Fruit, NotUsed]#Repr, _] = Flow[String].map(_ ⇒ new Apple).groupBy(2, _ ⇒ true) - val d3: Flow[String, (immutable.Seq[Apple], Source[Fruit, _]), _] = Flow[String].map(_ ⇒ new Apple).prefixAndTail(1) + val d1: SubFlow[Fruit, _, Flow[String, Fruit, NotUsed]#Repr, _] = Flow[String].map(_ => new Apple).splitWhen(_ => true) + val d2: SubFlow[Fruit, _, Flow[String, Fruit, NotUsed]#Repr, _] = Flow[String].map(_ => new Apple).groupBy(2, _ => true) + val d3: Flow[String, (immutable.Seq[Apple], Source[Fruit, _]), _] = Flow[String].map(_ => new Apple).prefixAndTail(1) } "be possible to convert to a processor, and should be able to take a Processor" in { val identity1 = Flow[Int].toProcessor - val identity2 = Flow.fromProcessor(() ⇒ identity1.run()) + val identity2 = Flow.fromProcessor(() => identity1.run()) Await.result( Source(1 to 10).via(identity2).limit(100).runWith(Sink.seq), 3.seconds) should ===(1 to 10) @@ -279,25 +279,25 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("akka.actor.debug.re } "eliminate passed in when matval from passed in not used" in { - val map = Flow.fromFunction((n: Int) ⇒ n + 1) + val map = Flow.fromFunction((n: Int) => n + 1) val result = map.viaMat(Flow[Int])(Keep.left) result shouldBe theSameInstanceAs(map) } "not eliminate passed in when matval from passed in is used" in { - val map = Flow.fromFunction((n: Int) ⇒ n + 1) + val map = Flow.fromFunction((n: Int) => n + 1) val result = map.viaMat(Flow[Int])(Keep.right) result shouldNot be theSameInstanceAs (map) } "eliminate itself if identity" in { - val map = Flow.fromFunction((n: Int) ⇒ n + 1) + val map = Flow.fromFunction((n: Int) => n + 1) val result = Flow[Int].viaMat(map)(Keep.right) result shouldBe theSameInstanceAs(map) } "not eliminate itself if identity but matval is used" in { - val map = Flow.fromFunction((n: Int) ⇒ n + 1) + val map = Flow.fromFunction((n: Int) => n + 1) val result = Flow[Int].viaMat(map)(Keep.left) result shouldNot be theSameInstanceAs (map) } @@ -487,7 +487,7 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("akka.actor.debug.re } "call future subscribers' onError should be called instead of onSubscribed after initial upstream reported an error" in { - new ChainSetup[Int, String, NotUsed](_.map(_ ⇒ throw TestException), settings.withInputBuffer(initialSize = 1, maxSize = 1), + new ChainSetup[Int, String, NotUsed](_.map(_ => throw TestException), settings.withInputBuffer(initialSize = 1, maxSize = 1), toFanoutPublisher(1)) { downstreamSubscription.request(1) upstreamSubscription.expectRequest(1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSplitAfterSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSplitAfterSpec.scala index e81ed35833..852e8b8d61 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSplitAfterSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSplitAfterSpec.scala @@ -121,7 +121,7 @@ class FlowSplitAfterSpec extends StreamSpec { "work with single elem splits" in assertAllStagesStopped { Await.result( - Source(1 to 10).splitAfter(_ ⇒ true).lift + Source(1 to 10).splitAfter(_ => true).lift .mapAsync(1)(_.runWith(Sink.head)) // Please note that this line *also* implicitly asserts nonempty substreams .grouped(10).runWith(Sink.head), 3.second) should ===(1 to 10) @@ -163,7 +163,7 @@ class FlowSplitAfterSpec extends StreamSpec { val publisherProbeProbe = TestPublisher.manualProbe[Int]() val exc = TE("test") val publisher = Source.fromPublisher(publisherProbeProbe) - .splitAfter(elem ⇒ if (elem == 3) throw exc else elem % 3 == 0) + .splitAfter(elem => if (elem == 3) throw exc else elem % 3 == 0) .lift .runWith(Sink.asPublisher(false)) val subscriber = TestSubscriber.manualProbe[Source[Int, NotUsed]]() @@ -198,7 +198,7 @@ class FlowSplitAfterSpec extends StreamSpec { val publisherProbeProbe = TestPublisher.manualProbe[Int]() val exc = TE("test") val publisher = Source.fromPublisher(publisherProbeProbe) - .splitAfter(elem ⇒ if (elem == 3) throw exc else elem % 3 == 0) + .splitAfter(elem => if (elem == 3) throw exc else elem % 3 == 0) .lift .withAttributes(ActorAttributes.supervisionStrategy(resumingDecider)) .runWith(Sink.asPublisher(false)) @@ -285,7 +285,7 @@ class FlowSplitAfterSpec extends StreamSpec { .withSubscriptionTimeoutSettings( StreamSubscriptionTimeoutSettings(StreamSubscriptionTimeoutTerminationMode.cancel, 500.millisecond))) - val testSource = Source.single(1).concat(Source.maybe).splitAfter(_ ⇒ true) + val testSource = Source.single(1).concat(Source.maybe).splitAfter(_ => true) a[SubscriptionTimeoutException] mustBe thrownBy { Await.result( diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSplitWhenSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSplitWhenSpec.scala index fd7c19bd8d..adeb0459c5 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSplitWhenSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSplitWhenSpec.scala @@ -96,7 +96,7 @@ class FlowSplitWhenSpec extends StreamSpec { Await.result( Source.empty[Int] - .splitWhen(_ ⇒ true).lift + .splitWhen(_ => true).lift .mapAsync(1)(_.runWith(Sink.headOption)).grouped(10).runWith(Sink.headOption), 3.seconds) should ===(None) // rather tricky way of saying that no empty substream should be emitted (vs. Some(None)) @@ -223,7 +223,7 @@ class FlowSplitWhenSpec extends StreamSpec { val publisherProbeProbe = TestPublisher.manualProbe[Int]() val exc = TE("test") val publisher = Source.fromPublisher(publisherProbeProbe) - .splitWhen(elem ⇒ if (elem == 3) throw exc else elem % 3 == 0) + .splitWhen(elem => if (elem == 3) throw exc else elem % 3 == 0) .lift .runWith(Sink.asPublisher(false)) val subscriber = TestSubscriber.manualProbe[Source[Int, NotUsed]]() @@ -254,7 +254,7 @@ class FlowSplitWhenSpec extends StreamSpec { "work with single elem splits" in assertAllStagesStopped { Await.result( - Source(1 to 100).splitWhen(_ ⇒ true).lift + Source(1 to 100).splitWhen(_ => true).lift .mapAsync(1)(_.runWith(Sink.head)) // Please note that this line *also* implicitly asserts nonempty substreams .grouped(200).runWith(Sink.head), 3.second) should ===(1 to 100) @@ -265,8 +265,8 @@ class FlowSplitWhenSpec extends StreamSpec { .withInputBuffer(initialSize = 1, maxSize = 1)) import system.dispatcher - val probe = Source(1 to 5).splitWhen(_ ⇒ true).lift - .map { src ⇒ src.runWith(Sink.ignore)(mat).flatMap(_ ⇒ src.runWith(Sink.ignore)(mat)) } + val probe = Source(1 to 5).splitWhen(_ => true).lift + .map { src => src.runWith(Sink.ignore)(mat).flatMap(_ => src.runWith(Sink.ignore)(mat)) } .runWith(TestSink.probe[Future[Done]])(mat) probe.request(1) val future = probe.requestNext() @@ -282,7 +282,7 @@ class FlowSplitWhenSpec extends StreamSpec { .withSubscriptionTimeoutSettings( StreamSubscriptionTimeoutSettings(StreamSubscriptionTimeoutTerminationMode.cancel, 500.millisecond))) - val testSource = Source.single(1).concat(Source.maybe).splitWhen(_ ⇒ true) + val testSource = Source.single(1).concat(Source.maybe).splitWhen(_ => true) a[SubscriptionTimeoutException] mustBe thrownBy { Await.result( @@ -301,7 +301,7 @@ class FlowSplitWhenSpec extends StreamSpec { val publisherProbeProbe = TestPublisher.manualProbe[Int]() val exc = TE("test") val publisher = Source.fromPublisher(publisherProbeProbe) - .splitWhen(elem ⇒ if (elem == 3) throw exc else elem % 3 == 0) + .splitWhen(elem => if (elem == 3) throw exc else elem % 3 == 0) .lift .withAttributes(ActorAttributes.supervisionStrategy(resumingDecider)) .runWith(Sink.asPublisher(false)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowStatefulMapConcatSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowStatefulMapConcatSpec.scala index 96aa4cc228..a33e16f08e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowStatefulMapConcatSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowStatefulMapConcatSpec.scala @@ -20,17 +20,17 @@ class FlowStatefulMapConcatSpec extends StreamSpec with ScriptedTest { "work in happy case" in { val script = Script( - Seq(2) → Seq(), - Seq(1) → Seq(1, 1), - Seq(3) → Seq(3), - Seq(6) → Seq(6, 6, 6)) - TestConfig.RandomTestRange foreach (_ ⇒ runScript(script, settings)(_.statefulMapConcat(() ⇒ { + Seq(2) -> Seq(), + Seq(1) -> Seq(1, 1), + Seq(3) -> Seq(3), + Seq(6) -> Seq(6, 6, 6)) + TestConfig.RandomTestRange foreach (_ => runScript(script, settings)(_.statefulMapConcat(() => { var prev: Option[Int] = None - x ⇒ prev match { - case Some(e) ⇒ + x => prev match { + case Some(e) => prev = Some(x) - (1 to e) map (_ ⇒ x) - case None ⇒ + (1 to e) map (_ => x) + case None => prev = Some(x) List.empty[Int] } @@ -38,15 +38,15 @@ class FlowStatefulMapConcatSpec extends StreamSpec with ScriptedTest { } "be able to restart" in { - Source(List(2, 1, 3, 4, 1)).statefulMapConcat(() ⇒ { + Source(List(2, 1, 3, 4, 1)).statefulMapConcat(() => { var prev: Option[Int] = None - x ⇒ { + x => { if (x % 3 == 0) throw ex prev match { - case Some(e) ⇒ + case Some(e) => prev = Some(x) - (1 to e) map (_ ⇒ x) - case None ⇒ + (1 to e) map (_ => x) + case None => prev = Some(x) List.empty[Int] } @@ -59,15 +59,15 @@ class FlowStatefulMapConcatSpec extends StreamSpec with ScriptedTest { } "be able to resume" in { - Source(List(2, 1, 3, 4, 1)).statefulMapConcat(() ⇒ { + Source(List(2, 1, 3, 4, 1)).statefulMapConcat(() => { var prev: Option[Int] = None - x ⇒ { + x => { if (x % 3 == 0) throw ex prev match { - case Some(e) ⇒ + case Some(e) => prev = Some(x) - (1 to e) map (_ ⇒ x) - case None ⇒ + (1 to e) map (_ => x) + case None => prev = Some(x) List.empty[Int] } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSupervisionSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSupervisionSpec.scala index 222d04e376..4582b62bd5 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSupervisionSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowSupervisionSpec.scala @@ -22,7 +22,7 @@ class FlowSupervisionSpec extends StreamSpec { val exc = new RuntimeException("simulated exc") with NoStackTrace - val failingMap = Flow[Int].map(n ⇒ if (n == 3) throw exc else n) + val failingMap = Flow[Int].map(n => if (n == 3) throw exc else n) def run(f: Flow[Int, Int, NotUsed]): immutable.Seq[Int] = Await.result(Source((1 to 5).toSeq ++ (1 to 5)).via(f).limit(1000).runWith(Sink.seq), 3.seconds) @@ -47,12 +47,12 @@ class FlowSupervisionSpec extends StreamSpec { "complete stream with NPE failure when null is emitted" in { intercept[NullPointerException] { - Await.result(Source(List("a", "b")).map(_ ⇒ null).limit(1000).runWith(Sink.seq), 3.seconds) + Await.result(Source(List("a", "b")).map(_ => null).limit(1000).runWith(Sink.seq), 3.seconds) }.getMessage should be(ReactiveStreamsCompliance.ElementMustNotBeNullMsg) } "resume stream when null is emitted" in { - val nullMap = Flow[String].map(elem ⇒ if (elem == "b") null else elem) + val nullMap = Flow[String].map(elem => if (elem == "b") null else elem) .withAttributes(supervisionStrategy(Supervision.resumingDecider)) val result = Await.result(Source(List("a", "b", "c")).via(nullMap) .limit(1000).runWith(Sink.seq), 3.seconds) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeSpec.scala index bf24ddb6dd..4c573d7086 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeSpec.scala @@ -6,7 +6,7 @@ package akka.stream.scaladsl import scala.concurrent.Await import scala.concurrent.duration._ -import java.util.concurrent.ThreadLocalRandom.{ current ⇒ random } +import java.util.concurrent.ThreadLocalRandom.{ current => random } import akka.stream.ActorMaterializer import akka.stream.ActorMaterializerSettings import akka.stream.actor.ActorSubscriberMessage.OnComplete @@ -26,8 +26,8 @@ class FlowTakeSpec extends StreamSpec with ScriptedTest { "A Take" must { "take" in { - def script(d: Int) = Script(TestConfig.RandomTestRange map { n ⇒ Seq(n) → (if (n > d) Nil else Seq(n)) }: _*) - TestConfig.RandomTestRange foreach { _ ⇒ + def script(d: Int) = Script(TestConfig.RandomTestRange map { n => Seq(n) -> (if (n > d) Nil else Seq(n)) }: _*) + TestConfig.RandomTestRange foreach { _ => val d = Math.min(Math.max(random.nextInt(-10, 60), 0), 50) runScript(script(d), settings)(_.take(d)) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeWhileSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeWhileSpec.scala index e1cef3e02d..bc6186703e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeWhileSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeWhileSpec.scala @@ -37,7 +37,7 @@ class FlowTakeWhileSpec extends StreamSpec { "continue if error" in assertAllStagesStopped { val testException = new Exception("test") with NoStackTrace - val p = Source(1 to 4).takeWhile(a ⇒ if (a == 3) throw testException else true).withAttributes(supervisionStrategy(resumingDecider)) + val p = Source(1 to 4).takeWhile(a => if (a == 3) throw testException else true).withAttributes(supervisionStrategy(resumingDecider)) .runWith(TestSink.probe[Int]) .request(4) .expectNext(1, 2, 4) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeWithinSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeWithinSpec.scala index 490c79dab7..066db00abe 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeWithinSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowTakeWithinSpec.scala @@ -24,16 +24,16 @@ class FlowTakeWithinSpec extends StreamSpec { val cSub = c.expectSubscription() cSub.request(100) val demand1 = pSub.expectRequest().toInt - (1 to demand1) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand1) foreach { _ => pSub.sendNext(input.next()) } val demand2 = pSub.expectRequest().toInt - (1 to demand2) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand2) foreach { _ => pSub.sendNext(input.next()) } val demand3 = pSub.expectRequest().toInt val sentN = demand1 + demand2 - (1 to sentN) foreach { n ⇒ c.expectNext(n) } + (1 to sentN) foreach { n => c.expectNext(n) } within(2.seconds) { c.expectComplete() } - (1 to demand3) foreach { _ ⇒ pSub.sendNext(input.next()) } + (1 to demand3) foreach { _ => pSub.sendNext(input.next()) } c.expectNoMsg(200.millis) } @@ -43,7 +43,7 @@ class FlowTakeWithinSpec extends StreamSpec { val cSub = c.expectSubscription() c.expectNoMsg(200.millis) cSub.request(100) - (1 to 3) foreach { n ⇒ c.expectNext(n) } + (1 to 3) foreach { n => c.expectNext(n) } c.expectComplete() c.expectNoMsg(200.millis) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowThrottleSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowThrottleSpec.scala index 2236ca09a9..893e98a9b8 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowThrottleSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowThrottleSpec.scala @@ -135,7 +135,7 @@ class FlowThrottleSpec extends StreamSpec { downstream.request(5) downstream.expectNoMsg(1200.millis) - for (i ← 7 to 11) upstream.sendNext(i) + for (i <- 7 to 11) upstream.sendNext(i) downstream.receiveWithin(300.millis, 5) should be(7 to 11) downstream.cancel() } @@ -156,7 +156,7 @@ class FlowThrottleSpec extends StreamSpec { downstream.expectNext(6) downstream.expectNoMsg(500.millis) //wait to receive 2 in burst afterwards downstream.request(5) - for (i ← 7 to 10) upstream.sendNext(i) + for (i <- 7 to 10) upstream.sendNext(i) downstream.receiveWithin(100.millis, 2) should be(Seq(7, 8)) downstream.cancel() } @@ -185,7 +185,7 @@ class FlowThrottleSpec extends StreamSpec { "Throttle for various cost elements" must { "work for happy case" in assertAllStagesStopped { - Source(1 to 5).throttle(1, 100.millis, 0, (_) ⇒ 1, Shaping) + Source(1 to 5).throttle(1, 100.millis, 0, (_) => 1, Shaping) .runWith(TestSink.probe[Int]) .request(5) .expectNext(1, 2, 3, 4, 5) @@ -230,7 +230,7 @@ class FlowThrottleSpec extends StreamSpec { } "send elements downstream as soon as time comes" in assertAllStagesStopped { - val probe = Source(1 to 10).throttle(4, 500.millis, 0, _ ⇒ 2, Shaping).runWith(TestSink.probe[Int]) + val probe = Source(1 to 10).throttle(4, 500.millis, 0, _ => 2, Shaping).runWith(TestSink.probe[Int]) .request(5) probe.receiveWithin(600.millis) should be(Seq(1, 2)) probe.expectNoMsg(100.millis) @@ -243,7 +243,7 @@ class FlowThrottleSpec extends StreamSpec { "burst according to its maximum if enough time passed" in assertAllStagesStopped { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - Source.fromPublisher(upstream).throttle(2, 400.millis, 5, (_) ⇒ 1, Shaping).runWith(Sink.fromSubscriber(downstream)) + Source.fromPublisher(upstream).throttle(2, 400.millis, 5, (_) => 1, Shaping).runWith(Sink.fromSubscriber(downstream)) // Exhaust bucket first downstream.request(5) @@ -256,7 +256,7 @@ class FlowThrottleSpec extends StreamSpec { downstream.expectNext(6) downstream.request(5) downstream.expectNoMsg(1200.millis) - for (i ← 7 to 11) upstream.sendNext(i) + for (i <- 7 to 11) upstream.sendNext(i) downstream.receiveWithin(300.millis, 5) should be(7 to 11) downstream.cancel() } @@ -264,7 +264,7 @@ class FlowThrottleSpec extends StreamSpec { "burst some elements if have enough time" in assertAllStagesStopped { val upstream = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[Int]() - Source.fromPublisher(upstream).throttle(2, 400.millis, 5, (e) ⇒ if (e < 9) 1 else 20, Shaping).runWith(Sink.fromSubscriber(downstream)) + Source.fromPublisher(upstream).throttle(2, 400.millis, 5, (e) => if (e < 9) 1 else 20, Shaping).runWith(Sink.fromSubscriber(downstream)) // Exhaust bucket first downstream.request(5) @@ -277,7 +277,7 @@ class FlowThrottleSpec extends StreamSpec { downstream.expectNext(6) downstream.expectNoMsg(500.millis) //wait to receive 2 in burst afterwards downstream.request(5) - for (i ← 7 to 9) upstream.sendNext(i) + for (i <- 7 to 9) upstream.sendNext(i) downstream.receiveWithin(200.millis, 2) should be(Seq(7, 8)) downstream.cancel() } @@ -305,7 +305,7 @@ class FlowThrottleSpec extends StreamSpec { "handle rate calculation function exception" in assertAllStagesStopped { val ex = new RuntimeException with NoStackTrace - Source(1 to 5).throttle(2, 200.millis, 0, (_) ⇒ { throw ex }, Shaping) + Source(1 to 5).throttle(2, 200.millis, 0, (_) => { throw ex }, Shaping) .throttle(1, 100.millis, 5, Enforcing) .runWith(TestSink.probe[Int]) .request(5) @@ -320,7 +320,7 @@ class FlowThrottleSpec extends StreamSpec { val expectedMaxRate = new AtomicInteger val (ref, done) = Source.actorRef[Int](bufferSize = 100000, OverflowStrategy.fail) .throttle(300, 1000.millis) - .toMat(Sink.foreach { elem ⇒ + .toMat(Sink.foreach { elem => val now = System.nanoTime() val n1 = counter1.incrementAndGet() val duration1Millis = (now - timestamp1.get) / 1000 / 1000 @@ -340,7 +340,7 @@ class FlowThrottleSpec extends StreamSpec { .run() expectedMaxRate.set(200) // sleep (at least) 5 ms between each element - (1 to 2700).foreach { n ⇒ + (1 to 2700).foreach { n => if (!done.isCompleted) { ref ! n val now = System.nanoTime() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWatchSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWatchSpec.scala index f366709cca..2a9c590261 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWatchSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWatchSpec.scala @@ -18,7 +18,7 @@ object FlowWatchSpec { class Replier extends Actor { override def receive: Receive = { - case msg: Int ⇒ sender() ! Reply(msg) + case msg: Int => sender() ! Reply(msg) } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWireTapSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWireTapSpec.scala index 90f17da57e..b9af41c36c 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWireTapSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWireTapSpec.scala @@ -20,12 +20,12 @@ class FlowWireTapSpec extends StreamSpec("akka.stream.materializer.debug.fuzzing "call the procedure for each element" in assertAllStagesStopped { Source(1 to 100).wireTap(testActor ! _).runWith(Sink.ignore).futureValue - 1 to 100 foreach { i ⇒ expectMsg(i) } + 1 to 100 foreach { i => expectMsg(i) } } "complete the future for an empty stream" in assertAllStagesStopped { Source.empty[String].wireTap(testActor ! _).runWith(Sink.ignore) foreach { - _ ⇒ testActor ! "done" + _ => testActor ! "done" } expectMsg("done") } @@ -33,7 +33,7 @@ class FlowWireTapSpec extends StreamSpec("akka.stream.materializer.debug.fuzzing "yield the first error" in assertAllStagesStopped { val p = TestPublisher.manualProbe[Int]() Source.fromPublisher(p).wireTap(testActor ! _).runWith(Sink.ignore).failed foreach { - ex ⇒ testActor ! ex + ex => testActor ! ex } val proc = p.expectSubscription() proc.expectRequest() @@ -44,7 +44,7 @@ class FlowWireTapSpec extends StreamSpec("akka.stream.materializer.debug.fuzzing "not cause subsequent stages to be failed if throws (same as wireTap(Sink))" in assertAllStagesStopped { val error = TE("Boom!") - val future = Source.single(1).wireTap(_ ⇒ throw error).runWith(Sink.ignore) + val future = Source.single(1).wireTap(_ => throw error).runWith(Sink.ignore) future.futureValue shouldEqual Done } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWithContextLogSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWithContextLogSpec.scala index 1184925a0f..854706c1ef 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWithContextLogSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWithContextLogSpec.scala @@ -34,7 +34,7 @@ class FlowWithContextLogSpec extends StreamSpec(""" "log each element" in { val logging = FlowWithContext[Message, Long].log("my-log") Source(List(Message("a", 1L), Message("b", 2L))) - .asSourceWithContext(m ⇒ m.offset) + .asSourceWithContext(m => m.offset) .via(logging) .asSource .runWith(Sink.ignore) @@ -45,9 +45,9 @@ class FlowWithContextLogSpec extends StreamSpec(""" } "allow extracting value to be logged" in { - val logging = FlowWithContext[Message, Long].log("my-log2", m ⇒ m.data) + val logging = FlowWithContext[Message, Long].log("my-log2", m => m.data) Source(List(Message("a", 1L))) - .asSourceWithContext(m ⇒ m.offset) + .asSourceWithContext(m => m.offset) .via(logging) .asSource .runWith(Sink.ignore) @@ -64,7 +64,7 @@ class FlowWithContextLogSpec extends StreamSpec(""" val logging = FlowWithContext[Message, Long].log("my-log3").withAttributes(disableElementLogging) Source(List(Message("a", 1L), Message("b", 2L))) - .asSourceWithContext(m ⇒ m.offset) + .asSourceWithContext(m => m.offset) .via(logging) .asSource .runWith(Sink.ignore) @@ -78,7 +78,7 @@ class FlowWithContextLogSpec extends StreamSpec(""" "log each element" in { Source(List(Message("a", 1L), Message("b", 2L))) - .asSourceWithContext(m ⇒ m.offset) + .asSourceWithContext(m => m.offset) .log("my-log4") .asSource .runWith(Sink.ignore) @@ -90,8 +90,8 @@ class FlowWithContextLogSpec extends StreamSpec(""" "allow extracting value to be logged" in { Source(List(Message("a", 1L))) - .asSourceWithContext(m ⇒ m.offset) - .log("my-log5", m ⇒ m.data) + .asSourceWithContext(m => m.offset) + .log("my-log5", m => m.data) .asSource .runWith(Sink.ignore) @@ -106,7 +106,7 @@ class FlowWithContextLogSpec extends StreamSpec(""" onFailure = Logging.DebugLevel) Source(List(Message("a", 1L), Message("b", 2L))) - .asSourceWithContext(m ⇒ m.offset) + .asSourceWithContext(m => m.offset) .log("my-log6") .withAttributes(disableElementLogging) .asSource diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWithContextSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWithContextSpec.scala index 9b7e8fe784..368a44d398 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWithContextSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowWithContextSpec.scala @@ -16,8 +16,8 @@ class FlowWithContextSpec extends StreamSpec { "A FlowWithContext" must { "get created from Flow.asFlowWithContext" in { - val flow = Flow[Message].map { case m ⇒ m.copy(data = m.data + "z") } - val flowWithContext = flow.asFlowWithContext((m: Message, o: Long) ⇒ Message(m.data, o)) { m ⇒ m.offset } + val flow = Flow[Message].map { case m => m.copy(data = m.data + "z") } + val flowWithContext = flow.asFlowWithContext((m: Message, o: Long) => Message(m.data, o)) { m => m.offset } val msg = Message("a", 1L) Source(Vector(msg)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowZipWithSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowZipWithSpec.scala index ce28c39160..da0ce10359 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowZipWithSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FlowZipWithSpec.scala @@ -58,7 +58,7 @@ class FlowZipWithSpec extends BaseTwoStreamsSetup { subscription.request(2) } probe.expectError() match { - case a: java.lang.ArithmeticException ⇒ a.getMessage should be("/ by zero") + case a: java.lang.ArithmeticException => a.getMessage should be("/ by zero") } probe.expectNoMsg(200.millis) } @@ -103,7 +103,7 @@ class FlowZipWithSpec extends BaseTwoStreamsSetup { val sourceFruits = Source(List("apple", "orange", "banana")) sourceCount.zipWith(sourceFruits) { - (countStr, fruitName) ⇒ + (countStr, fruitName) => s"$countStr $fruitName" }.runWith(Sink.foreach(println)) // this will print 'one apple', 'two orange', 'three banana' diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FramingSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FramingSpec.scala index ed2ea290ba..e885ffe9b4 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FramingSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FramingSpec.scala @@ -85,11 +85,11 @@ class FramingSpec extends StreamSpec { .named("lineFraming") def completeTestSequences(delimiter: ByteString): immutable.Iterable[ByteString] = - for (prefix ← delimiter.indices; s ← baseTestSequences) + for (prefix <- delimiter.indices; s <- baseTestSequences) yield delimiter.take(prefix) ++ s "work with various delimiters and test sequences" in { - for (delimiter ← delimiterBytes; _ ← 1 to 5) { + for (delimiter <- delimiterBytes; _ <- 1 to 5) { val testSequence = completeTestSequences(delimiter) val f = Source(testSequence) .map(_ ++ delimiter) @@ -167,8 +167,8 @@ class FramingSpec extends StreamSpec { val header = { val h = (new ByteStringBuilder).putInt(payload.size)(byteOrder).result() byteOrder match { - case ByteOrder.LITTLE_ENDIAN ⇒ h.take(fieldLength) - case ByteOrder.BIG_ENDIAN ⇒ h.drop(4 - fieldLength) + case ByteOrder.LITTLE_ENDIAN => h.take(fieldLength) + case ByteOrder.BIG_ENDIAN => h.drop(4 - fieldLength) } } offset ++ header ++ payload ++ tail @@ -176,12 +176,12 @@ class FramingSpec extends StreamSpec { "work with various byte orders, frame lengths and offsets" taggedAs LongRunningTest in { for { - byteOrder ← byteOrders - fieldOffset ← fieldOffsets - fieldLength ← fieldLengths + byteOrder <- byteOrders + fieldOffset <- fieldOffsets + fieldLength <- fieldLengths } { - val encodedFrames = frameLengths.filter(_ < (1L << (fieldLength * 8))).map { length ⇒ + val encodedFrames = frameLengths.filter(_ < (1L << (fieldLength * 8))).map { length => val payload = referenceChunk.take(length) encode(payload, fieldOffset, fieldLength, byteOrder) } @@ -198,9 +198,9 @@ class FramingSpec extends StreamSpec { "work with various byte orders, frame lengths and offsets using computeFrameSize" taggedAs LongRunningTest in { for { - byteOrder ← byteOrders - fieldOffset ← fieldOffsets - fieldLength ← fieldLengths + byteOrder <- byteOrders + fieldOffset <- fieldOffsets + fieldLength <- fieldLengths } { def computeFrameSize(offset: Array[Byte], length: Int): Int = { @@ -214,7 +214,7 @@ class FramingSpec extends StreamSpec { arr } - val encodedFrames = frameLengths.filter(_ < (1L << (fieldLength * 8))).map { length ⇒ + val encodedFrames = frameLengths.filter(_ < (1L << (fieldLength * 8))).map { length => val payload = referenceChunk.take(length) val offsetBytes = offset() val tailBytes = if (offsetBytes.length > 0) new Array[Byte](offsetBytes(0)) else Array.empty[Byte] @@ -241,8 +241,8 @@ class FramingSpec extends StreamSpec { val groupSize = 5 val single = encode(referenceChunk.take(100), 0, 1, ByteOrder.BIG_ENDIAN) val groupedFrames = (1 to groupSize) - .map(_ ⇒ single) - .fold(ByteString.empty)((result, bs) ⇒ result ++ bs) + .map(_ => single) + .fold(ByteString.empty)((result, bs) => result ++ bs) val publisher = TestPublisher.probe[ByteString]() val substriber = TestSubscriber.manualProbe[ByteString]() @@ -256,7 +256,7 @@ class FramingSpec extends StreamSpec { publisher.sendNext(groupedFrames) publisher.sendComplete() - for (_ ← 1 to groupSize) { + for (_ <- 1 to groupSize) { subscription.request(1) substriber.expectNext(single) } @@ -278,11 +278,11 @@ class FramingSpec extends StreamSpec { "report truncated frames" taggedAs LongRunningTest in { for { - //_ ← 1 to 10 - byteOrder ← byteOrders - fieldOffset ← fieldOffsets - fieldLength ← fieldLengths - frameLength ← frameLengths if frameLength < (1 << (fieldLength * 8)) && (frameLength != 0) + //_ <- 1 to 10 + byteOrder <- byteOrders + fieldOffset <- fieldOffsets + fieldLength <- fieldLengths + frameLength <- frameLengths if frameLength < (1 << (fieldLength * 8)) && (frameLength != 0) } { val fullFrame = encode(referenceChunk.take(frameLength), fieldOffset, fieldLength, byteOrder) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FutureFlattenSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FutureFlattenSourceSpec.scala index 8eabc1b4f2..4f93671882 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FutureFlattenSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/FutureFlattenSourceSpec.scala @@ -23,7 +23,7 @@ class FutureFlattenSourceSpec extends StreamSpec { "Future source" must { val underlying: Source[Int, String] = - Source(List(1, 2, 3)).mapMaterializedValue(_ ⇒ "foo") + Source(List(1, 2, 3)).mapMaterializedValue(_ => "foo") "emit the elements of the already successful future source" in assertAllStagesStopped { val (sourceMatVal, sinkMatVal) = @@ -117,7 +117,7 @@ class FutureFlattenSourceSpec extends StreamSpec { val materializationLatch = TestLatch(1) val (sourceMatVal, sinkMatVal) = Source.fromFutureSource(sourcePromise.future) - .mapMaterializedValue { value ⇒ + .mapMaterializedValue { value => materializationLatch.countDown() value } @@ -160,7 +160,7 @@ class FutureFlattenSourceSpec extends StreamSpec { subscriber.ensureSubscription() - sourcePromise.success(Source.fromPublisher(publisher).mapMaterializedValue(_ ⇒ "woho")) + sourcePromise.success(Source.fromPublisher(publisher).mapMaterializedValue(_ => "woho")) // materialized value completes but still no demand matVal.futureValue should ===("woho") @@ -187,7 +187,7 @@ class FutureFlattenSourceSpec extends StreamSpec { subscriber.ensureSubscription() - sourcePromise.success(Source.fromPublisher(publisher).mapMaterializedValue(_ ⇒ "woho")) + sourcePromise.success(Source.fromPublisher(publisher).mapMaterializedValue(_ => "woho")) // materialized value completes but still no demand matVal.futureValue should ===("woho") diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBackedFlowSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBackedFlowSpec.scala index afbdf488ab..991804616c 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBackedFlowSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBackedFlowSpec.scala @@ -13,7 +13,7 @@ import org.reactivestreams.Subscriber object GraphFlowSpec { val source1 = Source(0 to 3) - val partialGraph = GraphDSL.create() { implicit b ⇒ + val partialGraph = GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val source2 = Source(4 to 9) val source3 = Source.empty[Int] @@ -24,7 +24,7 @@ object GraphFlowSpec { val m2 = b.add(Merge[Int](2)) inMerge.out.map(_ * 2) ~> m2.in(0) - m2.out.map(_ / 2).map(i ⇒ (i + 1).toString) ~> outMerge.in(0) + m2.out.map(_ / 2).map(i => (i + 1).toString) ~> outMerge.in(0) source2 ~> inMerge.in(0) source3 ~> m2.in(1) @@ -48,7 +48,7 @@ class GraphFlowSpec extends StreamSpec { def validateProbe(probe: TestSubscriber.ManualProbe[Int], requests: Int, result: Set[Int]): Unit = { val subscription = probe.expectSubscription() - val collected = (1 to requests).map { _ ⇒ + val collected = (1 to requests).map { _ => subscription.request(1) probe.expectNext() }.toSet @@ -63,7 +63,7 @@ class GraphFlowSpec extends StreamSpec { "work with a Source and Sink" in { val probe = TestSubscriber.manualProbe[Int]() - val flow = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ + val flow = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => import GraphDSL.Implicits._ FlowShape(partial.in, partial.out.map(_.toInt).outlet) }) @@ -76,7 +76,7 @@ class GraphFlowSpec extends StreamSpec { "be transformable with a Pipe" in { val probe = TestSubscriber.manualProbe[Int]() - val flow = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ FlowShape(partial.in, partial.out) + val flow = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => FlowShape(partial.in, partial.out) }) source1.via(flow).map(_.toInt).to(Sink.fromSubscriber(probe)).run() @@ -87,11 +87,11 @@ class GraphFlowSpec extends StreamSpec { "work with another GraphFlow" in { val probe = TestSubscriber.manualProbe[Int]() - val flow1 = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ + val flow1 = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => FlowShape(partial.in, partial.out) }) - val flow2 = Flow.fromGraph(GraphDSL.create(Flow[String].map(_.toInt)) { implicit b ⇒ importFlow ⇒ + val flow2 = Flow.fromGraph(GraphDSL.create(Flow[String].map(_.toInt)) { implicit b => importFlow => FlowShape(importFlow.in, importFlow.out) }) @@ -103,10 +103,10 @@ class GraphFlowSpec extends StreamSpec { "be reusable multiple times" in { val probe = TestSubscriber.manualProbe[Int]() - val flow = Flow.fromGraph(GraphDSL.create(Flow[Int].map(_ * 2)) { implicit b ⇒ importFlow ⇒ FlowShape(importFlow.in, importFlow.out) + val flow = Flow.fromGraph(GraphDSL.create(Flow[Int].map(_ * 2)) { implicit b => importFlow => FlowShape(importFlow.in, importFlow.out) }) - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ Source(1 to 5) ~> flow ~> flow ~> Sink.fromSubscriber(probe) ClosedShape @@ -120,7 +120,7 @@ class GraphFlowSpec extends StreamSpec { "work with a Sink" in { val probe = TestSubscriber.manualProbe[Int]() - val source = Source.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ + val source = Source.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => import GraphDSL.Implicits._ source1 ~> partial.in SourceShape(partial.out.map(_.toInt).outlet) @@ -144,7 +144,7 @@ class GraphFlowSpec extends StreamSpec { val probe = TestSubscriber.manualProbe[Int]() - val source = Source.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ + val source = Source.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => import GraphDSL.Implicits._ source1 ~> partial.in SourceShape(partial.out) @@ -158,13 +158,13 @@ class GraphFlowSpec extends StreamSpec { "work with an GraphFlow" in { val probe = TestSubscriber.manualProbe[Int]() - val source = Source.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ + val source = Source.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => import GraphDSL.Implicits._ source1 ~> partial.in SourceShape(partial.out) }) - val flow = Flow.fromGraph(GraphDSL.create(Flow[String].map(_.toInt)) { implicit b ⇒ importFlow ⇒ + val flow = Flow.fromGraph(GraphDSL.create(Flow[String].map(_.toInt)) { implicit b => importFlow => FlowShape(importFlow.in, importFlow.out) }) @@ -176,12 +176,12 @@ class GraphFlowSpec extends StreamSpec { "be reusable multiple times" in { val probe = TestSubscriber.manualProbe[Int]() - val source = Source.fromGraph(GraphDSL.create(Source(1 to 5)) { implicit b ⇒ s ⇒ + val source = Source.fromGraph(GraphDSL.create(Source(1 to 5)) { implicit b => s => import GraphDSL.Implicits._ SourceShape(s.out.map(_ * 2).outlet) }) - RunnableGraph.fromGraph(GraphDSL.create(source, source)(Keep.both) { implicit b ⇒ (s1, s2) ⇒ + RunnableGraph.fromGraph(GraphDSL.create(source, source)(Keep.both) { implicit b => (s1, s2) => import GraphDSL.Implicits._ val merge = b.add(Merge[Int](2)) s1.out ~> merge.in(0) @@ -198,7 +198,7 @@ class GraphFlowSpec extends StreamSpec { "work with a Source" in { val probe = TestSubscriber.manualProbe[Int]() - val sink = Sink.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ + val sink = Sink.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => import GraphDSL.Implicits._ partial.out.map(_.toInt) ~> Sink.fromSubscriber(probe) SinkShape(partial.in) @@ -213,7 +213,7 @@ class GraphFlowSpec extends StreamSpec { val probe = TestSubscriber.manualProbe[Int]() val pubSink = Sink.asPublisher[Int](false) - val sink = Sink.fromGraph(GraphDSL.create(pubSink) { implicit b ⇒ p ⇒ SinkShape(p.in) + val sink = Sink.fromGraph(GraphDSL.create(pubSink) { implicit b => p => SinkShape(p.in) }) val mm = source1.runWith(sink) @@ -225,7 +225,7 @@ class GraphFlowSpec extends StreamSpec { "be transformable with a Pipe" in { val probe = TestSubscriber.manualProbe[Int]() - val sink = Sink.fromGraph(GraphDSL.create(partialGraph, Flow[String].map(_.toInt))(Keep.both) { implicit b ⇒ (partial, flow) ⇒ + val sink = Sink.fromGraph(GraphDSL.create(partialGraph, Flow[String].map(_.toInt))(Keep.both) { implicit b => (partial, flow) => import GraphDSL.Implicits._ flow.out ~> partial.in partial.out.map(_.toInt) ~> Sink.fromSubscriber(probe) @@ -242,11 +242,11 @@ class GraphFlowSpec extends StreamSpec { val probe = TestSubscriber.manualProbe[Int]() - val flow = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ + val flow = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => FlowShape(partial.in, partial.out) }) - val sink = Sink.fromGraph(GraphDSL.create(Flow[String].map(_.toInt)) { implicit b ⇒ flow ⇒ + val sink = Sink.fromGraph(GraphDSL.create(Flow[String].map(_.toInt)) { implicit b => flow => import GraphDSL.Implicits._ flow.out ~> Sink.fromSubscriber(probe) SinkShape(flow.in) @@ -264,24 +264,24 @@ class GraphFlowSpec extends StreamSpec { val inSource = Source.asSubscriber[Int] val outSink = Sink.asPublisher[Int](false) - val flow = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b ⇒ partial ⇒ + val flow = Flow.fromGraph(GraphDSL.create(partialGraph) { implicit b => partial => import GraphDSL.Implicits._ FlowShape(partial.in, partial.out.map(_.toInt).outlet) }) - val source = Source.fromGraph(GraphDSL.create(Flow[Int].map(_.toString), inSource)(Keep.right) { implicit b ⇒ (flow, src) ⇒ + val source = Source.fromGraph(GraphDSL.create(Flow[Int].map(_.toString), inSource)(Keep.right) { implicit b => (flow, src) => import GraphDSL.Implicits._ src.out ~> flow.in SourceShape(flow.out) }) - val sink = Sink.fromGraph(GraphDSL.create(Flow[String].map(_.toInt), outSink)(Keep.right) { implicit b ⇒ (flow, snk) ⇒ + val sink = Sink.fromGraph(GraphDSL.create(Flow[String].map(_.toInt), outSink)(Keep.right) { implicit b => (flow, snk) => import GraphDSL.Implicits._ flow.out ~> snk.in SinkShape(flow.in) }) - val (m1, m2, m3) = RunnableGraph.fromGraph(GraphDSL.create(source, flow, sink)(Tuple3.apply) { implicit b ⇒ (src, f, snk) ⇒ + val (m1, m2, m3) = RunnableGraph.fromGraph(GraphDSL.create(source, flow, sink)(Tuple3.apply) { implicit b => (src, f, snk) => import GraphDSL.Implicits._ src.out.map(_.toInt) ~> f.in f.out.map(_.toString) ~> snk.in @@ -301,15 +301,15 @@ class GraphFlowSpec extends StreamSpec { val inSource = Source.asSubscriber[Int] val outSink = Sink.asPublisher[Int](false) - val source = Source.fromGraph(GraphDSL.create(inSource) { implicit b ⇒ src ⇒ + val source = Source.fromGraph(GraphDSL.create(inSource) { implicit b => src => SourceShape(src.out) }) - val sink = Sink.fromGraph(GraphDSL.create(outSink) { implicit b ⇒ snk ⇒ + val sink = Sink.fromGraph(GraphDSL.create(outSink) { implicit b => snk => SinkShape(snk.in) }) - val (m1, m2) = RunnableGraph.fromGraph(GraphDSL.create(source, sink)(Keep.both) { implicit b ⇒ (src, snk) ⇒ + val (m1, m2) = RunnableGraph.fromGraph(GraphDSL.create(source, sink)(Keep.both) { implicit b => (src, snk) => import GraphDSL.Implicits._ src.out ~> snk.in ClosedShape diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBalanceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBalanceSpec.scala index b248a896ac..3a7e5759e9 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBalanceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBalanceSpec.scala @@ -26,7 +26,7 @@ class GraphBalanceSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(Balance[Int](2)) Source(List(1, 2, 3)) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(c1) @@ -50,7 +50,7 @@ class GraphBalanceSpec extends StreamSpec { "support waiting for demand from all downstream subscriptions" in { val s1 = TestSubscriber.manualProbe[Int]() - val p2 = RunnableGraph.fromGraph(GraphDSL.create(Sink.asPublisher[Int](false)) { implicit b ⇒ p2Sink ⇒ + val p2 = RunnableGraph.fromGraph(GraphDSL.create(Sink.asPublisher[Int](false)) { implicit b => p2Sink => val balance = b.add(Balance[Int](2, waitForAllDownstreams = true)) Source(List(1, 2, 3)) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(s1) @@ -80,7 +80,7 @@ class GraphBalanceSpec extends StreamSpec { "support waiting for demand from all non-cancelled downstream subscriptions" in assertAllStagesStopped { val s1 = TestSubscriber.manualProbe[Int]() - val (p2, p3) = RunnableGraph.fromGraph(GraphDSL.create(Sink.asPublisher[Int](false), Sink.asPublisher[Int](false))(Keep.both) { implicit b ⇒ (p2Sink, p3Sink) ⇒ + val (p2, p3) = RunnableGraph.fromGraph(GraphDSL.create(Sink.asPublisher[Int](false), Sink.asPublisher[Int](false))(Keep.both) { implicit b => (p2Sink, p3Sink) => val balance = b.add(Balance[Int](3, waitForAllDownstreams = true)) Source(List(1, 2, 3)) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(s1) @@ -112,7 +112,7 @@ class GraphBalanceSpec extends StreamSpec { } "work with one-way merge" in { - val result = Source.fromGraph(GraphDSL.create() { implicit b ⇒ + val result = Source.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(Balance[Int](1)) val source = b.add(Source(1 to 3)) @@ -126,7 +126,7 @@ class GraphBalanceSpec extends StreamSpec { "work with 5-way balance" in { val sink = Sink.head[Seq[Int]] - val (s1, s2, s3, s4, s5) = RunnableGraph.fromGraph(GraphDSL.create(sink, sink, sink, sink, sink)(Tuple5.apply) { implicit b ⇒ (f1, f2, f3, f4, f5) ⇒ + val (s1, s2, s3, s4, s5) = RunnableGraph.fromGraph(GraphDSL.create(sink, sink, sink, sink, sink)(Tuple5.apply) { implicit b => (f1, f2, f3, f4, f5) => val balance = b.add(Balance[Int](5, waitForAllDownstreams = true)) Source(0 to 14) ~> balance.in balance.out(0).grouped(15) ~> f1 @@ -144,7 +144,7 @@ class GraphBalanceSpec extends StreamSpec { val numElementsForSink = 10000 val outputs = Sink.fold[Int, Int](0)(_ + _) - val results = RunnableGraph.fromGraph(GraphDSL.create(outputs, outputs, outputs)(List(_, _, _)) { implicit b ⇒ (o1, o2, o3) ⇒ + val results = RunnableGraph.fromGraph(GraphDSL.create(outputs, outputs, outputs)(List(_, _, _)) { implicit b => (o1, o2, o3) => val balance = b.add(Balance[Int](3, waitForAllDownstreams = true)) Source.repeat(1).take(numElementsForSink * 3) ~> balance.in balance.out(0) ~> o1 @@ -154,7 +154,7 @@ class GraphBalanceSpec extends StreamSpec { }).run() import system.dispatcher - val sum = Future.sequence(results).map { res ⇒ + val sum = Future.sequence(results).map { res => res should not contain 0 res.sum } @@ -163,7 +163,7 @@ class GraphBalanceSpec extends StreamSpec { "fairly balance between three outputs" in { val probe = TestSink.probe[Int] - val (p1, p2, p3) = RunnableGraph.fromGraph(GraphDSL.create(probe, probe, probe)(Tuple3.apply) { implicit b ⇒ (o1, o2, o3) ⇒ + val (p1, p2, p3) = RunnableGraph.fromGraph(GraphDSL.create(probe, probe, probe)(Tuple3.apply) { implicit b => (o1, o2, o3) => val balance = b.add(Balance[Int](3)) Source(1 to 7) ~> balance.in balance.out(0) ~> o1 @@ -189,7 +189,7 @@ class GraphBalanceSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(Balance[Int](2)) Source(List(1, 2, 3)) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(c1) @@ -211,7 +211,7 @@ class GraphBalanceSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(Balance[Int](2)) Source(List(1, 2, 3)) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(c1) @@ -234,7 +234,7 @@ class GraphBalanceSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(Balance[Int](2)) Source.fromPublisher(p1.getPublisher) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(c1) @@ -265,7 +265,7 @@ class GraphBalanceSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(new Balance[Int](2, waitForAllDownstreams = false, eagerCancel = true)) Source.fromPublisher(p1.getPublisher) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(c1) @@ -296,7 +296,7 @@ class GraphBalanceSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(Balance[Int](2)) Source.fromPublisher(p1.getPublisher) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(c1) @@ -328,7 +328,7 @@ class GraphBalanceSpec extends StreamSpec { val c2 = TestSubscriber.manualProbe[Int]() val c3 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(Balance[Int](3)) Source.fromPublisher(p1.getPublisher) ~> balance.in balance.out(0) ~> Sink.fromSubscriber(c1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBroadcastSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBroadcastSpec.scala index 70c9a9ab08..9ebca31740 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBroadcastSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphBroadcastSpec.scala @@ -26,7 +26,7 @@ class GraphBroadcastSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[Int](2)) Source(List(1, 2, 3)) ~> bcast.in bcast.out(0) ~> Flow[Int].buffer(16, OverflowStrategy.backpressure) ~> Sink.fromSubscriber(c1) @@ -53,7 +53,7 @@ class GraphBroadcastSpec extends StreamSpec { } "work with one-way broadcast" in assertAllStagesStopped { - val result = Source.fromGraph(GraphDSL.create() { implicit b ⇒ + val result = Source.fromGraph(GraphDSL.create() { implicit b => val broadcast = b.add(Broadcast[Int](1)) val source = b.add(Source(1 to 3)) @@ -75,7 +75,7 @@ class GraphBroadcastSpec extends StreamSpec { headSink, headSink, headSink)( - (fut1, fut2, fut3, fut4, fut5) ⇒ Future.sequence(List(fut1, fut2, fut3, fut4, fut5))) { implicit b ⇒ (p1, p2, p3, p4, p5) ⇒ + (fut1, fut2, fut3, fut4, fut5) => Future.sequence(List(fut1, fut2, fut3, fut4, fut5))) { implicit b => (p1, p2, p3, p4, p5) => val bcast = b.add(Broadcast[Int](5)) Source(List(1, 2, 3)) ~> bcast.in bcast.out(0).grouped(5) ~> p1.in @@ -95,8 +95,8 @@ class GraphBroadcastSpec extends StreamSpec { val headSink: Sink[T, FT] = Sink.head[T] import system.dispatcher - val combine: (FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT) ⇒ Future[Seq[Seq[Int]]] = - (f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20, f21, f22) ⇒ + val combine: (FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT, FT) => Future[Seq[Seq[Int]]] = + (f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20, f21, f22) => Future.sequence(List(f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20, f21, f22)) val result = RunnableGraph.fromGraph(GraphDSL.create( @@ -104,7 +104,7 @@ class GraphBroadcastSpec extends StreamSpec { headSink, headSink, headSink, headSink, headSink, headSink, headSink, headSink, headSink, headSink, headSink, headSink, headSink, headSink, headSink, - headSink, headSink)(combine) { implicit b ⇒ (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22) ⇒ + headSink, headSink)(combine) { implicit b => (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22) => val bcast = b.add(Broadcast[Int](22)) Source(List(1, 2, 3)) ~> bcast.in bcast.out(0).grouped(5) ~> p1.in @@ -139,7 +139,7 @@ class GraphBroadcastSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[Int](2)) Source(List(1, 2, 3)) ~> bcast.in bcast.out(0) ~> Flow[Int] ~> Sink.fromSubscriber(c1) @@ -161,7 +161,7 @@ class GraphBroadcastSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[Int](2)) Source(List(1, 2, 3)) ~> bcast.in bcast.out(0) ~> Flow[Int].named("identity-a") ~> Sink.fromSubscriber(c1) @@ -184,7 +184,7 @@ class GraphBroadcastSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[Int](2)) Source.fromPublisher(p1.getPublisher) ~> bcast.in bcast.out(0) ~> Flow[Int] ~> Sink.fromSubscriber(c1) @@ -213,7 +213,7 @@ class GraphBroadcastSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[Int]() - val sink = Sink.fromGraph(GraphDSL.create() { implicit b ⇒ + val sink = Sink.fromGraph(GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[Int](2)) bcast.out(0) ~> Sink.fromSubscriber(c1) bcast.out(1) ~> Sink.fromSubscriber(c2) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphConcatSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphConcatSpec.scala index f4125ccbee..925d92a92e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphConcatSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphConcatSpec.scala @@ -29,7 +29,7 @@ class GraphConcatSpec extends TwoStreamsSetup { "work in the happy case" in assertAllStagesStopped { val probe = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val concat1 = b add Concat[Int]() val concat2 = b add Concat[Int]() @@ -46,7 +46,7 @@ class GraphConcatSpec extends TwoStreamsSetup { val subscription = probe.expectSubscription() - for (i ← 1 to 10) { + for (i <- 1 to 10) { subscription.request(1) probe.expectNext(i) } @@ -132,7 +132,7 @@ class GraphConcatSpec extends TwoStreamsSetup { val promise = Promise[Int]() val subscriber = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val concat = b add Concat[Int]() Source(List(1, 2, 3)) ~> concat.in(0) Source.fromFuture(promise.future) ~> concat.in(1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphDSLCompileSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphDSLCompileSpec.scala index ed6e8fa1a2..0ff148a4bf 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphDSLCompileSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphDSLCompileSpec.scala @@ -31,7 +31,7 @@ class GraphDSLCompileSpec extends StreamSpec { } - val apples = () ⇒ Iterator.continually(new Apple) + val apples = () => Iterator.continually(new Apple) val f1 = Flow[String].via(op[String, String]).named("f1") val f2 = Flow[String].via(op[String, String]).named("f2") @@ -48,7 +48,7 @@ class GraphDSLCompileSpec extends StreamSpec { "A Graph" should { import GraphDSL.Implicits._ "build simple merge" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(Merge[String](2)) in1 ~> f1 ~> merge.in(0) in2 ~> f2 ~> merge.in(1) @@ -58,7 +58,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "build simple broadcast" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[String](2)) in1 ~> f1 ~> bcast.in bcast.out(0) ~> f2 ~> out1 @@ -68,7 +68,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "build simple balance" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val balance = b.add(Balance[String](2)) in1 ~> f1 ~> balance.in balance.out(0) ~> f2 ~> out1 @@ -78,7 +78,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "build simple merge - broadcast" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(Merge[String](2)) val bcast = b.add(Broadcast[String](2)) in1 ~> f1 ~> merge.in(0) @@ -91,7 +91,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "build simple merge - broadcast with implicits" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val merge = b.add(Merge[String](2)) val bcast = b.add(Broadcast[String](2)) @@ -116,7 +116,7 @@ class GraphDSLCompileSpec extends StreamSpec { "detect cycle in " in { pending // FIXME needs cycle detection capability intercept[IllegalArgumentException] { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(Merge[String](2)) val bcast1 = b.add(Broadcast[String](2)) val bcast2 = b.add(Broadcast[String](2)) @@ -134,7 +134,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "express complex topologies in a readable way" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(Merge[String](2)) val bcast1 = b.add(Broadcast[String](2)) val bcast2 = b.add(Broadcast[String](2)) @@ -148,7 +148,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "build broadcast - merge" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[String](2)) val merge = b.add(Merge[String](2)) import GraphDSL.Implicits._ @@ -160,7 +160,7 @@ class GraphDSLCompileSpec extends StreamSpec { "build wikipedia Topological_sorting" in { // see https://en.wikipedia.org/wiki/Topological_sorting#mediaviewer/File:Directed_acyclic_graph.png - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val b3 = b.add(Broadcast[String](2)) val b7 = b.add(Broadcast[String](2)) val b11 = b.add(Broadcast[String](3)) @@ -189,7 +189,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "make it optional to specify flows" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(Merge[String](2)) val bcast = b.add(Broadcast[String](2)) import GraphDSL.Implicits._ @@ -201,12 +201,12 @@ class GraphDSLCompileSpec extends StreamSpec { } "build unzip - zip" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(Zip[Int, String]()) val unzip = b.add(Unzip[Int, String]()) val out = Sink.asPublisher[(Int, String)](false) import GraphDSL.Implicits._ - Source(List(1 → "a", 2 → "b", 3 → "c")) ~> unzip.in + Source(List(1 -> "a", 2 -> "b", 3 -> "c")) ~> unzip.in unzip.out0 ~> Flow[Int].map(_ * 2) ~> zip.in0 unzip.out1 ~> zip.in1 zip.out ~> out @@ -216,7 +216,7 @@ class GraphDSLCompileSpec extends StreamSpec { "throw an error if some ports are not connected" in { intercept[IllegalStateException] { - GraphDSL.create() { implicit b ⇒ + GraphDSL.create() { implicit b => val s = b.add(Source.empty[Int]) val op = b.add(Flow[Int].map(_ + 1)) val sink = b.add(Sink.foreach[Int](println)) @@ -232,7 +232,7 @@ class GraphDSLCompileSpec extends StreamSpec { "throw an error if a connected port is returned in the shape" in { intercept[IllegalStateException] { - GraphDSL.create() { implicit b ⇒ + GraphDSL.create() { implicit b => val s = b.add(Source.empty[Int]) val op = b.add(Flow[Int].map(_ + 1)) val sink = b.add(Sink.foreach[Int](println)) @@ -247,7 +247,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "build with variance" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val merge = b.add(Merge[Fruit](2)) Source.fromIterator[Fruit](apples) ~> Flow[Fruit] ~> merge.in(0) @@ -258,7 +258,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "build with variance when indices are not specified" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val fruitMerge = b.add(Merge[Fruit](2)) Source.fromIterator[Fruit](apples) ~> fruitMerge @@ -293,7 +293,7 @@ class GraphDSLCompileSpec extends StreamSpec { } "build with implicits and variance" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => def appleSource = b.add(Source.fromPublisher(TestPublisher.manualProbe[Apple]())) def fruitSource = b.add(Source.fromPublisher(TestPublisher.manualProbe[Fruit]())) val outA = b add Sink.fromSubscriber(TestSubscriber.manualProbe[Fruit]()) @@ -318,7 +318,7 @@ class GraphDSLCompileSpec extends StreamSpec { b.add(Source.fromIterator(apples)) ~> Flow[Apple] ~> b.add(Sink.asPublisher[Fruit](false)) appleSource ~> Flow[Apple] ~> merge.in(10) - Source(List(1 → "a", 2 → "b", 3 → "c")) ~> unzip.in + Source(List(1 -> "a", 2 -> "b", 3 -> "c")) ~> unzip.in unzip.out1 ~> whatever unzip.out0 ~> b.add(Sink.asPublisher[Any](false)) @@ -331,31 +331,31 @@ class GraphDSLCompileSpec extends StreamSpec { "build with plain flow without junctions" in { import GraphDSL.Implicits._ - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => in1 ~> f1 ~> out1 ClosedShape }).run() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => in1 ~> f1 ~> f2.to(out1) ClosedShape }).run() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => (in1 via f1) ~> f2 ~> out1 ClosedShape }).run() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => in1 ~> out1 ClosedShape }).run() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => in1 ~> (f1 to out1) ClosedShape }).run() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => (in1 via f1) ~> out1 ClosedShape }).run() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => (in1 via f1) ~> (f2 to out1) ClosedShape }).run() @@ -363,7 +363,7 @@ class GraphDSLCompileSpec extends StreamSpec { "suitably override attribute handling methods" in { import akka.stream.Attributes._ - val ga = GraphDSL.create() { implicit b ⇒ + val ga = GraphDSL.create() { implicit b => val id = b.add(GraphStages.identity[Any]) FlowShape(id.in, id.out) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMatValueSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMatValueSpec.scala index 7b9da59f98..b919e95e1c 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMatValueSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMatValueSpec.scala @@ -27,7 +27,7 @@ class GraphMatValueSpec extends StreamSpec { "expose the materialized value as source" in { val sub = TestSubscriber.manualProbe[Int]() - val f = RunnableGraph.fromGraph(GraphDSL.create(foldSink) { implicit b ⇒ fold ⇒ + val f = RunnableGraph.fromGraph(GraphDSL.create(foldSink) { implicit b => fold => Source(1 to 10) ~> fold b.materializedValue.mapAsync(4)(identity) ~> Sink.fromSubscriber(sub) ClosedShape @@ -43,7 +43,7 @@ class GraphMatValueSpec extends StreamSpec { "expose the materialized value as source multiple times" in { val sub = TestSubscriber.manualProbe[Int]() - val f = RunnableGraph.fromGraph(GraphDSL.create(foldSink) { implicit b ⇒ fold ⇒ + val f = RunnableGraph.fromGraph(GraphDSL.create(foldSink) { implicit b => fold => val zip = b.add(ZipWith[Int, Int, Int](_ + _)) Source(1 to 10) ~> fold b.materializedValue.mapAsync(4)(identity) ~> zip.in0 @@ -61,7 +61,7 @@ class GraphMatValueSpec extends StreamSpec { } // Exposes the materialized value as a stream value - val foldFeedbackSource: Source[Future[Int], Future[Int]] = Source.fromGraph(GraphDSL.create(foldSink) { implicit b ⇒ fold ⇒ + val foldFeedbackSource: Source[Future[Int], Future[Int]] = Source.fromGraph(GraphDSL.create(foldSink) { implicit b => fold => Source(1 to 10) ~> fold SourceShape(b.materializedValue) }) @@ -73,12 +73,12 @@ class GraphMatValueSpec extends StreamSpec { } "allow exposing the materialized value as port even if wrapped and the final materialized value is Unit" in { - val noMatSource: Source[Int, Unit] = foldFeedbackSource.mapAsync(4)(identity).map(_ + 100).mapMaterializedValue((_) ⇒ ()) + val noMatSource: Source[Int, Unit] = foldFeedbackSource.mapAsync(4)(identity).map(_ + 100).mapMaterializedValue((_) => ()) Await.result(noMatSource.runWith(Sink.head), 3.seconds) should ===(155) } "work properly with nesting and reusing" in { - val compositeSource1 = Source.fromGraph(GraphDSL.create(foldFeedbackSource, foldFeedbackSource)(Keep.both) { implicit b ⇒ (s1, s2) ⇒ + val compositeSource1 = Source.fromGraph(GraphDSL.create(foldFeedbackSource, foldFeedbackSource)(Keep.both) { implicit b => (s1, s2) => val zip = b.add(ZipWith[Int, Int, Int](_ + _)) s1.out.mapAsync(4)(identity) ~> zip.in0 @@ -86,7 +86,7 @@ class GraphMatValueSpec extends StreamSpec { SourceShape(zip.out) }) - val compositeSource2 = Source.fromGraph(GraphDSL.create(compositeSource1, compositeSource1)(Keep.both) { implicit b ⇒ (s1, s2) ⇒ + val compositeSource2 = Source.fromGraph(GraphDSL.create(compositeSource1, compositeSource1)(Keep.both) { implicit b => (s1, s2) => val zip = b.add(ZipWith[Int, Int, Int](_ + _)) s1.out ~> zip.in0 s2.out.map(_ * 10000) ~> zip.in1 @@ -104,7 +104,7 @@ class GraphMatValueSpec extends StreamSpec { } "work also when the source’s module is copied" in { - val foldFlow: Flow[Int, Int, Future[Int]] = Flow.fromGraph(GraphDSL.create(foldSink) { implicit builder ⇒ fold ⇒ + val foldFlow: Flow[Int, Int, Future[Int]] = Flow.fromGraph(GraphDSL.create(foldSink) { implicit builder => fold => FlowShape(fold.in, builder.materializedValue.mapAsync(4)(identity).outlet) }) @@ -112,7 +112,7 @@ class GraphMatValueSpec extends StreamSpec { } "work also when the source’s module is copied and the graph is extended before using the matValSrc" in { - val foldFlow: Flow[Int, Int, Future[Int]] = Flow.fromGraph(GraphDSL.create(foldSink) { implicit builder ⇒ fold ⇒ + val foldFlow: Flow[Int, Int, Future[Int]] = Flow.fromGraph(GraphDSL.create(foldSink) { implicit builder => fold => val map = builder.add(Flow[Future[Int]].mapAsync(4)(identity)) builder.materializedValue ~> map FlowShape(fold.in, map.outlet) @@ -123,12 +123,12 @@ class GraphMatValueSpec extends StreamSpec { "perform side-effecting transformations even when not used as source" in { var done = false - val g = GraphDSL.create() { implicit b ⇒ + val g = GraphDSL.create() { implicit b => import GraphDSL.Implicits._ - Source.empty.mapMaterializedValue(_ ⇒ done = true) ~> Sink.ignore + Source.empty.mapMaterializedValue(_ => done = true) ~> Sink.ignore ClosedShape } - val r = RunnableGraph.fromGraph(GraphDSL.create(Sink.ignore) { implicit b ⇒ (s) ⇒ + val r = RunnableGraph.fromGraph(GraphDSL.create(Sink.ignore) { implicit b => (s) => b.add(g) Source(1 to 10) ~> s ClosedShape @@ -138,7 +138,7 @@ class GraphMatValueSpec extends StreamSpec { } "produce NotUsed when not importing materialized value" in { - val source = Source.fromGraph(GraphDSL.create() { implicit b ⇒ + val source = Source.fromGraph(GraphDSL.create() { implicit b => SourceShape(b.materializedValue) }) source.runWith(Sink.seq).futureValue should ===(List(akka.NotUsed)) @@ -151,7 +151,7 @@ class GraphMatValueSpec extends StreamSpec { "produce NotUsed when starting from Flow.via with transformation" in { var done = false Source.empty.viaMat( - Flow[Int].via(Flow[Int].mapMaterializedValue(_ ⇒ done = true)))(Keep.right) + Flow[Int].via(Flow[Int].mapMaterializedValue(_ => done = true)))(Keep.right) .to(Sink.ignore).run() should ===(akka.NotUsed) done should ===(true) } @@ -162,7 +162,7 @@ class GraphMatValueSpec extends StreamSpec { // that the materialized value was that of the other module (which is inconsistent with Keep.left behavior). val sink = Sink.ignore - val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] ⇒ + val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] => import GraphDSL.Implicits._ val s = builder.add(sink) val src = builder.add(Source(1 to 3)) @@ -180,8 +180,8 @@ class GraphMatValueSpec extends StreamSpec { // EmptyModule.compose broke this by always returning the other module intact, which means // that the materialized value was that of the other module (which is inconsistent with Keep.left behavior). - val sink = Sink.ignore.mapMaterializedValue(_ ⇒ testActor ! "side effect!") - val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] ⇒ + val sink = Sink.ignore.mapMaterializedValue(_ => testActor ! "side effect!") + val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] => import GraphDSL.Implicits._ val s = builder.add(sink) val src = builder.add(Source(1 to 3)) @@ -200,7 +200,7 @@ class GraphMatValueSpec extends StreamSpec { "with Identity Flow optimization even if ports are wired in an arbitrary higher nesting level" in { val mat2 = ActorMaterializer(ActorMaterializerSettings(system)) - val subflow = GraphDSL.create() { implicit b ⇒ + val subflow = GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val zip = b.add(Zip[String, String]()) val bc = b.add(Broadcast[String](2)) @@ -258,9 +258,9 @@ class GraphMatValueSpec extends StreamSpec { "provide a new materialized value for each materialization" in { // coverage for #23577 val matGen = new AtomicInteger(0) - val source = Source.empty[Int].mapMaterializedValue(_ ⇒ matGen.incrementAndGet()) + val source = Source.empty[Int].mapMaterializedValue(_ => matGen.incrementAndGet()) - val graph = Source.fromGraph(GraphDSL.create(source) { implicit b ⇒ s ⇒ + val graph = Source.fromGraph(GraphDSL.create(source) { implicit b => s => import GraphDSL.Implicits._ val merge = b.add(Merge[Int](2)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeLatestSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeLatestSpec.scala index 105165c3ff..d7374518bf 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeLatestSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeLatestSpec.scala @@ -34,7 +34,7 @@ class GraphMergeLatestSpec extends TwoStreamsSetup { val up3 = TestSource.probe[Int] val probe = TestSubscriber.manualProbe[List[Int]]() - val (in1, in2, in3) = RunnableGraph.fromGraph(GraphDSL.create(up1, up2, up3)((_, _, _)) { implicit b ⇒ (s1, s2, s3) ⇒ + val (in1, in2, in3) = RunnableGraph.fromGraph(GraphDSL.create(up1, up2, up3)((_, _, _)) { implicit b => (s1, s2, s3) => val m = b.add(MergeLatest[Int](3)) s1 ~> m @@ -66,7 +66,7 @@ class GraphMergeLatestSpec extends TwoStreamsSetup { val up3 = TestSource.probe[Int] val probe = TestSubscriber.manualProbe[List[Int]]() - val (in1, in2, in3) = RunnableGraph.fromGraph(GraphDSL.create(up1, up2, up3)((_, _, _)) { implicit b ⇒ (s1, s2, s3) ⇒ + val (in1, in2, in3) = RunnableGraph.fromGraph(GraphDSL.create(up1, up2, up3)((_, _, _)) { implicit b => (s1, s2, s3) => val m = b.add(MergeLatest[Int](3)) s1 ~> m @@ -111,7 +111,7 @@ class GraphMergeLatestSpec extends TwoStreamsSetup { } "work with one-way merge" in { - val result = Source.fromGraph(GraphDSL.create() { implicit b ⇒ + val result = Source.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(MergeLatest[Int](1)) val source = b.add(Source(1 to 3)) @@ -127,7 +127,7 @@ class GraphMergeLatestSpec extends TwoStreamsSetup { val up2 = TestSource.probe[Int] val probe = TestSubscriber.manualProbe[List[Int]]() - val (in1, in2) = RunnableGraph.fromGraph(GraphDSL.create(up1, up2)((_, _)) { implicit b ⇒ (s1, s2) ⇒ + val (in1, in2) = RunnableGraph.fromGraph(GraphDSL.create(up1, up2)((_, _)) { implicit b => (s1, s2) => val m = b.add(MergeLatest[Int](2, true)) s1 ~> m diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergePreferredSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergePreferredSpec.scala index 150e49ac91..924f779044 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergePreferredSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergePreferredSpec.scala @@ -33,7 +33,7 @@ class GraphMergePreferredSpec extends TwoStreamsSetup { val preferred = Source(Stream.fill(numElements)(1)) val aux = Source(Stream.fill(numElements)(2)) - val result = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b ⇒ sink ⇒ + val result = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b => sink => val merge = b.add(MergePreferred[Int](3)) preferred ~> merge.preferred @@ -48,7 +48,7 @@ class GraphMergePreferredSpec extends TwoStreamsSetup { } "eventually pass through all elements without corrupting the ordering" in { - val result = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b ⇒ sink ⇒ + val result = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b => sink => val merge = b.add(MergePreferred[Int](3)) Source(1 to 100) ~> merge.preferred @@ -63,16 +63,16 @@ class GraphMergePreferredSpec extends TwoStreamsSetup { resultSeq.toSet should ===((1 to 400).toSet) //test ordering of elements coming from each of the flows resultSeq.filter(_ <= 100) should ===(1 to 100) - resultSeq.filter(e ⇒ e > 100 && e <= 200) should ===(101 to 200) - resultSeq.filter(e ⇒ e > 200 && e <= 300) should ===(201 to 300) - resultSeq.filter(e ⇒ e > 300 && e <= 400) should ===(301 to 400) + resultSeq.filter(e => e > 100 && e <= 200) should ===(101 to 200) + resultSeq.filter(e => e > 200 && e <= 300) should ===(201 to 300) + resultSeq.filter(e => e > 300 && e <= 400) should ===(301 to 400) } "disallow multiple preferred inputs" in { val s = Source(0 to 3) (the[IllegalArgumentException] thrownBy { - val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(MergePreferred[Int](1)) s ~> merge.preferred @@ -89,7 +89,7 @@ class GraphMergePreferredSpec extends TwoStreamsSetup { val s = Source(0 to 3) (the[IllegalArgumentException] thrownBy { - val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(MergePreferred[Int](1)) s ~> merge.preferred diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergePrioritizedSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergePrioritizedSpec.scala index fcf1ab17de..593572f85a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergePrioritizedSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergePrioritizedSpec.scala @@ -27,9 +27,9 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { commonTests() "stream data from all sources" in { - val source1 = Source.fromIterator(() ⇒ (1 to 3).iterator) - val source2 = Source.fromIterator(() ⇒ (4 to 6).iterator) - val source3 = Source.fromIterator(() ⇒ (7 to 9).iterator) + val source1 = Source.fromIterator(() => (1 to 3).iterator) + val source2 = Source.fromIterator(() => (4 to 6).iterator) + val source3 = Source.fromIterator(() => (7 to 9).iterator) val priorities = Seq(6, 3, 1) @@ -40,7 +40,7 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { val subscription = probe.expectSubscription() var collected = Seq.empty[Int] - for (_ ← 1 to 9) { + for (_ <- 1 to 9) { subscription.request(1) collected :+= probe.expectNext() } @@ -51,9 +51,9 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { "stream data with priority" in { val elementCount = 20000 - val source1 = Source.fromIterator(() ⇒ Iterator.continually(1).take(elementCount)) - val source2 = Source.fromIterator(() ⇒ Iterator.continually(2).take(elementCount)) - val source3 = Source.fromIterator(() ⇒ Iterator.continually(3).take(elementCount)) + val source1 = Source.fromIterator(() => Iterator.continually(1).take(elementCount)) + val source2 = Source.fromIterator(() => Iterator.continually(2).take(elementCount)) + val source3 = Source.fromIterator(() => Iterator.continually(3).take(elementCount)) val priorities = Seq(6, 3, 1) @@ -64,7 +64,7 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { val subscription = probe.expectSubscription() var collected = Seq.empty[Int] - for (_ ← 1 to elementCount) { + for (_ <- 1 to elementCount) { subscription.request(1) collected :+= probe.expectNext() } @@ -80,9 +80,9 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { "stream data when only one source produces" in { val elementCount = 10 - val source1 = Source.fromIterator(() ⇒ Iterator.continually(1).take(elementCount)) - val source2 = Source.fromIterator[Int](() ⇒ Iterator.empty) - val source3 = Source.fromIterator[Int](() ⇒ Iterator.empty) + val source1 = Source.fromIterator(() => Iterator.continually(1).take(elementCount)) + val source2 = Source.fromIterator[Int](() => Iterator.empty) + val source3 = Source.fromIterator[Int](() => Iterator.empty) val priorities = Seq(6, 3, 1) @@ -93,7 +93,7 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { val subscription = probe.expectSubscription() var collected = Seq.empty[Int] - for (_ ← 1 to elementCount) { + for (_ <- 1 to elementCount) { subscription.request(1) collected :+= probe.expectNext() } @@ -109,9 +109,9 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { "stream data with priority when only two sources produce" in { val elementCount = 20000 - val source1 = Source.fromIterator(() ⇒ Iterator.continually(1).take(elementCount)) - val source2 = Source.fromIterator(() ⇒ Iterator.continually(2).take(elementCount)) - val source3 = Source.fromIterator[Int](() ⇒ Iterator.empty) + val source1 = Source.fromIterator(() => Iterator.continually(1).take(elementCount)) + val source2 = Source.fromIterator(() => Iterator.continually(2).take(elementCount)) + val source3 = Source.fromIterator[Int](() => Iterator.empty) val priorities = Seq(6, 3, 1) @@ -122,7 +122,7 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { val subscription = probe.expectSubscription() var collected = Seq.empty[Int] - for (_ ← 1 to elementCount) { + for (_ <- 1 to elementCount) { subscription.request(1) collected :+= probe.expectNext() } @@ -137,7 +137,7 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { } private def threeSourceMerge[T](source1: Source[T, NotUsed], source2: Source[T, NotUsed], source3: Source[T, NotUsed], priorities: Seq[Int], probe: ManualProbe[T]) = { - RunnableGraph.fromGraph(GraphDSL.create(source1, source2, source3)((_, _, _)) { implicit b ⇒ (s1, s2, s3) ⇒ + RunnableGraph.fromGraph(GraphDSL.create(source1, source2, source3)((_, _, _)) { implicit b => (s1, s2, s3) => val merge = b.add(MergePrioritized[T](priorities)) // introduce a delay on the consuming side making it more likely that // the actual prioritization happens and elements does not just pass through diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeSortedSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeSortedSpec.scala index 02d111fe94..ad320fae38 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeSortedSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeSortedSpec.scala @@ -22,14 +22,14 @@ class GraphMergeSortedSpec extends TwoStreamsSetup with GeneratorDrivenPropertyC override def out: Outlet[Outputs] = merge.out } - implicit def noShrink[T] = Shrink[T](_ ⇒ Stream.empty) // do not shrink failures, it only destroys evidence + implicit def noShrink[T] = Shrink[T](_ => Stream.empty) // do not shrink failures, it only destroys evidence "MergeSorted" must { "work in the nominal case" in { val gen = Gen.listOf(Gen.oneOf(false, true)) - forAll(gen) { picks ⇒ + forAll(gen) { picks => val N = picks.size val (left, right) = picks.zipWithIndex.partition(_._1) Source(left.map(_._2)).mergeSorted(Source(right.map(_._2))) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeSpec.scala index c18ef4a97d..2a65958fe4 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphMergeSpec.scala @@ -35,7 +35,7 @@ class GraphMergeSpec extends TwoStreamsSetup { val source3 = Source(List[Int]()) val probe = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val m1 = b.add(Merge[Int](2)) val m2 = b.add(Merge[Int](2)) @@ -51,7 +51,7 @@ class GraphMergeSpec extends TwoStreamsSetup { val subscription = probe.expectSubscription() var collected = Seq.empty[Int] - for (_ ← 1 to 10) { + for (_ <- 1 to 10) { subscription.request(1) collected :+= probe.expectNext() } @@ -64,7 +64,7 @@ class GraphMergeSpec extends TwoStreamsSetup { } "work with one-way merge" in { - val result = Source.fromGraph(GraphDSL.create() { implicit b ⇒ + val result = Source.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(Merge[Int](1)) val source = b.add(Source(1 to 3)) @@ -85,7 +85,7 @@ class GraphMergeSpec extends TwoStreamsSetup { val probe = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val merge = b.add(Merge[Int](6)) source1 ~> merge.in(0) @@ -102,7 +102,7 @@ class GraphMergeSpec extends TwoStreamsSetup { val subscription = probe.expectSubscription() var collected = Set.empty[Int] - for (_ ← 1 to 5) { + for (_ <- 1 to 5) { subscription.request(1) collected += probe.expectNext() } @@ -171,7 +171,7 @@ class GraphMergeSpec extends TwoStreamsSetup { val src1 = Source.asSubscriber[Int] val src2 = Source.asSubscriber[Int] - val (graphSubscriber1, graphSubscriber2) = RunnableGraph.fromGraph(GraphDSL.create(src1, src2)((_, _)) { implicit b ⇒ (s1, s2) ⇒ + val (graphSubscriber1, graphSubscriber2) = RunnableGraph.fromGraph(GraphDSL.create(src1, src2)((_, _)) { implicit b => (s1, s2) => val merge = b.add(Merge[Int](2)) s1.out ~> merge.in(0) s2.out ~> merge.in(1) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphOpsIntegrationSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphOpsIntegrationSpec.scala index d9b985e2c5..2d7e4571ac 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphOpsIntegrationSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphOpsIntegrationSpec.scala @@ -26,7 +26,7 @@ object GraphOpsIntegrationSpec { } def apply[In, Out](pipeline: Flow[In, Out, _]): Graph[ShufflePorts[In, Out], NotUsed] = { - GraphDSL.create() { implicit b ⇒ + GraphDSL.create() { implicit b => val merge = b.add(Merge[In](2)) val balance = b.add(Balance[Out](2)) merge.out ~> pipeline ~> balance.in @@ -50,7 +50,7 @@ class GraphOpsIntegrationSpec extends StreamSpec { "GraphDSLs" must { "support broadcast - merge layouts" in { - val resultFuture = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b ⇒ (sink) ⇒ + val resultFuture = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b => (sink) => val bcast = b.add(Broadcast[Int](2)) val merge = b.add(Merge[Int](2)) @@ -66,13 +66,13 @@ class GraphOpsIntegrationSpec extends StreamSpec { "support balance - merge (parallelization) layouts" in { val elements = 0 to 10 - val out = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b ⇒ (sink) ⇒ + val out = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b => (sink) => val balance = b.add(Balance[Int](5)) val merge = b.add(Merge[Int](5)) Source(elements) ~> balance.in - for (i ← 0 until 5) balance.out(i) ~> merge.in(i) + for (i <- 0 until 5) balance.out(i) ~> merge.in(i) merge.out.grouped(elements.size * 2) ~> sink.in ClosedShape @@ -85,7 +85,7 @@ class GraphOpsIntegrationSpec extends StreamSpec { // see https://en.wikipedia.org/wiki/Topological_sorting#mediaviewer/File:Directed_acyclic_graph.png val seqSink = Sink.head[Seq[Int]] - val (resultFuture2, resultFuture9, resultFuture10) = RunnableGraph.fromGraph(GraphDSL.create(seqSink, seqSink, seqSink)(Tuple3.apply) { implicit b ⇒ (sink2, sink9, sink10) ⇒ + val (resultFuture2, resultFuture9, resultFuture10) = RunnableGraph.fromGraph(GraphDSL.create(seqSink, seqSink, seqSink)(Tuple3.apply) { implicit b => (sink2, sink9, sink10) => val b3 = b.add(Broadcast[Int](2)) val b7 = b.add(Broadcast[Int](2)) val b11 = b.add(Broadcast[Int](3)) @@ -131,7 +131,7 @@ class GraphOpsIntegrationSpec extends StreamSpec { "allow adding of flows to sources and sinks to flows" in { - val resultFuture = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b ⇒ (sink) ⇒ + val resultFuture = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Seq[Int]]) { implicit b => (sink) => val bcast = b.add(Broadcast[Int](2)) val merge = b.add(Merge[Int](2)) @@ -149,7 +149,7 @@ class GraphOpsIntegrationSpec extends StreamSpec { val p = Source(List(1, 2, 3)).runWith(Sink.asPublisher(false)) val s = TestSubscriber.manualProbe[Int] val flow = Flow[Int].map(_ * 2) - RunnableGraph.fromGraph(GraphDSL.create() { implicit builder ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit builder => Source.fromPublisher(p) ~> flow ~> Sink.fromSubscriber(s) ClosedShape }).run() @@ -164,7 +164,7 @@ class GraphOpsIntegrationSpec extends StreamSpec { "be possible to use as lego bricks" in { val shuffler = Shuffle(Flow[Int].map(_ + 1)) - val f: Future[Seq[Int]] = RunnableGraph.fromGraph(GraphDSL.create(shuffler, shuffler, shuffler, Sink.head[Seq[Int]])((_, _, _, fut) ⇒ fut) { implicit b ⇒ (s1, s2, s3, sink) ⇒ + val f: Future[Seq[Int]] = RunnableGraph.fromGraph(GraphDSL.create(shuffler, shuffler, shuffler, Sink.head[Seq[Int]])((_, _, _, fut) => fut) { implicit b => (s1, s2, s3, sink) => val merge = b.add(Merge[Int](2)) Source(List(1, 2, 3)) ~> s1.in1 @@ -192,15 +192,15 @@ class GraphOpsIntegrationSpec extends StreamSpec { implicit val ex = materializer.system.dispatcher //#graph-from-list - val sinks = immutable.Seq("a", "b", "c").map(prefix ⇒ - Flow[String].filter(str ⇒ str.startsWith(prefix)).toMat(Sink.head[String])(Keep.right) + val sinks = immutable.Seq("a", "b", "c").map(prefix => + Flow[String].filter(str => str.startsWith(prefix)).toMat(Sink.head[String])(Keep.right) ) - val g: RunnableGraph[Seq[Future[String]]] = RunnableGraph.fromGraph(GraphDSL.create(sinks) { implicit b ⇒ sinkList ⇒ + val g: RunnableGraph[Seq[Future[String]]] = RunnableGraph.fromGraph(GraphDSL.create(sinks) { implicit b => sinkList => val broadcast = b.add(Broadcast[String](sinkList.size)) Source(List("ax", "bx", "cx")) ~> broadcast - sinkList.foreach(sink ⇒ broadcast ~> sink) + sinkList.foreach(sink => broadcast ~> sink) ClosedShape }) @@ -221,11 +221,11 @@ class GraphOpsIntegrationSpec extends StreamSpec { val sinks = immutable.Seq(Sink.seq[Int]) - val g: RunnableGraph[Seq[Future[immutable.Seq[Int]]]] = RunnableGraph.fromGraph(GraphDSL.create(sinks) { implicit b ⇒ sinkList ⇒ + val g: RunnableGraph[Seq[Future[immutable.Seq[Int]]]] = RunnableGraph.fromGraph(GraphDSL.create(sinks) { implicit b => sinkList => val broadcast = b.add(Broadcast[Int](sinkList.size)) Source(List(1, 2, 3)) ~> broadcast - sinkList.foreach(sink ⇒ broadcast ~> sink) + sinkList.foreach(sink => broadcast ~> sink) ClosedShape }) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphPartialSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphPartialSpec.scala index e98bd5fabb..82060c5f26 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphPartialSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphPartialSpec.scala @@ -21,16 +21,16 @@ class GraphPartialSpec extends StreamSpec { import GraphDSL.Implicits._ "be able to build and reuse simple partial graphs" in { - val doubler = GraphDSL.create() { implicit b ⇒ + val doubler = GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[Int](2)) - val zip = b.add(ZipWith((a: Int, b: Int) ⇒ a + b)) + val zip = b.add(ZipWith((a: Int, b: Int) => a + b)) bcast.out(0) ~> zip.in0 bcast.out(1) ~> zip.in1 FlowShape(bcast.in, zip.out) } - val (_, _, result) = RunnableGraph.fromGraph(GraphDSL.create(doubler, doubler, Sink.head[Seq[Int]])(Tuple3.apply) { implicit b ⇒ (d1, d2, sink) ⇒ + val (_, _, result) = RunnableGraph.fromGraph(GraphDSL.create(doubler, doubler, Sink.head[Seq[Int]])(Tuple3.apply) { implicit b => (d1, d2, sink) => Source(List(1, 2, 3)) ~> d1.in d1.out ~> d2.in d2.out.grouped(100) ~> sink.in @@ -41,9 +41,9 @@ class GraphPartialSpec extends StreamSpec { } "be able to build and reuse simple materializing partial graphs" in { - val doubler = GraphDSL.create(Sink.head[Seq[Int]]) { implicit b ⇒ sink ⇒ + val doubler = GraphDSL.create(Sink.head[Seq[Int]]) { implicit b => sink => val bcast = b.add(Broadcast[Int](3)) - val zip = b.add(ZipWith((a: Int, b: Int) ⇒ a + b)) + val zip = b.add(ZipWith((a: Int, b: Int) => a + b)) bcast.out(0) ~> zip.in0 bcast.out(1) ~> zip.in1 @@ -51,7 +51,7 @@ class GraphPartialSpec extends StreamSpec { FlowShape(bcast.in, zip.out) } - val (sub1, sub2, result) = RunnableGraph.fromGraph(GraphDSL.create(doubler, doubler, Sink.head[Seq[Int]])(Tuple3.apply) { implicit b ⇒ (d1, d2, sink) ⇒ + val (sub1, sub2, result) = RunnableGraph.fromGraph(GraphDSL.create(doubler, doubler, Sink.head[Seq[Int]])(Tuple3.apply) { implicit b => (d1, d2, sink) => Source(List(1, 2, 3)) ~> d1.in d1.out ~> d2.in d2.out.grouped(100) ~> sink.in @@ -66,10 +66,10 @@ class GraphPartialSpec extends StreamSpec { "be able to build and reuse complex materializing partial graphs" in { val summer = Sink.fold[Int, Int](0)(_ + _) - val doubler = GraphDSL.create(summer, summer)(Tuple2.apply) { implicit b ⇒ (s1, s2) ⇒ + val doubler = GraphDSL.create(summer, summer)(Tuple2.apply) { implicit b => (s1, s2) => val bcast = b.add(Broadcast[Int](3)) val bcast2 = b.add(Broadcast[Int](2)) - val zip = b.add(ZipWith((a: Int, b: Int) ⇒ a + b)) + val zip = b.add(ZipWith((a: Int, b: Int) => a + b)) bcast.out(0) ~> zip.in0 bcast.out(1) ~> zip.in1 @@ -81,7 +81,7 @@ class GraphPartialSpec extends StreamSpec { FlowShape(bcast.in, bcast2.out(1)) } - val (sub1, sub2, result) = RunnableGraph.fromGraph(GraphDSL.create(doubler, doubler, Sink.head[Seq[Int]])(Tuple3.apply) { implicit b ⇒ (d1, d2, sink) ⇒ + val (sub1, sub2, result) = RunnableGraph.fromGraph(GraphDSL.create(doubler, doubler, Sink.head[Seq[Int]])(Tuple3.apply) { implicit b => (d1, d2, sink) => Source(List(1, 2, 3)) ~> d1.in d1.out ~> d2.in d2.out.grouped(100) ~> sink.in @@ -96,11 +96,11 @@ class GraphPartialSpec extends StreamSpec { } "be able to expose the ports of imported graphs" in { - val p = GraphDSL.create(Flow[Int].map(_ + 1)) { implicit b ⇒ flow ⇒ + val p = GraphDSL.create(Flow[Int].map(_ + 1)) { implicit b => flow => FlowShape(flow.in, flow.out) } - val fut = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Int], p)(Keep.left) { implicit b ⇒ (sink, flow) ⇒ + val fut = RunnableGraph.fromGraph(GraphDSL.create(Sink.head[Int], p)(Keep.left) { implicit b => (sink, flow) => import GraphDSL.Implicits._ Source.single(0) ~> flow.in flow.out ~> sink.in diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphPartitionSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphPartitionSpec.scala index 04ab622d92..0087d5ad77 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphPartitionSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphPartitionSpec.scala @@ -22,11 +22,11 @@ class GraphPartitionSpec extends StreamSpec { "partition to three subscribers" in assertAllStagesStopped { - val (s1, s2, s3) = RunnableGraph.fromGraph(GraphDSL.create(Sink.seq[Int], Sink.seq[Int], Sink.seq[Int])(Tuple3.apply) { implicit b ⇒ (sink1, sink2, sink3) ⇒ + val (s1, s2, s3) = RunnableGraph.fromGraph(GraphDSL.create(Sink.seq[Int], Sink.seq[Int], Sink.seq[Int])(Tuple3.apply) { implicit b => (sink1, sink2, sink3) => val partition = b.add(Partition[Int](3, { - case g if (g > 3) ⇒ 0 - case l if (l < 3) ⇒ 1 - case e if (e == 3) ⇒ 2 + case g if (g > 3) => 0 + case l if (l < 3) => 1 + case e if (e == 3) => 2 })) Source(List(1, 2, 3, 4, 5)) ~> partition.in partition.out(0) ~> sink1.in @@ -45,10 +45,10 @@ class GraphPartitionSpec extends StreamSpec { val c1 = TestSubscriber.probe[String]() val c2 = TestSubscriber.probe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val partition = b.add(Partition[String](2, { - case s if (s.length > 4) ⇒ 0 - case _ ⇒ 1 + case s if (s.length > 4) => 0 + case _ => 1 })) Source(List("this", "is", "just", "another", "test")) ~> partition.in partition.out(0) ~> Sink.fromSubscriber(c1) @@ -72,8 +72,8 @@ class GraphPartitionSpec extends StreamSpec { val c1 = TestSubscriber.probe[Int]() val c2 = TestSubscriber.probe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ - val partition = b.add(Partition[Int](2, { case l if l < 6 ⇒ 0; case _ ⇒ 1 })) + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => + val partition = b.add(Partition[Int](2, { case l if l < 6 => 0; case _ => 1 })) Source(List(6, 3)) ~> partition.in partition.out(0) ~> Sink.fromSubscriber(c1) partition.out(1) ~> Sink.fromSubscriber(c2) @@ -94,8 +94,8 @@ class GraphPartitionSpec extends StreamSpec { val c1 = TestSubscriber.probe[Int]() val c2 = TestSubscriber.probe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ - val partition = b.add(new Partition[Int](2, { case l if l < 6 ⇒ 0; case _ ⇒ 1 }, false)) + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => + val partition = b.add(new Partition[Int](2, { case l if l < 6 => 0; case _ => 1 }, false)) Source.fromPublisher(p1.getPublisher) ~> partition.in partition.out(0) ~> Flow[Int].buffer(16, OverflowStrategy.backpressure) ~> Sink.fromSubscriber(c1) partition.out(1) ~> Flow[Int].buffer(16, OverflowStrategy.backpressure) ~> Sink.fromSubscriber(c2) @@ -125,8 +125,8 @@ class GraphPartitionSpec extends StreamSpec { val c1 = TestSubscriber.probe[Int]() val c2 = TestSubscriber.probe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ - val partition = b.add(new Partition[Int](2, { case l if l < 6 ⇒ 0; case _ ⇒ 1 }, true)) + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => + val partition = b.add(new Partition[Int](2, { case l if l < 6 => 0; case _ => 1 }, true)) Source.fromPublisher(p1.getPublisher) ~> partition.in partition.out(0) ~> Flow[Int].buffer(16, OverflowStrategy.backpressure) ~> Sink.fromSubscriber(c1) partition.out(1) ~> Flow[Int].buffer(16, OverflowStrategy.backpressure) ~> Sink.fromSubscriber(c2) @@ -150,8 +150,8 @@ class GraphPartitionSpec extends StreamSpec { val s = Sink.seq[Int] val input = Set(5, 2, 9, 1, 1, 1, 10) - val g = RunnableGraph.fromGraph(GraphDSL.create(s) { implicit b ⇒ sink ⇒ - val partition = b.add(Partition[Int](2, { case l if l < 4 ⇒ 0; case _ ⇒ 1 })) + val g = RunnableGraph.fromGraph(GraphDSL.create(s) { implicit b => sink => + val partition = b.add(Partition[Int](2, { case l if l < 4 => 0; case _ => 1 })) val merge = b.add(Merge[Int](2)) Source(input) ~> partition.in partition.out(0) ~> merge.in(0) @@ -172,8 +172,8 @@ class GraphPartitionSpec extends StreamSpec { val c1 = TestSubscriber.probe[Int]() val c2 = TestSubscriber.probe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ - val partition = b.add(Partition[Int](2, { case l if l < 6 ⇒ 0; case _ ⇒ 1 })) + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => + val partition = b.add(Partition[Int](2, { case l if l < 6 => 0; case _ => 1 })) Source(List(6)) ~> partition.in partition.out(0) ~> Sink.fromSubscriber(c1) partition.out(1) ~> Sink.fromSubscriber(c2) @@ -192,8 +192,8 @@ class GraphPartitionSpec extends StreamSpec { val c1 = TestSubscriber.probe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ - val partition = b.add(Partition[Int](2, { case l if l < 0 ⇒ -1; case _ ⇒ 0 })) + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => + val partition = b.add(Partition[Int](2, { case l if l < 0 => -1; case _ => 0 })) Source(List(-3)) ~> partition.in partition.out(0) ~> Sink.fromSubscriber(c1) partition.out(1) ~> Sink.ignore diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphStageTimersSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphStageTimersSpec.scala index d148fb4025..241a4565af 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphStageTimersSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphStageTimersSpec.scala @@ -68,17 +68,17 @@ class GraphStageTimersSpec extends StreamSpec { } private def onTestEvent(event: Any): Unit = event match { - case TestSingleTimer ⇒ + case TestSingleTimer => scheduleOnce("TestSingleTimer", 500.millis.dilated) - case TestSingleTimerResubmit ⇒ + case TestSingleTimerResubmit => scheduleOnce("TestSingleTimerResubmit", 500.millis.dilated) - case TestCancelTimer ⇒ + case TestCancelTimer => scheduleOnce("TestCancelTimer", 1.milli.dilated) // Likely in mailbox but we cannot guarantee cancelTimer("TestCancelTimer") probe ! TestCancelTimerAck scheduleOnce("TestCancelTimer", 500.milli.dilated) - case TestRepeatedTimer ⇒ + case TestRepeatedTimer => schedulePeriodically("TestRepeatedTimer", 100.millis.dilated) } } @@ -144,7 +144,7 @@ class GraphStageTimersSpec extends StreamSpec { driver ! TestRepeatedTimer val seq = receiveWhile(2.seconds) { - case t: Tick ⇒ t + case t: Tick => t } seq should have length 5 expectNoMsg(1.second) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphUnzipSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphUnzipSpec.scala index 1d0b7636d3..25f3da1e74 100755 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphUnzipSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphUnzipSpec.scala @@ -23,9 +23,9 @@ class GraphUnzipSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val unzip = b.add(Unzip[Int, String]()) - Source(List(1 → "a", 2 → "b", 3 → "c")) ~> unzip.in + Source(List(1 -> "a", 2 -> "b", 3 -> "c")) ~> unzip.in unzip.out1 ~> Flow[String].buffer(16, OverflowStrategy.backpressure) ~> Sink.fromSubscriber(c2) unzip.out0 ~> Flow[Int].buffer(16, OverflowStrategy.backpressure).map(_ * 2) ~> Sink.fromSubscriber(c1) ClosedShape @@ -53,9 +53,9 @@ class GraphUnzipSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val unzip = b.add(Unzip[Int, String]()) - Source(List(1 → "a", 2 → "b", 3 → "c")) ~> unzip.in + Source(List(1 -> "a", 2 -> "b", 3 -> "c")) ~> unzip.in unzip.out0 ~> Sink.fromSubscriber(c1) unzip.out1 ~> Sink.fromSubscriber(c2) ClosedShape @@ -75,9 +75,9 @@ class GraphUnzipSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val unzip = b.add(Unzip[Int, String]()) - Source(List(1 → "a", 2 → "b", 3 → "c")) ~> unzip.in + Source(List(1 -> "a", 2 -> "b", 3 -> "c")) ~> unzip.in unzip.out0 ~> Sink.fromSubscriber(c1) unzip.out1 ~> Sink.fromSubscriber(c2) ClosedShape @@ -97,9 +97,9 @@ class GraphUnzipSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val unzip = b.add(Unzip[Int, String]()) - Source(List(1 → "a", 2 → "b", 3 → "c")) ~> unzip.in + Source(List(1 -> "a", 2 -> "b", 3 -> "c")) ~> unzip.in unzip.out0 ~> Sink.fromSubscriber(c1) unzip.out1 ~> Sink.fromSubscriber(c2) ClosedShape @@ -120,9 +120,9 @@ class GraphUnzipSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val unzip = b.add(Unzip[Int, String]()) - Source(List(1 → "a", 2 → "b", 3 → "c")) ~> unzip.in + Source(List(1 -> "a", 2 -> "b", 3 -> "c")) ~> unzip.in unzip.out0 ~> Sink.fromSubscriber(c1) unzip.out1 ~> Sink.fromSubscriber(c2) ClosedShape @@ -144,7 +144,7 @@ class GraphUnzipSpec extends StreamSpec { val c1 = TestSubscriber.manualProbe[Int]() val c2 = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val unzip = b.add(Unzip[Int, String]()) Source.fromPublisher(p1.getPublisher) ~> unzip.in unzip.out0 ~> Sink.fromSubscriber(c1) @@ -158,10 +158,10 @@ class GraphUnzipSpec extends StreamSpec { sub1.request(3) sub2.request(3) p1.expectRequest(p1Sub, 16) - p1Sub.sendNext(1 → "a") + p1Sub.sendNext(1 -> "a") c1.expectNext(1) c2.expectNext("a") - p1Sub.sendNext(2 → "b") + p1Sub.sendNext(2 -> "b") c1.expectNext(2) c2.expectNext("b") sub1.cancel() @@ -171,10 +171,10 @@ class GraphUnzipSpec extends StreamSpec { "work with zip" in assertAllStagesStopped { val c1 = TestSubscriber.manualProbe[(Int, String)]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(Zip[Int, String]()) val unzip = b.add(Unzip[Int, String]()) - Source(List(1 → "a", 2 → "b", 3 → "c")) ~> unzip.in + Source(List(1 -> "a", 2 -> "b", 3 -> "c")) ~> unzip.in unzip.out0 ~> zip.in0 unzip.out1 ~> zip.in1 zip.out ~> Sink.fromSubscriber(c1) @@ -183,9 +183,9 @@ class GraphUnzipSpec extends StreamSpec { val sub1 = c1.expectSubscription() sub1.request(5) - c1.expectNext(1 → "a") - c1.expectNext(2 → "b") - c1.expectNext(3 → "c") + c1.expectNext(1 -> "a") + c1.expectNext(2 -> "b") + c1.expectNext(3 -> "c") c1.expectComplete() } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphUnzipWithSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphUnzipWithSpec.scala index 8e9c01df54..2d216ab5db 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphUnzipWithSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphUnzipWithSpec.scala @@ -33,7 +33,7 @@ class GraphUnzipWithSpec extends StreamSpec { def right: Outlet[RightOutput] } - val f: (Int ⇒ (Int, String)) = b ⇒ (b + b, b + "+" + b) + val f: (Int => (Int, String)) = b => (b + b, b + "+" + b) def fixture(b: GraphDSL.Builder[_]): Fixture = new Fixture(b) { val unzip = b.add(UnzipWith[Int, Int, String](f)) @@ -49,7 +49,7 @@ class GraphUnzipWithSpec extends StreamSpec { val leftSubscriber = TestSubscriber.probe[LeftOutput]() val rightSubscriber = TestSubscriber.probe[RightOutput]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val f = fixture(b) Source.fromPublisher(p) ~> f.in @@ -98,7 +98,7 @@ class GraphUnzipWithSpec extends StreamSpec { val leftProbe = TestSubscriber.manualProbe[LeftOutput]() val rightProbe = TestSubscriber.manualProbe[RightOutput]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val unzip = b.add(UnzipWith(f)) Source(1 to 4) ~> unzip.in @@ -148,8 +148,8 @@ class GraphUnzipWithSpec extends StreamSpec { val leftProbe = TestSubscriber.manualProbe[LeftOutput]() val rightProbe = TestSubscriber.manualProbe[RightOutput]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ - val unzip = b.add(UnzipWith[Int, Int, String]((b: Int) ⇒ (1 / b, 1 + "/" + b))) + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => + val unzip = b.add(UnzipWith[Int, Int, String]((b: Int) => (1 / b, 1 + "/" + b))) Source(-2 to 2) ~> unzip.in @@ -180,7 +180,7 @@ class GraphUnzipWithSpec extends StreamSpec { } leftProbe.expectError() match { - case a: java.lang.ArithmeticException ⇒ a.getMessage should be("/ by zero") + case a: java.lang.ArithmeticException => a.getMessage should be("/ by zero") } rightProbe.expectError() @@ -195,8 +195,8 @@ class GraphUnzipWithSpec extends StreamSpec { case class Person(name: String, surname: String, int: Int) - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ - val unzip = b.add(UnzipWith((a: Person) ⇒ Person.unapply(a).get)) + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => + val unzip = b.add(UnzipWith((a: Person) => Person.unapply(a).get)) Source.single(Person("Caplin", "Capybara", 3)) ~> unzip.in @@ -231,9 +231,9 @@ class GraphUnzipWithSpec extends StreamSpec { val probe15 = TestSubscriber.manualProbe[String]() val probe21 = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => - val split22 = (a: (List[Int])) ⇒ + val split22 = (a: (List[Int])) => (a(0), a(0).toString, a(1), a(1).toString, a(2), a(2).toString, diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipLatestSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipLatestSpec.scala index bd89d7422a..e5379b4595 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipLatestSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipLatestSpec.scala @@ -155,11 +155,11 @@ class GraphZipLatestSpec probe.expectNext((a3, b2)) } - val first = (t: (Probe[Boolean], Probe[Int])) ⇒ t._1 - val second = (t: (Probe[Boolean], Probe[Int])) ⇒ t._2 + val first = (t: (Probe[Boolean], Probe[Int])) => t._1 + val second = (t: (Probe[Boolean], Probe[Int])) => t._2 "complete when either source completes" in { - forAll(Gen.oneOf(first, second)) { select ⇒ + forAll(Gen.oneOf(first, second)) { select => val (probe, bools, ints) = testGraph[Boolean, Int] Given("either source completes") @@ -171,7 +171,7 @@ class GraphZipLatestSpec } "complete when either source completes and requesting element" in { - forAll(Gen.oneOf(first, second)) { select ⇒ + forAll(Gen.oneOf(first, second)) { select => val (probe, bools, ints) = testGraph[Boolean, Int] Given("either source completes") @@ -186,7 +186,7 @@ class GraphZipLatestSpec } "complete when either source completes with some pending element" in { - forAll(Gen.oneOf(first, second)) { select ⇒ + forAll(Gen.oneOf(first, second)) { select => val (probe, bools, ints) = testGraph[Boolean, Int] Given("one element pushed on each source") @@ -221,7 +221,7 @@ class GraphZipLatestSpec } "complete if no pending demand" in { - forAll(Gen.oneOf(first, second)) { select ⇒ + forAll(Gen.oneOf(first, second)) { select => val (probe, bools, ints) = testGraph[Boolean, Int] Given("request for one element") @@ -241,7 +241,7 @@ class GraphZipLatestSpec } "fail when either source has error" in { - forAll(Gen.oneOf(first, second)) { select ⇒ + forAll(Gen.oneOf(first, second)) { select => val (probe, bools, ints) = testGraph[Boolean, Int] val error = new RuntimeException @@ -282,15 +282,15 @@ class GraphZipLatestSpec Given(s"numbers up to 99 in tuples") val allNumbers = for { - firstDigit ← 0 to 9 - secondDigit ← 0 to 9 + firstDigit <- 0 to 9 + secondDigit <- 0 to 9 } yield (firstDigit, secondDigit) allNumbers.groupBy(_._1).toList.sortBy(_._1).foreach { - case (firstDigit, pairs) ⇒ { + case (firstDigit, pairs) => { When(s"sending first digit $firstDigit") firstDigits.sendNext(firstDigit) - pairs.map { case (_, digits) ⇒ digits }.foreach { secondDigit ⇒ + pairs.map { case (_, digits) => digits }.foreach { secondDigit => And(s"sending second digit $secondDigit") secondDigits.sendNext(secondDigit) probe.request(1) @@ -317,7 +317,7 @@ class GraphZipLatestSpec .create( TestSink.probe[(A, B)], TestSource.probe[A], - TestSource.probe[B])(Tuple3.apply) { implicit b ⇒ (ts, as, bs) ⇒ + TestSource.probe[B])(Tuple3.apply) { implicit b => (ts, as, bs) => import GraphDSL.Implicits._ val zipLatest = b.add(new ZipLatest[A, B]()) as ~> zipLatest.in0 diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipLatestWithSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipLatestWithSpec.scala index a693835b56..aa786ac9a9 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipLatestWithSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipLatestWithSpec.scala @@ -40,7 +40,7 @@ class GraphZipLatestWithSpec extends TwoStreamsSetup { val downstreamProbe = TestSubscriber.manualProbe[Outputs]() RunnableGraph - .fromGraph(GraphDSL.create() { implicit b ⇒ + .fromGraph(GraphDSL.create() { implicit b => val zipLatest = b.add(ZipLatestWith((_: Int) + (_: Int))) val never = Source.single(3).initialDelay(1 day) Source(1 to 2).concat(never) ~> zipLatest.in0 @@ -75,7 +75,7 @@ class GraphZipLatestWithSpec extends TwoStreamsSetup { val probe = TestSubscriber.manualProbe[Outputs]() RunnableGraph - .fromGraph(GraphDSL.create() { implicit b ⇒ + .fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipLatestWith[Int, Int, Int]((_: Int) / (_: Int))) val never = Source.single(2).initialDelay(1 day) Source.single(1).concat(never) ~> zip.in0 @@ -97,7 +97,7 @@ class GraphZipLatestWithSpec extends TwoStreamsSetup { subscription.request(2) } probe.expectError() match { - case a: java.lang.ArithmeticException ⇒ + case a: java.lang.ArithmeticException => a.getMessage should be("/ by zero") } probe.expectNoMsg(200.millis) @@ -146,7 +146,7 @@ class GraphZipLatestWithSpec extends TwoStreamsSetup { case class Person(name: String, surname: String, int: Int) RunnableGraph - .fromGraph(GraphDSL.create() { implicit b ⇒ + .fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipLatestWith(Person.apply _)) Source.single("Caplin") ~> zip.in0 @@ -173,7 +173,7 @@ class GraphZipLatestWithSpec extends TwoStreamsSetup { val upstreamProbe = TestPublisher.manualProbe[Int]() RunnableGraph - .fromGraph(GraphDSL.create() { implicit b ⇒ + .fromGraph(GraphDSL.create() { implicit b => val sum22 = (v1: Int, v2: String, v3: Int, @@ -195,7 +195,7 @@ class GraphZipLatestWithSpec extends TwoStreamsSetup { v19: Int, v20: String, v21: Int, - v22: String) ⇒ + v22: String) => v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10 + v11 + v12 + v13 + v14 + v15 + v16 + v17 + v18 + v19 + v20 + v21 + v22 diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipNSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipNSpec.scala index 53881b3f37..69479598c3 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipNSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipNSpec.scala @@ -29,7 +29,7 @@ class GraphZipNSpec extends TwoStreamsSetup { "work in the happy case" in assertAllStagesStopped { val probe = TestSubscriber.manualProbe[immutable.Seq[Int]]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zipN = b.add(ZipN[Int](2)) Source(1 to 4) ~> zipN.in(0) @@ -59,7 +59,7 @@ class GraphZipNSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[immutable.Seq[Int]]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zipN = b.add(ZipN[Int](2)) Source.fromPublisher(upstream1) ~> zipN.in(0) @@ -84,7 +84,7 @@ class GraphZipNSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[immutable.Seq[Int]]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zipN = b.add(ZipN[Int](2)) Source.fromPublisher(upstream1) ~> zipN.in(0) @@ -110,7 +110,7 @@ class GraphZipNSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[immutable.Seq[Int]]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zipN = b.add(ZipN[Int](2)) Source.fromPublisher(upstream1) ~> zipN.in(0) @@ -135,7 +135,7 @@ class GraphZipNSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[immutable.Seq[Int]]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zipN = b.add(ZipN[Int](2)) Source.fromPublisher(upstream1) ~> zipN.in(0) @@ -161,7 +161,7 @@ class GraphZipNSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[Int]() val downstream = TestSubscriber.probe[immutable.Seq[Int]]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zipN = b.add(ZipN[Int](2)) Source.fromPublisher(upstream1) ~> zipN.in(0) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipSpec.scala index 27a5f0e260..13bb3eae0b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipSpec.scala @@ -29,7 +29,7 @@ class GraphZipSpec extends TwoStreamsSetup { "work in the happy case" in assertAllStagesStopped { val probe = TestSubscriber.manualProbe[(Int, String)]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(Zip[Int, String]()) Source(1 to 4) ~> zip.in0 @@ -58,7 +58,7 @@ class GraphZipSpec extends TwoStreamsSetup { val upstream1 = TestPublisher.probe[Int]() val upstream2 = TestPublisher.probe[String]() - val completed = RunnableGraph.fromGraph(GraphDSL.create(Sink.ignore) { implicit b ⇒ out ⇒ + val completed = RunnableGraph.fromGraph(GraphDSL.create(Sink.ignore) { implicit b => out => val zip = b.add(Zip[Int, String]()) Source.fromPublisher(upstream1) ~> zip.in0 @@ -83,7 +83,7 @@ class GraphZipSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[String]() val downstream = TestSubscriber.probe[(Int, String)]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zip = b.add(Zip[Int, String]()) Source.fromPublisher(upstream1) ~> zip.in0 @@ -109,7 +109,7 @@ class GraphZipSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[String]() val downstream = TestSubscriber.probe[(Int, String)]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zip = b.add(Zip[Int, String]()) Source.fromPublisher(upstream1) ~> zip.in0 @@ -134,7 +134,7 @@ class GraphZipSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[String]() val downstream = TestSubscriber.probe[(Int, String)]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zip = b.add(Zip[Int, String]()) Source.fromPublisher(upstream1) ~> zip.in0 @@ -160,7 +160,7 @@ class GraphZipSpec extends TwoStreamsSetup { val upstream2 = TestPublisher.probe[String]() val downstream = TestSubscriber.probe[(Int, String)]() - RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b ⇒ out ⇒ + RunnableGraph.fromGraph(GraphDSL.create(Sink.fromSubscriber(downstream)) { implicit b => out => val zip = b.add(Zip[Int, String]()) Source.fromPublisher(upstream1) ~> zip.in0 diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipWithNSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipWithNSpec.scala index faae3a2476..44d5ec1247 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipWithNSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipWithNSpec.scala @@ -27,7 +27,7 @@ class GraphZipWithNSpec extends TwoStreamsSetup { "work in the happy case" in { val probe = TestSubscriber.manualProbe[Outputs]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipWithN((_: immutable.Seq[Int]).sum)(2)) Source(1 to 4) ~> zip.in(0) Source(10 to 40 by 10) ~> zip.in(1) @@ -54,7 +54,7 @@ class GraphZipWithNSpec extends TwoStreamsSetup { "work in the sad case" in { val probe = TestSubscriber.manualProbe[Outputs]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipWithN((_: immutable.Seq[Int]).foldLeft(1)(_ / _))(2)) Source(1 to 4) ~> zip.in(0) @@ -75,7 +75,7 @@ class GraphZipWithNSpec extends TwoStreamsSetup { subscription.request(2) } probe.expectError() match { - case a: java.lang.ArithmeticException ⇒ a.getMessage should be("/ by zero") + case a: java.lang.ArithmeticException => a.getMessage should be("/ by zero") } probe.expectNoMsg(200.millis) } @@ -117,7 +117,7 @@ class GraphZipWithNSpec extends TwoStreamsSetup { "work with 3 inputs" in { val probe = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipWithN((_: immutable.Seq[Int]).sum)(3)) Source.single(1) ~> zip.in(0) @@ -140,11 +140,11 @@ class GraphZipWithNSpec extends TwoStreamsSetup { "work with 30 inputs" in { val probe = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipWithN((_: immutable.Seq[Int]).sum)(30)) (0 to 29).foreach { - n ⇒ Source.single(n) ~> zip.in(n) + n => Source.single(n) ~> zip.in(n) } zip.out ~> Sink.fromSubscriber(probe) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipWithSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipWithSpec.scala index 925d9d04ad..3129ecba6d 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipWithSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/GraphZipWithSpec.scala @@ -26,7 +26,7 @@ class GraphZipWithSpec extends TwoStreamsSetup { "work in the happy case" in { val probe = TestSubscriber.manualProbe[Outputs]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipWith((_: Int) + (_: Int))) Source(1 to 4) ~> zip.in0 Source(10 to 40 by 10) ~> zip.in1 @@ -53,7 +53,7 @@ class GraphZipWithSpec extends TwoStreamsSetup { "work in the sad case" in { val probe = TestSubscriber.manualProbe[Outputs]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipWith[Int, Int, Int]((_: Int) / (_: Int))) Source(1 to 4) ~> zip.in0 @@ -74,7 +74,7 @@ class GraphZipWithSpec extends TwoStreamsSetup { subscription.request(2) } probe.expectError() match { - case a: java.lang.ArithmeticException ⇒ a.getMessage should be("/ by zero") + case a: java.lang.ArithmeticException => a.getMessage should be("/ by zero") } probe.expectNoMsg(200.millis) } @@ -118,7 +118,7 @@ class GraphZipWithSpec extends TwoStreamsSetup { case class Person(name: String, surname: String, int: Int) - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val zip = b.add(ZipWith(Person.apply _)) Source.single("Caplin") ~> zip.in0 @@ -141,10 +141,10 @@ class GraphZipWithSpec extends TwoStreamsSetup { "work with up to 22 inputs" in { val probe = TestSubscriber.manualProbe[String]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val sum22 = (v1: Int, v2: String, v3: Int, v4: String, v5: Int, v6: String, v7: Int, v8: String, v9: Int, v10: String, - v11: Int, v12: String, v13: Int, v14: String, v15: Int, v16: String, v17: Int, v18: String, v19: Int, v20: String, v21: Int, v22: String) ⇒ + v11: Int, v12: String, v13: Int, v14: String, v15: Int, v16: String, v17: Int, v18: String, v19: Int, v20: String, v21: Int, v22: String) => v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10 + v11 + v12 + v13 + v14 + v15 + v16 + v17 + v18 + v19 + v20 + v21 + v22 diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/HubSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/HubSpec.scala index 3263fd0261..a5d2a38abf 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/HubSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/HubSpec.scala @@ -43,7 +43,7 @@ class HubSpec extends StreamSpec { val upstream = TestPublisher.probe[Int]() Source.fromPublisher(upstream).runWith(sink) - for (i ← 1 to 5) upstream.sendNext(i) + for (i <- 1 to 5) upstream.sendNext(i) upstream.expectCancellation() result.futureValue.sorted should ===(1 to 5) @@ -55,7 +55,7 @@ class HubSpec extends StreamSpec { val upstream2 = TestPublisher.probe[Int]() Source.fromPublisher(upstream1).runWith(sink) - for (i ← 1 to 5) upstream1.sendNext(i) + for (i <- 1 to 5) upstream1.sendNext(i) upstream1.expectCancellation() result.futureValue.sorted should ===(1 to 5) @@ -69,7 +69,7 @@ class HubSpec extends StreamSpec { val downstream = TestSubscriber.manualProbe[Int]() val sink = Sink.fromSubscriber(downstream).runWith(MergeHub.source[Int](3)) - Source(1 to 10).map { i ⇒ testActor ! i; i }.runWith(sink) + Source(1 to 10).map { i => testActor ! i; i }.runWith(sink) val sub = downstream.expectSubscription() sub.request(1) @@ -280,7 +280,7 @@ class HubSpec extends StreamSpec { "be able to implement a keep-dropping-if-unsubscribed policy with a simple Sink.ignore" in assertAllStagesStopped { val killSwitch = KillSwitches.shared("test-switch") - val source = Source.fromIterator(() ⇒ Iterator.from(0)).via(killSwitch.flow).runWith(BroadcastHub.sink(8)) + val source = Source.fromIterator(() => Iterator.from(0)).via(killSwitch.flow).runWith(BroadcastHub.sink(8)) // Now the Hub "drops" elements until we attach a new consumer (Source.ignore consumes as fast as possible) source.runWith(Sink.ignore) @@ -293,7 +293,7 @@ class HubSpec extends StreamSpec { downstream.request(1) val first = downstream.expectNext() - for (i ← (first + 1) to (first + 10)) { + for (i <- (first + 1) to (first + 10)) { downstream.request(1) downstream.expectNext(i) } @@ -404,12 +404,12 @@ class HubSpec extends StreamSpec { "PartitionHub" must { "work in the happy case with one stream" in assertAllStagesStopped { - val source = Source(1 to 10).runWith(PartitionHub.sink((size, elem) ⇒ 0, startAfterNrOfConsumers = 0, bufferSize = 8)) + val source = Source(1 to 10).runWith(PartitionHub.sink((size, elem) => 0, startAfterNrOfConsumers = 0, bufferSize = 8)) source.runWith(Sink.seq).futureValue should ===(1 to 10) } "work in the happy case with two streams" in assertAllStagesStopped { - val source = Source(0 until 10).runWith(PartitionHub.sink((size, elem) ⇒ elem % size, startAfterNrOfConsumers = 2, bufferSize = 8)) + val source = Source(0 until 10).runWith(PartitionHub.sink((size, elem) => elem % size, startAfterNrOfConsumers = 2, bufferSize = 8)) val result1 = source.runWith(Sink.seq) // it should not start publishing until startAfterNrOfConsumers = 2 Thread.sleep(20) @@ -419,10 +419,10 @@ class HubSpec extends StreamSpec { } "be able to use as round-robin router" in assertAllStagesStopped { - val source = Source(0 until 10).runWith(PartitionHub.statefulSink(() ⇒ { + val source = Source(0 until 10).runWith(PartitionHub.statefulSink(() => { var n = 0L - (info, elem) ⇒ { + (info, elem) => { n += 1 info.consumerIdByIdx((n % info.size).toInt) } @@ -434,14 +434,14 @@ class HubSpec extends StreamSpec { } "be able to use as sticky session router" in assertAllStagesStopped { - val source = Source(List("usr-1", "usr-2", "usr-1", "usr-3")).runWith(PartitionHub.statefulSink(() ⇒ { + val source = Source(List("usr-1", "usr-2", "usr-1", "usr-3")).runWith(PartitionHub.statefulSink(() => { var sessions = Map.empty[String, Long] var n = 0L - (info, elem) ⇒ { + (info, elem) => { sessions.get(elem) match { - case Some(id) if info.consumerIds.exists(_ == id) ⇒ id - case _ ⇒ + case Some(id) if info.consumerIds.exists(_ == id) => id + case _ => n += 1 val id = info.consumerIdByIdx((n % info.size).toInt) sessions = sessions.updated(elem, id) @@ -457,7 +457,7 @@ class HubSpec extends StreamSpec { "be able to use as fastest consumer router" in assertAllStagesStopped { val source = Source(0 until 1000).runWith(PartitionHub.statefulSink( - () ⇒ (info, elem) ⇒ info.consumerIds.toVector.minBy(id ⇒ info.queueSize(id)), + () => (info, elem) => info.consumerIds.toVector.minBy(id => info.queueSize(id)), startAfterNrOfConsumers = 2, bufferSize = 4)) val result1 = source.runWith(Sink.seq) val result2 = source.throttle(10, 100.millis, 10, ThrottleMode.Shaping).runWith(Sink.seq) @@ -467,7 +467,7 @@ class HubSpec extends StreamSpec { "route evenly" in assertAllStagesStopped { val (testSource, hub) = TestSource.probe[Int].toMat( - PartitionHub.sink((size, elem) ⇒ elem % size, startAfterNrOfConsumers = 2, bufferSize = 8))(Keep.both).run() + PartitionHub.sink((size, elem) => elem % size, startAfterNrOfConsumers = 2, bufferSize = 8))(Keep.both).run() val probe0 = hub.runWith(TestSink.probe[Int]) val probe1 = hub.runWith(TestSink.probe[Int]) probe0.request(3) @@ -501,7 +501,7 @@ class HubSpec extends StreamSpec { "route unevenly" in assertAllStagesStopped { val (testSource, hub) = TestSource.probe[Int].toMat( - PartitionHub.sink((size, elem) ⇒ (elem % 3) % 2, startAfterNrOfConsumers = 2, bufferSize = 8))(Keep.both).run() + PartitionHub.sink((size, elem) => (elem % 3) % 2, startAfterNrOfConsumers = 2, bufferSize = 8))(Keep.both).run() val probe0 = hub.runWith(TestSink.probe[Int]) val probe1 = hub.runWith(TestSink.probe[Int]) @@ -532,7 +532,7 @@ class HubSpec extends StreamSpec { "backpressure" in assertAllStagesStopped { val (testSource, hub) = TestSource.probe[Int].toMat( - PartitionHub.sink((size, elem) ⇒ 0, startAfterNrOfConsumers = 2, bufferSize = 4))(Keep.both).run() + PartitionHub.sink((size, elem) => 0, startAfterNrOfConsumers = 2, bufferSize = 4))(Keep.both).run() val probe0 = hub.runWith(TestSink.probe[Int]) val probe1 = hub.runWith(TestSink.probe[Int]) probe0.request(10) @@ -555,7 +555,7 @@ class HubSpec extends StreamSpec { "ensure that from two different speed consumers the slower controls the rate" in assertAllStagesStopped { val (firstElem, source) = Source.maybe[Int].concat(Source(1 until 20)).toMat( - PartitionHub.sink((size, elem) ⇒ elem % size, startAfterNrOfConsumers = 2, bufferSize = 1))(Keep.both).run() + PartitionHub.sink((size, elem) => elem % size, startAfterNrOfConsumers = 2, bufferSize = 1))(Keep.both).run() val f1 = source.throttle(1, 10.millis, 1, ThrottleMode.shaping).runWith(Sink.seq) // Second cannot be overwhelmed since the first one throttles the overall rate, and second allows a higher rate @@ -572,7 +572,7 @@ class HubSpec extends StreamSpec { "properly signal error to consumers" in assertAllStagesStopped { val upstream = TestPublisher.probe[Int]() val source = Source.fromPublisher(upstream).runWith( - PartitionHub.sink((size, elem) ⇒ elem % size, startAfterNrOfConsumers = 2, bufferSize = 8)) + PartitionHub.sink((size, elem) => elem % size, startAfterNrOfConsumers = 2, bufferSize = 8)) val downstream1 = TestSubscriber.probe[Int]() source.runWith(Sink.fromSubscriber(downstream1)) @@ -601,7 +601,7 @@ class HubSpec extends StreamSpec { } "properly signal completion to consumers arriving after producer finished" in assertAllStagesStopped { - val source = Source.empty[Int].runWith(PartitionHub.sink((size, elem) ⇒ elem % size, startAfterNrOfConsumers = 0)) + val source = Source.empty[Int].runWith(PartitionHub.sink((size, elem) => elem % size, startAfterNrOfConsumers = 0)) // Wait enough so the Hub gets the completion. This is racy, but this is fine because both // cases should work in the end Thread.sleep(10) @@ -612,7 +612,7 @@ class HubSpec extends StreamSpec { "remember completion for materialisations after completion" in { val (sourceProbe, source) = TestSource.probe[Unit].toMat( - PartitionHub.sink((size, elem) ⇒ 0, startAfterNrOfConsumers = 0))(Keep.both).run() + PartitionHub.sink((size, elem) => 0, startAfterNrOfConsumers = 0))(Keep.both).run() val sinkProbe = source.runWith(TestSink.probe[Unit]) sourceProbe.sendComplete() @@ -630,7 +630,7 @@ class HubSpec extends StreamSpec { "properly signal error to consumers arriving after producer finished" in assertAllStagesStopped { val source = Source.failed[Int](TE("Fail!")).runWith( - PartitionHub.sink((size, elem) ⇒ 0, startAfterNrOfConsumers = 0)) + PartitionHub.sink((size, elem) => 0, startAfterNrOfConsumers = 0)) // Wait enough so the Hub gets the failure. This is racy, but this is fine because both // cases should work in the end Thread.sleep(10) @@ -642,7 +642,7 @@ class HubSpec extends StreamSpec { "drop elements with negative index" in assertAllStagesStopped { val source = Source(0 until 10).runWith(PartitionHub.sink( - (size, elem) ⇒ if (elem == 3 || elem == 4) -1 else elem % size, startAfterNrOfConsumers = 2, bufferSize = 8)) + (size, elem) => if (elem == 3 || elem == 4) -1 else elem % size, startAfterNrOfConsumers = 2, bufferSize = 8)) val result1 = source.runWith(Sink.seq) val result2 = source.runWith(Sink.seq) result1.futureValue should ===((0 to 8 by 2).filterNot(_ == 4)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/JsonFramingSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/JsonFramingSpec.scala index b72b199a69..e764616fbd 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/JsonFramingSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/JsonFramingSpec.scala @@ -35,7 +35,7 @@ class JsonFramingSpec extends AkkaSpec { val result = Source.single(ByteString(input)) .via(JsonFraming.objectScanner(Int.MaxValue)) .runFold(Seq.empty[String]) { - case (acc, entry) ⇒ acc ++ Seq(entry.utf8String) + case (acc, entry) => acc ++ Seq(entry.utf8String) } // #using-json-framing @@ -56,7 +56,7 @@ class JsonFramingSpec extends AkkaSpec { .via(JsonFraming.objectScanner(Int.MaxValue)) .take(1) .runFold(Seq.empty[String]) { - case (acc, entry) ⇒ acc ++ Seq(entry.utf8String) + case (acc, entry) => acc ++ Seq(entry.utf8String) } Await.result(result, 3.seconds) shouldBe Seq("""{ "name": "john" }""") @@ -72,7 +72,7 @@ class JsonFramingSpec extends AkkaSpec { val result = Source.single(ByteString(input)) .via(JsonFraming.objectScanner(Int.MaxValue)) .runFold(Seq.empty[String]) { - case (acc, entry) ⇒ acc ++ Seq(entry.utf8String) + case (acc, entry) => acc ++ Seq(entry.utf8String) } Await.result(result, 3.seconds) shouldBe Seq( @@ -88,7 +88,7 @@ class JsonFramingSpec extends AkkaSpec { val result = Source.single(ByteString(input)) .via(JsonFraming.objectScanner(Int.MaxValue)) .runFold(Seq.empty[String]) { - case (acc, entry) ⇒ acc ++ Seq(entry.utf8String) + case (acc, entry) => acc ++ Seq(entry.utf8String) } result.futureValue shouldBe Seq( @@ -112,7 +112,7 @@ class JsonFramingSpec extends AkkaSpec { val result = Source.apply(input) .via(JsonFraming.objectScanner(Int.MaxValue)) .runFold(Seq.empty[String]) { - case (acc, entry) ⇒ acc ++ Seq(entry.utf8String) + case (acc, entry) => acc ++ Seq(entry.utf8String) } result.futureValue shouldBe Seq( @@ -458,7 +458,7 @@ class JsonFramingSpec extends AkkaSpec { val buffer = new JsonObjectParser() """{ "name": "john"""".foreach { - c ⇒ + c => buffer.offer(ByteString(c)) buffer.poll() should ===(None) } @@ -492,7 +492,7 @@ class JsonFramingSpec extends AkkaSpec { val result = Source.single(ByteString(input)) .via(JsonFraming.objectScanner(5)).map(_.utf8String) .runFold(Seq.empty[String]) { - case (acc, entry) ⇒ acc ++ Seq(entry) + case (acc, entry) => acc ++ Seq(entry) } a[FramingException] shouldBe thrownBy { @@ -504,7 +504,7 @@ class JsonFramingSpec extends AkkaSpec { val input = List( """{ "name": "john" }""", """{ "name": "jack" }""", - """{ "name": "very very long name somehow. how did this happen?" }""").map(s ⇒ ByteString(s)) + """{ "name": "very very long name somehow. how did this happen?" }""").map(s => ByteString(s)) val probe = Source(input) .via(JsonFraming.objectScanner(48)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazilyAsyncSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazilyAsyncSpec.scala index 1714716d37..87227e783b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazilyAsyncSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazilyAsyncSpec.scala @@ -24,7 +24,7 @@ class LazilyAsyncSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "A lazy async source" should { "work in happy path scenario" in assertAllStagesStopped { - val stream = Source.lazilyAsync { () ⇒ Future(42) }.runWith(Sink.head) + val stream = Source.lazilyAsync { () => Future(42) }.runWith(Sink.head) stream.futureValue should ===(42) } @@ -33,7 +33,7 @@ class LazilyAsyncSpec extends StreamSpec with DefaultTimeout with ScalaFutures { val probe = TestSubscriber.probe[Int]() val constructed = new AtomicBoolean(false) - val result = Source.lazilyAsync { () ⇒ constructed.set(true); Future(42) } + val result = Source.lazilyAsync { () => constructed.set(true); Future(42) } .runWith(Sink.fromSubscriber(probe)) probe.cancel() @@ -41,7 +41,7 @@ class LazilyAsyncSpec extends StreamSpec with DefaultTimeout with ScalaFutures { } "fail materialized value when downstream cancels without ever consuming any element" in assertAllStagesStopped { - val materialization = Source.lazilyAsync { () ⇒ Future(42) } + val materialization = Source.lazilyAsync { () => Future(42) } .toMat(Sink.cancelled)(Keep.left) .run() @@ -54,8 +54,8 @@ class LazilyAsyncSpec extends StreamSpec with DefaultTimeout with ScalaFutures { val probe = TestSubscriber.probe[Int]() val materialization: Future[Done] = - Source.lazilyAsync { () ⇒ Future(42) } - .mapMaterializedValue(_.map(_ ⇒ Done)) + Source.lazilyAsync { () => Future(42) } + .mapMaterializedValue(_.map(_ => Done)) .to(Sink.fromSubscriber(probe)) .run() @@ -70,7 +70,7 @@ class LazilyAsyncSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "propagate failed future from factory" in assertAllStagesStopped { val probe = TestSubscriber.probe[Int]() val failure = new RuntimeException("too bad") - val materialization = Source.lazilyAsync { () ⇒ Future.failed(failure) } + val materialization = Source.lazilyAsync { () => Future.failed(failure) } .to(Sink.fromSubscriber(probe)) .run() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazyFlowSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazyFlowSpec.scala index 30dc76e42a..2b780a297d 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazyFlowSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazyFlowSpec.scala @@ -25,22 +25,22 @@ class LazyFlowSpec extends StreamSpec { val ex = TE("") "A LazyFlow" must { - def mapF(e: Int): () ⇒ Future[Flow[Int, String, NotUsed]] = () ⇒ - Future.successful(Flow.fromFunction[Int, String](i ⇒ (i * e).toString)) + def mapF(e: Int): () => Future[Flow[Int, String, NotUsed]] = () => + Future.successful(Flow.fromFunction[Int, String](i => (i * e).toString)) val flowF = Future.successful(Flow[Int]) "work in happy case" in assertAllStagesStopped { val probe = Source(2 to 10) .via(Flow.lazyInitAsync[Int, String, NotUsed](mapF(2))) .runWith(TestSink.probe[String]) probe.request(100) - (2 to 10).map(i ⇒ (i * 2).toString).foreach(probe.expectNext) + (2 to 10).map(i => (i * 2).toString).foreach(probe.expectNext) } "work with slow flow init" in assertAllStagesStopped { val p = Promise[Flow[Int, Int, NotUsed]]() val sourceProbe = TestPublisher.manualProbe[Int]() val flowProbe = Source.fromPublisher(sourceProbe) - .via(Flow.lazyInitAsync[Int, Int, NotUsed](() ⇒ p.future)) + .via(Flow.lazyInitAsync[Int, Int, NotUsed](() => p.future)) .runWith(TestSink.probe[Int]) val sourceSub = sourceProbe.expectSubscription() @@ -53,7 +53,7 @@ class LazyFlowSpec extends StreamSpec { p.success(Flow[Int]) flowProbe.request(99) flowProbe.expectNext(0) - (1 to 10).foreach(i ⇒ { + (1 to 10).foreach(i => { sourceSub.sendNext(i) flowProbe.expectNext(i) }) @@ -63,7 +63,7 @@ class LazyFlowSpec extends StreamSpec { "complete when there was no elements in the stream" in assertAllStagesStopped { def flowMaker() = flowF val probe = Source.empty - .via(Flow.lazyInitAsync(() ⇒ flowMaker)) + .via(Flow.lazyInitAsync(() => flowMaker)) .runWith(TestSink.probe[Int]) probe.request(1).expectComplete() } @@ -71,7 +71,7 @@ class LazyFlowSpec extends StreamSpec { "complete normally when upstream completes BEFORE the stage has switched to the inner flow" in assertAllStagesStopped { val promise = Promise[Flow[Int, Int, NotUsed]] val (pub, sub) = TestSource.probe[Int] - .viaMat(Flow.lazyInitAsync(() ⇒ promise.future))(Keep.left) + .viaMat(Flow.lazyInitAsync(() => promise.future))(Keep.left) .toMat(TestSink.probe)(Keep.both) .run() sub.request(1) @@ -82,7 +82,7 @@ class LazyFlowSpec extends StreamSpec { "complete normally when upstream completes AFTER the stage has switched to the inner flow" in assertAllStagesStopped { val (pub, sub) = TestSource.probe[Int] - .viaMat(Flow.lazyInitAsync(() ⇒ Future.successful(Flow[Int])))(Keep.left) + .viaMat(Flow.lazyInitAsync(() => Future.successful(Flow[Int])))(Keep.left) .toMat(TestSink.probe)(Keep.both) .run() sub.request(1) @@ -95,7 +95,7 @@ class LazyFlowSpec extends StreamSpec { "fail gracefully when flow factory method failed" in assertAllStagesStopped { val sourceProbe = TestPublisher.manualProbe[Int]() val probe = Source.fromPublisher(sourceProbe) - .via(Flow.lazyInitAsync[Int, Int, NotUsed](() ⇒ throw ex)) + .via(Flow.lazyInitAsync[Int, Int, NotUsed](() => throw ex)) .runWith(TestSink.probe[Int]) val sourceSub = sourceProbe.expectSubscription() @@ -109,7 +109,7 @@ class LazyFlowSpec extends StreamSpec { "fail gracefully when upstream failed" in assertAllStagesStopped { val sourceProbe = TestPublisher.manualProbe[Int]() val probe = Source.fromPublisher(sourceProbe) - .via(Flow.lazyInitAsync(() ⇒ flowF)) + .via(Flow.lazyInitAsync(() => flowF)) .runWith(TestSink.probe) val sourceSub = sourceProbe.expectSubscription() @@ -124,7 +124,7 @@ class LazyFlowSpec extends StreamSpec { "fail gracefully when factory future failed" in assertAllStagesStopped { val sourceProbe = TestPublisher.manualProbe[Int]() val flowProbe = Source.fromPublisher(sourceProbe) - .via(Flow.lazyInitAsync[Int, Int, NotUsed](() ⇒ Future.failed(ex))) + .via(Flow.lazyInitAsync[Int, Int, NotUsed](() => Future.failed(ex))) .runWith(TestSink.probe) val sourceSub = sourceProbe.expectSubscription() @@ -136,7 +136,7 @@ class LazyFlowSpec extends StreamSpec { "cancel upstream when the downstream is cancelled" in assertAllStagesStopped { val sourceProbe = TestPublisher.manualProbe[Int]() val probe = Source.fromPublisher(sourceProbe) - .via(Flow.lazyInitAsync[Int, Int, NotUsed](() ⇒ flowF)) + .via(Flow.lazyInitAsync[Int, Int, NotUsed](() => flowF)) .runWith(TestSink.probe[Int]) val sourceSub = sourceProbe.expectSubscription() @@ -153,11 +153,11 @@ class LazyFlowSpec extends StreamSpec { val msg = "fail!" val matFail = TE(msg) val result = Source.single("whatever") - .viaMat(Flow.lazyInitAsync(() ⇒ throw matFail))(Keep.right) + .viaMat(Flow.lazyInitAsync(() => throw matFail))(Keep.right) .toMat(Sink.ignore)(Keep.left) .run() - ScalaFutures.whenReady(result.failed) { e ⇒ + ScalaFutures.whenReady(result.failed) { e => e.getMessage shouldBe msg } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazySinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazySinkSpec.scala index 329e1f4368..58666d529e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazySinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazySinkSpec.scala @@ -28,7 +28,7 @@ class LazySinkSpec extends StreamSpec { "A LazySink" must { "work in happy case" in assertAllStagesStopped { - val futureProbe = Source(0 to 10).runWith(Sink.lazyInitAsync(() ⇒ Future.successful(TestSink.probe[Int]))) + val futureProbe = Source(0 to 10).runWith(Sink.lazyInitAsync(() => Future.successful(TestSink.probe[Int]))) val probe = Await.result(futureProbe, remainingOrDefault).get probe.request(100) (0 to 10).foreach(probe.expectNext) @@ -37,7 +37,7 @@ class LazySinkSpec extends StreamSpec { "work with slow sink init" in assertAllStagesStopped { val p = Promise[Sink[Int, Probe[Int]]]() val sourceProbe = TestPublisher.manualProbe[Int]() - val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync(() ⇒ p.future)) + val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync(() => p.future)) val sourceSub = sourceProbe.expectSubscription() sourceSub.expectRequest(1) @@ -50,7 +50,7 @@ class LazySinkSpec extends StreamSpec { val probe = Await.result(futureProbe, remainingOrDefault).get probe.request(100) probe.expectNext(0) - (1 to 10).foreach(i ⇒ { + (1 to 10).foreach(i => { sourceSub.sendNext(i) probe.expectNext(i) }) @@ -58,13 +58,13 @@ class LazySinkSpec extends StreamSpec { } "complete when there was no elements in stream" in assertAllStagesStopped { - val futureProbe = Source.empty.runWith(Sink.lazyInitAsync(() ⇒ Future.successful(Sink.fold[Int, Int](0)(_ + _)))) + val futureProbe = Source.empty.runWith(Sink.lazyInitAsync(() => Future.successful(Sink.fold[Int, Int](0)(_ + _)))) val futureResult = Await.result(futureProbe, remainingOrDefault) futureResult should ===(None) } "complete normally when upstream is completed" in assertAllStagesStopped { - val futureProbe = Source.single(1).runWith(Sink.lazyInitAsync(() ⇒ Future.successful(TestSink.probe[Int]))) + val futureProbe = Source.single(1).runWith(Sink.lazyInitAsync(() => Future.successful(TestSink.probe[Int]))) val futureResult = Await.result(futureProbe, remainingOrDefault).get futureResult.request(1) .expectNext(1) @@ -73,7 +73,7 @@ class LazySinkSpec extends StreamSpec { "failed gracefully when sink factory method failed" in assertAllStagesStopped { val sourceProbe = TestPublisher.manualProbe[Int]() - val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync[Int, Probe[Int]](() ⇒ throw ex)) + val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync[Int, Probe[Int]](() => throw ex)) val sourceSub = sourceProbe.expectSubscription() sourceSub.expectRequest(1) @@ -84,7 +84,7 @@ class LazySinkSpec extends StreamSpec { "failed gracefully when upstream failed" in assertAllStagesStopped { val sourceProbe = TestPublisher.manualProbe[Int]() - val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync(() ⇒ Future.successful(TestSink.probe[Int]))) + val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync(() => Future.successful(TestSink.probe[Int]))) val sourceSub = sourceProbe.expectSubscription() sourceSub.expectRequest(1) @@ -98,7 +98,7 @@ class LazySinkSpec extends StreamSpec { "fail gracefully when factory future failed" in assertAllStagesStopped { val sourceProbe = TestPublisher.manualProbe[Int]() - val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync(() ⇒ Future.failed(ex))) + val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync(() => Future.failed(ex))) val sourceSub = sourceProbe.expectSubscription() sourceSub.expectRequest(1) @@ -108,7 +108,7 @@ class LazySinkSpec extends StreamSpec { "cancel upstream when internal sink is cancelled" in assertAllStagesStopped { val sourceProbe = TestPublisher.manualProbe[Int]() - val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync(() ⇒ Future.successful(TestSink.probe[Int]))) + val futureProbe = Source.fromPublisher(sourceProbe).runWith(Sink.lazyInitAsync(() => Future.successful(TestSink.probe[Int]))) val sourceSub = sourceProbe.expectSubscription() sourceSub.expectRequest(1) sourceSub.sendNext(0) @@ -133,7 +133,7 @@ class LazySinkSpec extends StreamSpec { val result = Source(List("whatever")) .runWith( Sink.lazyInitAsync[String, NotUsed]( - () ⇒ { println("create sink"); Future.successful(Sink.fromGraph(FailingInnerMat)) })) + () => { println("create sink"); Future.successful(Sink.fromGraph(FailingInnerMat)) })) result.failed.futureValue should ===(matFail) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazySourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazySourceSpec.scala index 2b042f80c0..369b84e0d6 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazySourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/LazySourceSpec.scala @@ -25,7 +25,7 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "A lazy source" should { "work like a normal source, happy path" in assertAllStagesStopped { - val result = Source.fromGraph(LazySource(() ⇒ Source(List(1, 2, 3)))).runWith(Sink.seq) + val result = Source.fromGraph(LazySource(() => Source(List(1, 2, 3)))).runWith(Sink.seq) result.futureValue should ===(Seq(1, 2, 3)) } @@ -33,14 +33,14 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "never construct the source when there was no demand" in assertAllStagesStopped { val probe = TestSubscriber.probe[Int]() val constructed = new AtomicBoolean(false) - val result = Source.fromGraph(LazySource { () ⇒ constructed.set(true); Source(List(1, 2, 3)) }).runWith(Sink.fromSubscriber(probe)) + val result = Source.fromGraph(LazySource { () => constructed.set(true); Source(List(1, 2, 3)) }).runWith(Sink.fromSubscriber(probe)) probe.cancel() constructed.get() should ===(false) } "fail the materialized value when downstream cancels without ever consuming any element" in assertAllStagesStopped { - val matF = Source.fromGraph(LazySource(() ⇒ Source(List(1, 2, 3)))) + val matF = Source.fromGraph(LazySource(() => Source(List(1, 2, 3)))) .toMat(Sink.cancelled)(Keep.left) .run() @@ -53,7 +53,7 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { val outProbe = TestSubscriber.probe[Int]() val inProbe = TestPublisher.probe[Int]() - Source.fromGraph(LazySource(() ⇒ Source.fromPublisher(inProbe))).runWith(Sink.fromSubscriber(outProbe)) + Source.fromGraph(LazySource(() => Source.fromPublisher(inProbe))).runWith(Sink.fromSubscriber(outProbe)) outProbe.request(1) inProbe.expectRequest() @@ -66,8 +66,8 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "materialize when the source has been created" in assertAllStagesStopped { val probe = TestSubscriber.probe[Int]() - val matF: Future[Done] = Source.fromGraph(LazySource { () ⇒ - Source(List(1, 2, 3)).mapMaterializedValue(_ ⇒ Done) + val matF: Future[Done] = Source.fromGraph(LazySource { () => + Source(List(1, 2, 3)).mapMaterializedValue(_ => Done) }).to(Sink.fromSubscriber(probe)) .run() @@ -83,7 +83,7 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { val outProbe = TestSubscriber.probe[Int]() val inProbe = TestPublisher.probe[Int]() - Source.fromGraph(LazySource(() ⇒ Source.fromPublisher(inProbe))).runWith(Sink.fromSubscriber(outProbe)) + Source.fromGraph(LazySource(() => Source.fromPublisher(inProbe))).runWith(Sink.fromSubscriber(outProbe)) outProbe.request(1) inProbe.expectRequest() @@ -103,7 +103,7 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { } } - val result = Source.lazily(() ⇒ Source.fromGraph(FailingInnerMat)).to(Sink.ignore).run() + val result = Source.lazily(() => Source.fromGraph(FailingInnerMat)).to(Sink.ignore).run() result.failed.futureValue should ===(matFail) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/MaybeSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/MaybeSourceSpec.scala index 72982310fa..bcd104e5c6 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/MaybeSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/MaybeSourceSpec.scala @@ -36,8 +36,8 @@ class MaybeSourceSpec extends StreamSpec with DefaultTimeout { } "allow external triggering of empty completion" in assertAllStagesStopped { - val neverSource = Source.maybe[Int].filter(_ ⇒ false) - val counterSink = Sink.fold[Int, Int](0) { (acc, _) ⇒ acc + 1 } + val neverSource = Source.maybe[Int].filter(_ => false) + val counterSink = Sink.fold[Int, Int](0) { (acc, _) => acc + 1 } val (neverPromise, counterFuture) = neverSource.toMat(counterSink)(Keep.both).run() @@ -71,7 +71,7 @@ class MaybeSourceSpec extends StreamSpec with DefaultTimeout { "allow external triggering of onError" in assertAllStagesStopped { val neverSource = Source.maybe[Int] - val counterSink = Sink.fold[Int, Int](0) { (acc, _) ⇒ acc + 1 } + val counterSink = Sink.fold[Int, Int](0) { (acc, _) => acc + 1 } val (neverPromise, counterFuture) = neverSource.toMat(counterSink)(Keep.both).run() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/PublisherSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/PublisherSinkSpec.scala index b70b35a77d..77518a1c4b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/PublisherSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/PublisherSinkSpec.scala @@ -20,7 +20,7 @@ class PublisherSinkSpec extends StreamSpec { "be unique when created twice" in assertAllStagesStopped { - val (pub1, pub2) = RunnableGraph.fromGraph(GraphDSL.create(Sink.asPublisher[Int](false), Sink.asPublisher[Int](false))(Keep.both) { implicit b ⇒ (p1, p2) ⇒ + val (pub1, pub2) = RunnableGraph.fromGraph(GraphDSL.create(Sink.asPublisher[Int](false), Sink.asPublisher[Int](false))(Keep.both) { implicit b => (p1, p2) => import GraphDSL.Implicits._ val bcast = b.add(Broadcast[Int](2)) @@ -47,7 +47,7 @@ class PublisherSinkSpec extends StreamSpec { "be able to use Publisher in materialized value transformation" in { val f = Source(1 to 3).runWith( - Sink.asPublisher[Int](false).mapMaterializedValue(p ⇒ Source.fromPublisher(p).runFold(0)(_ + _))) + Sink.asPublisher[Int](false).mapMaterializedValue(p => Source.fromPublisher(p).runFold(0)(_ + _))) Await.result(f, 3.seconds) should be(6) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/QueueSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/QueueSinkSpec.scala index 716a0dcba9..c6ae88f006 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/QueueSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/QueueSinkSpec.scala @@ -28,7 +28,7 @@ class QueueSinkSpec extends StreamSpec { "send the elements as result of future" in assertAllStagesStopped { val expected = List(Some(1), Some(2), Some(3), None) val queue = Source(expected.flatten).runWith(Sink.queue()) - expected foreach { v ⇒ + expected foreach { v => queue.pull() pipeTo testActor expectMsg(v) } @@ -129,11 +129,11 @@ class QueueSinkSpec extends StreamSpec { .withAttributes(inputBuffer(bufferSize, bufferSize)) val bufferFullProbe = Promise[akka.Done.type] val queue = Source(1 to streamElementCount) - .alsoTo(Flow[Int].drop(bufferSize - 1).to(Sink.foreach(_ ⇒ bufferFullProbe.trySuccess(akka.Done)))) + .alsoTo(Flow[Int].drop(bufferSize - 1).to(Sink.foreach(_ => bufferFullProbe.trySuccess(akka.Done)))) .toMat(sink)(Keep.right) .run() bufferFullProbe.future.futureValue should ===(akka.Done) - for (i ← 1 to streamElementCount) { + for (i <- 1 to streamElementCount) { queue.pull() pipeTo testActor expectMsg(Some(i)) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/QueueSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/QueueSourceSpec.scala index 9807b016fe..d383ffee1f 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/QueueSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/QueueSourceSpec.scala @@ -38,7 +38,7 @@ class QueueSourceSpec extends StreamSpec { val s = TestSubscriber.manualProbe[Int]() val queue = Source.queue(10, OverflowStrategy.fail).to(Sink.fromSubscriber(s)).run() val sub = s.expectSubscription - for (i ← 1 to 3) { + for (i <- 1 to 3) { sub.request(1) assertSuccess(queue.offer(i)) s.expectNext(i) @@ -85,15 +85,15 @@ class QueueSourceSpec extends StreamSpec { val s = TestSubscriber.manualProbe[Int]() val queue = Source.queue(100, OverflowStrategy.dropHead).to(Sink.fromSubscriber(s)).run() val sub = s.expectSubscription - for (n ← 1 to 20) assertSuccess(queue.offer(n)) + for (n <- 1 to 20) assertSuccess(queue.offer(n)) sub.request(10) - for (n ← 1 to 10) assertSuccess(queue.offer(n)) + for (n <- 1 to 10) assertSuccess(queue.offer(n)) sub.request(10) - for (n ← 11 to 20) assertSuccess(queue.offer(n)) + for (n <- 11 to 20) assertSuccess(queue.offer(n)) - for (n ← 200 to 399) assertSuccess(queue.offer(n)) + for (n <- 200 to 399) assertSuccess(queue.offer(n)) sub.request(100) - for (n ← 300 to 399) assertSuccess(queue.offer(n)) + for (n <- 300 to 399) assertSuccess(queue.offer(n)) sub.cancel() } @@ -167,7 +167,7 @@ class QueueSourceSpec extends StreamSpec { "fail offer future if user does not wait in backpressure mode" in assertAllStagesStopped { val (queue, probe) = Source.queue[Int](5, OverflowStrategy.backpressure).toMat(TestSink.probe)(Keep.both).run() - for (i ← 1 to 5) assertSuccess(queue.offer(i)) + for (i <- 1 to 5) assertSuccess(queue.offer(i)) queue.offer(6).pipeTo(testActor) @@ -324,7 +324,7 @@ class QueueSourceSpec extends StreamSpec { Source.queue[Unit](10, OverflowStrategy.fail).toMat(TestSink.probe)(Keep.both).run() intercept[StreamDetachedException] { Await.result( - (1 to 15).map(_ ⇒ queue.offer(())).last, 3.seconds) + (1 to 15).map(_ => queue.offer(())).last, 3.seconds) } } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/RestartSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/RestartSpec.scala index 4a28afd202..2dc716eb2a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/RestartSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/RestartSpec.scala @@ -33,7 +33,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "A restart with backoff source" should { "run normally" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() Source.repeat("a") }.runWith(TestSink.probe) @@ -51,7 +51,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "restart on completion" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() Source(List("a", "b")) }.runWith(TestSink.probe) @@ -69,12 +69,12 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "restart on failure" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() Source(List("a", "b", "c")) .map { - case "c" ⇒ throw TE("failed") - case other ⇒ other + case "c" => throw TE("failed") + case other => other } }.runWith(TestSink.probe) @@ -91,7 +91,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "backoff before restart" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.withBackoff(minBackoff, maxBackoff, 0) { () ⇒ + val probe = RestartSource.withBackoff(minBackoff, maxBackoff, 0) { () => created.incrementAndGet() Source(List("a", "b")) }.runWith(TestSink.probe) @@ -113,7 +113,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "reset exponential backoff back to minimum when source runs for at least minimum backoff without completing" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.withBackoff(minBackoff, maxBackoff, 0) { () ⇒ + val probe = RestartSource.withBackoff(minBackoff, maxBackoff, 0) { () => created.incrementAndGet() Source(List("a", "b")) }.runWith(TestSink.probe) @@ -145,9 +145,9 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "cancel the currently running source when cancelled" in assertAllStagesStopped { val created = new AtomicInteger() val promise = Promise[Done]() - val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() - Source.repeat("a").watchTermination() { (_, term) ⇒ + Source.repeat("a").watchTermination() { (_, term) => promise.completeWith(term) } }.runWith(TestSink.probe) @@ -164,7 +164,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "not restart the source when cancelled while backing off" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.withBackoff(minBackoff, maxBackoff, 0) { () ⇒ + val probe = RestartSource.withBackoff(minBackoff, maxBackoff, 0) { () => created.incrementAndGet() Source.single("a") }.runWith(TestSink.probe) @@ -181,12 +181,12 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "stop on completion if it should only be restarted in failures" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.onFailuresWithBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val probe = RestartSource.onFailuresWithBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() Source(List("a", "b", "c")) .map { - case "c" ⇒ if (created.get() == 1) throw TE("failed") else "c" - case other ⇒ other + case "c" => if (created.get() == 1) throw TE("failed") else "c" + case other => other } }.runWith(TestSink.probe) @@ -205,12 +205,12 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "restart on failure when only due to failures should be restarted" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.onFailuresWithBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val probe = RestartSource.onFailuresWithBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() Source(List("a", "b", "c")) .map { - case "c" ⇒ throw TE("failed") - case other ⇒ other + case "c" => throw TE("failed") + case other => other } }.runWith(TestSink.probe) @@ -228,7 +228,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "not restart the source when maxRestarts is reached" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0, maxRestarts = 1) { () ⇒ + val probe = RestartSource.withBackoff(shortMinBackoff, shortMaxBackoff, 0, maxRestarts = 1) { () => created.incrementAndGet() Source.single("a") }.runWith(TestSink.probe) @@ -244,7 +244,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "reset maxRestarts when source runs for at least minimum backoff without completing" in assertAllStagesStopped { val created = new AtomicInteger() - val probe = RestartSource.withBackoff(minBackoff, maxBackoff, 0, maxRestarts = 2) { () ⇒ + val probe = RestartSource.withBackoff(minBackoff, maxBackoff, 0, maxRestarts = 2) { () => created.incrementAndGet() Source(List("a")) }.runWith(TestSink.probe) @@ -272,7 +272,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "run normally" in assertAllStagesStopped { val created = new AtomicInteger() val result = Promise[Seq[String]]() - val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() Sink.seq.mapMaterializedValue(result.completeWith) })(Keep.left).run() @@ -289,7 +289,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "restart on cancellation" in assertAllStagesStopped { val created = new AtomicInteger() val (queue, sinkProbe) = TestSource.probe[String].toMat(TestSink.probe)(Keep.both).run() - val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() Flow[String].takeWhile(_ != "cancel", inclusive = true) .to(Sink.foreach(queue.sendNext)) @@ -313,7 +313,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "backoff before restart" in assertAllStagesStopped { val created = new AtomicInteger() val (queue, sinkProbe) = TestSource.probe[String].toMat(TestSink.probe)(Keep.both).run() - val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(minBackoff, maxBackoff, 0) { () ⇒ + val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(minBackoff, maxBackoff, 0) { () => created.incrementAndGet() Flow[String].takeWhile(_ != "cancel", inclusive = true) .to(Sink.foreach(queue.sendNext)) @@ -338,7 +338,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "reset exponential backoff back to minimum when sink runs for at least minimum backoff without completing" in assertAllStagesStopped { val created = new AtomicInteger() val (queue, sinkProbe) = TestSource.probe[String].toMat(TestSink.probe)(Keep.both).run() - val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(minBackoff, maxBackoff, 0) { () ⇒ + val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(minBackoff, maxBackoff, 0) { () => created.incrementAndGet() Flow[String].takeWhile(_ != "cancel", inclusive = true) .to(Sink.foreach(queue.sendNext)) @@ -378,7 +378,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "not restart the sink when completed while backing off" in assertAllStagesStopped { val created = new AtomicInteger() val (queue, sinkProbe) = TestSource.probe[String].toMat(TestSink.probe)(Keep.both).run() - val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(minBackoff, maxBackoff, 0) { () ⇒ + val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(minBackoff, maxBackoff, 0) { () => created.incrementAndGet() Flow[String].takeWhile(_ != "cancel", inclusive = true) .to(Sink.foreach(queue.sendNext)) @@ -401,7 +401,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "not restart the sink when maxRestarts is reached" in assertAllStagesStopped { val created = new AtomicInteger() val (queue, sinkProbe) = TestSource.probe[String].toMat(TestSink.probe)(Keep.both).run() - val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(shortMinBackoff, shortMaxBackoff, 0, maxRestarts = 1) { () ⇒ + val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(shortMinBackoff, shortMaxBackoff, 0, maxRestarts = 1) { () => created.incrementAndGet() Flow[String].takeWhile(_ != "cancel", inclusive = true) .to(Sink.foreach(queue.sendNext)) @@ -423,7 +423,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "reset maxRestarts when sink runs for at least minimum backoff without completing" in assertAllStagesStopped { val created = new AtomicInteger() val (queue, sinkProbe) = TestSource.probe[String].toMat(TestSink.probe)(Keep.both).run() - val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(minBackoff, maxBackoff, 0, maxRestarts = 2) { () ⇒ + val probe = TestSource.probe[String].toMat(RestartSink.withBackoff(minBackoff, maxBackoff, 0, maxRestarts = 2) { () => created.incrementAndGet() Flow[String].takeWhile(_ != "cancel", inclusive = true) .to(Sink.foreach(queue.sendNext)) @@ -457,11 +457,11 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "A restart with backoff flow" should { // helps reuse all the setupFlow code for both methods: withBackoff, and onlyOnFailuresWithBackoff - def RestartFlowFactory[In, Out](onlyOnFailures: Boolean): (FiniteDuration, FiniteDuration, Double, Int) ⇒ (() ⇒ Flow[In, Out, _]) ⇒ Flow[In, Out, NotUsed] = if (onlyOnFailures) { + def RestartFlowFactory[In, Out](onlyOnFailures: Boolean): (FiniteDuration, FiniteDuration, Double, Int) => (() => Flow[In, Out, _]) => Flow[In, Out, NotUsed] = if (onlyOnFailures) { RestartFlow.onFailuresWithBackoff } else { // choose the correct backoff method - (minBackoff, maxBackoff, randomFactor, maxRestarts) ⇒ RestartFlow.withBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) + (minBackoff, maxBackoff, randomFactor, maxRestarts) => RestartFlow.withBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) } def setupFlow(minBackoff: FiniteDuration, maxBackoff: FiniteDuration, maxRestarts: Int = -1, onlyOnFailures: Boolean = false) = { @@ -475,27 +475,27 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 // We can't just use ordinary probes here because we're expecting them to get started/restarted. Instead, we // simply use the probes as a message bus for feeding and capturing events. - val (source, sink) = TestSource.probe[String].viaMat(RestartFlowFactory(onlyOnFailures)(minBackoff, maxBackoff, 0, maxRestarts) { () ⇒ + val (source, sink) = TestSource.probe[String].viaMat(RestartFlowFactory(onlyOnFailures)(minBackoff, maxBackoff, 0, maxRestarts) { () => created.incrementAndGet() Flow.fromSinkAndSource( Flow[String] .takeWhile(_ != "cancel") .map { - case "in error" ⇒ throw TE("in error") - case other ⇒ other + case "in error" => throw TE("in error") + case other => other } .to(Sink.foreach(flowInSource.sendNext) .mapMaterializedValue(_.onComplete { - case Success(_) ⇒ flowInSource.sendNext("in complete") - case Failure(_) ⇒ flowInSource.sendNext("in error") + case Success(_) => flowInSource.sendNext("in complete") + case Failure(_) => flowInSource.sendNext("in error") })), flowOutSource .takeWhile(_ != "complete") .map { - case "error" ⇒ throw TE("error") - case other ⇒ other - }.watchTermination()((_, term) ⇒ - term.foreach(_ ⇒ { + case "error" => throw TE("error") + case other => other + }.watchTermination()((_, term) => + term.foreach(_ => { flowInSource.sendNext("out complete") }))) })(Keep.left).toMat(TestSink.probe[String])(Keep.both).run() @@ -505,7 +505,7 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "run normally" in assertAllStagesStopped { val created = new AtomicInteger() - val (source, sink) = TestSource.probe[String].viaMat(RestartFlow.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () ⇒ + val (source, sink) = TestSource.probe[String].viaMat(RestartFlow.withBackoff(shortMinBackoff, shortMaxBackoff, 0) { () => created.incrementAndGet() Flow[String] })(Keep.left).toMat(TestSink.probe[String])(Keep.both).run() @@ -746,12 +746,12 @@ class RestartSpec extends StreamSpec(Map("akka.test.single-expect-default" -> "1 "onFailuresWithBackoff, wrapped flow exception should restart configured times" in { val flowCreations = new AtomicInteger(0) - val failsSomeTimes = Flow[Int].map { i ⇒ + val failsSomeTimes = Flow[Int].map { i => if (i % 3 == 0) throw TE("fail") else i } val restartOnFailures = - RestartFlow.onFailuresWithBackoff(1.second, 2.seconds, 0.2, 2)(() ⇒ { + RestartFlow.onFailuresWithBackoff(1.second, 2.seconds, 0.2, 2)(() => { flowCreations.incrementAndGet() failsSomeTimes }).addAttributes(Attributes(Delay(100.millis))) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ReverseArrowSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ReverseArrowSpec.scala index f49aecf621..0fef44af0b 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ReverseArrowSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/ReverseArrowSpec.scala @@ -19,14 +19,14 @@ class ReverseArrowSpec extends StreamSpec { "Reverse Arrows in the Graph DSL" must { "work from Inlets" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => s.in <~ source ClosedShape }).run(), 1.second) should ===(Seq(1, 2, 3)) } "work from SinkShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => s <~ source ClosedShape }).run(), 1.second) should ===(Seq(1, 2, 3)) @@ -34,7 +34,7 @@ class ReverseArrowSpec extends StreamSpec { "work from Sink" in { val sub = TestSubscriber.manualProbe[Int] - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => Sink.fromSubscriber(sub) <~ source ClosedShape }).run() @@ -44,7 +44,7 @@ class ReverseArrowSpec extends StreamSpec { } "not work from Outlets" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val o: Outlet[Int] = b.add(source).out "o <~ source" shouldNot compile sink <~ o @@ -53,7 +53,7 @@ class ReverseArrowSpec extends StreamSpec { } "not work from SourceShape" in { - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => val o: SourceShape[Int] = b.add(source) "o <~ source" shouldNot compile sink <~ o @@ -66,7 +66,7 @@ class ReverseArrowSpec extends StreamSpec { } "work from FlowShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val f: FlowShape[Int, Int] = b.add(Flow[Int]) f <~ source f ~> s @@ -75,7 +75,7 @@ class ReverseArrowSpec extends StreamSpec { } "work from UniformFanInShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val f: UniformFanInShape[Int, Int] = b.add(Merge[Int](2)) f <~ source f <~ Source.empty @@ -85,7 +85,7 @@ class ReverseArrowSpec extends StreamSpec { } "work from UniformFanOutShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val f: UniformFanOutShape[Int, Int] = b.add(Broadcast[Int](2)) f <~ source f ~> Sink.ignore @@ -95,7 +95,7 @@ class ReverseArrowSpec extends StreamSpec { } "work towards Outlets" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val o: Outlet[Int] = b.add(source).out s <~ o ClosedShape @@ -103,7 +103,7 @@ class ReverseArrowSpec extends StreamSpec { } "work towards SourceShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val o: SourceShape[Int] = b.add(source) s <~ o ClosedShape @@ -111,14 +111,14 @@ class ReverseArrowSpec extends StreamSpec { } "work towards Source" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => s <~ source ClosedShape }).run(), 1.second) should ===(Seq(1, 2, 3)) } "work towards FlowShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val f: FlowShape[Int, Int] = b.add(Flow[Int]) s <~ f source ~> f @@ -127,7 +127,7 @@ class ReverseArrowSpec extends StreamSpec { } "work towards UniformFanInShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val f: UniformFanInShape[Int, Int] = b.add(Merge[Int](2)) s <~ f Source.empty ~> f @@ -137,7 +137,7 @@ class ReverseArrowSpec extends StreamSpec { } "fail towards already full UniformFanInShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val f: UniformFanInShape[Int, Int] = b.add(Merge[Int](2)) val src = b.add(source) Source.empty ~> f @@ -148,7 +148,7 @@ class ReverseArrowSpec extends StreamSpec { } "work towards UniformFanOutShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val f: UniformFanOutShape[Int, Int] = b.add(Broadcast[Int](2)) s <~ f Sink.ignore <~ f @@ -158,7 +158,7 @@ class ReverseArrowSpec extends StreamSpec { } "fail towards already full UniformFanOutShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => val f: UniformFanOutShape[Int, Int] = b.add(Broadcast[Int](2)) val sink2: SinkShape[Int] = b.add(Sink.ignore) val src = b.add(source) @@ -170,14 +170,14 @@ class ReverseArrowSpec extends StreamSpec { } "work across a Flow" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => s <~ Flow[Int] <~ source ClosedShape }).run(), 1.second) should ===(Seq(1, 2, 3)) } "work across a FlowShape" in { - Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b ⇒ s ⇒ + Await.result(RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit b => s => s <~ b.add(Flow[Int]) <~ source ClosedShape }).run(), 1.second) should ===(Seq(1, 2, 3)) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SeqSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SeqSinkSpec.scala index e57d0c0165..5503a0e4b0 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SeqSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SeqSinkSpec.scala @@ -27,7 +27,7 @@ class SeqSinkSpec extends StreamSpec { "return an empty Seq[T] from an empty Source" in { val input: immutable.Seq[Int] = Nil - val future: Future[immutable.Seq[Int]] = Source.fromIterator(() ⇒ input.iterator).runWith(Sink.seq) + val future: Future[immutable.Seq[Int]] = Source.fromIterator(() => input.iterator).runWith(Sink.seq) val result: immutable.Seq[Int] = Await.result(future, remainingOrDefault) result should be(input) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkAsJavaStreamSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkAsJavaStreamSpec.scala index c27a1548ff..b217dfb04a 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkAsJavaStreamSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkAsJavaStreamSpec.scala @@ -28,7 +28,7 @@ class SinkAsJavaStreamSpec extends StreamSpec(UnboundedMailboxConfig) { } "fail if parent stream is failed" in { - val javaSource = Source(1 to 100).map(_ ⇒ throw TE("")).runWith(StreamConverters.asJavaStream()) + val javaSource = Source(1 to 100).map(_ => throw TE("")).runWith(StreamConverters.asJavaStream()) a[TE] shouldBe thrownBy { javaSource.findFirst() } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkForeachAsyncSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkForeachAsyncSpec.scala index 3dc2e60dd4..0a4f72e094 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkForeachAsyncSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkForeachAsyncSpec.scala @@ -25,7 +25,7 @@ class SinkForeachAsyncSpec extends StreamSpec { "A foreachAsync" must { "handle empty source" in assertAllStagesStopped { import system.dispatcher - val p = Source(List.empty[Int]).runWith(Sink.foreachAsync(3)(a ⇒ Future {})) + val p = Source(List.empty[Int]).runWith(Sink.foreachAsync(3)(a => Future {})) Await.result(p, remainingOrDefault) } @@ -33,10 +33,10 @@ class SinkForeachAsyncSpec extends StreamSpec { implicit val ec = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(4)) val probe = TestProbe() - val latch = (1 to 4).map(_ → TestLatch(1)).toMap + val latch = (1 to 4).map(_ -> TestLatch(1)).toMap val sink: Sink[Int, Future[Done]] = { - Sink.foreachAsync(4) { n: Int ⇒ + Sink.foreachAsync(4) { n: Int => Future { Await.result(latch(n), remainingOrDefault) probe.ref ! n @@ -65,10 +65,10 @@ class SinkForeachAsyncSpec extends StreamSpec { implicit val ec = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(1)) val probe = TestProbe() - val latch = (1 to 4).map(_ → TestLatch(1)).toMap + val latch = (1 to 4).map(_ -> TestLatch(1)).toMap - val sink: Sink[() ⇒ Int, Future[Done]] = { - Sink.foreachAsync(1) { (n: () ⇒ Int) ⇒ + val sink: Sink[() => Int, Future[Done]] = { + Sink.foreachAsync(1) { (n: () => Int) => Future { Await.result(latch(n()), remainingOrDefault) probe.ref ! n() @@ -143,8 +143,8 @@ class SinkForeachAsyncSpec extends StreamSpec { import system.dispatcher val probe = TestProbe() - val latch = (1 to 4).map(_ → TestLatch(1)).toMap - val p = Source(1 to 4).runWith(Sink.foreachAsync(4)((n: Int) ⇒ { + val latch = (1 to 4).map(_ -> TestLatch(1)).toMap + val p = Source(1 to 4).runWith(Sink.foreachAsync(4)((n: Int) => { Future { Await.ready(latch(n), 5.seconds) probe.ref ! n @@ -170,9 +170,9 @@ class SinkForeachAsyncSpec extends StreamSpec { import system.dispatcher val probe = TestProbe() - val latch = (1 to 5).map(_ → TestLatch()).toMap + val latch = (1 to 5).map(_ -> TestLatch()).toMap - val p = Source(1 to 5).runWith(Sink.foreachAsync(4)((n: Int) ⇒ { + val p = Source(1 to 5).runWith(Sink.foreachAsync(4)((n: Int) => { Future { probe.ref ! n Await.ready(latch(n), 5.seconds) @@ -183,7 +183,7 @@ class SinkForeachAsyncSpec extends StreamSpec { assert(!p.isCompleted) - for (i ← 1 to 4) latch(i).countDown() + for (i <- 1 to 4) latch(i).countDown() latch(5).countDown() probe.expectMsg(5) @@ -199,7 +199,7 @@ class SinkForeachAsyncSpec extends StreamSpec { val probe = TestProbe() val latch = TestLatch(1) - val p = Source(1 to 5).runWith(Sink.foreachAsync(4)((n: Int) ⇒ { + val p = Source(1 to 5).runWith(Sink.foreachAsync(4)((n: Int) => { Future { if (n == 3) throw new RuntimeException("err1") with NoStackTrace else { @@ -222,7 +222,7 @@ class SinkForeachAsyncSpec extends StreamSpec { val element4Latch = new CountDownLatch(1) val errorLatch = new CountDownLatch(2) - val p = Source.fromIterator(() ⇒ Iterator.from(1)).runWith(Sink.foreachAsync(3)((n: Int) ⇒ { + val p = Source.fromIterator(() => Iterator.from(1)).runWith(Sink.foreachAsync(3)((n: Int) => { Future { if (n == 3) { // Error will happen only after elements 1, 2 has been processed diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkForeachParallelSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkForeachParallelSpec.scala index 2eecc62428..ef959b6c2f 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkForeachParallelSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkForeachParallelSpec.scala @@ -26,8 +26,8 @@ class SinkForeachParallelSpec extends StreamSpec { import system.dispatcher val probe = TestProbe() - val latch = (1 to 4).map(_ → TestLatch(1)).toMap - val p = Source(1 to 4).runWith(Sink.foreachParallel(4)((n: Int) ⇒ { + val latch = (1 to 4).map(_ -> TestLatch(1)).toMap + val p = Source(1 to 4).runWith(Sink.foreachParallel(4)((n: Int) => { Await.ready(latch(n), 5.seconds) probe.ref ! n })) @@ -51,9 +51,9 @@ class SinkForeachParallelSpec extends StreamSpec { import system.dispatcher val probe = TestProbe() - val latch = (1 to 5).map(_ → TestLatch()).toMap + val latch = (1 to 5).map(_ -> TestLatch()).toMap - val p = Source(1 to 5).runWith(Sink.foreachParallel(4)((n: Int) ⇒ { + val p = Source(1 to 5).runWith(Sink.foreachParallel(4)((n: Int) => { probe.ref ! n Await.ready(latch(n), 5.seconds) })) @@ -62,7 +62,7 @@ class SinkForeachParallelSpec extends StreamSpec { assert(!p.isCompleted) - for (i ← 1 to 4) latch(i).countDown() + for (i <- 1 to 4) latch(i).countDown() latch(5).countDown() probe.expectMsg(5) @@ -78,7 +78,7 @@ class SinkForeachParallelSpec extends StreamSpec { val probe = TestProbe() val latch = TestLatch(1) - val p = Source(1 to 5).runWith(Sink.foreachParallel(4)((n: Int) ⇒ { + val p = Source(1 to 5).runWith(Sink.foreachParallel(4)((n: Int) => { if (n == 3) throw new RuntimeException("err1") with NoStackTrace else { probe.ref ! n @@ -99,7 +99,7 @@ class SinkForeachParallelSpec extends StreamSpec { val element4Latch = new CountDownLatch(1) val errorLatch = new CountDownLatch(2) - val p = Source.fromIterator(() ⇒ Iterator.from(1)).runWith(Sink.foreachParallel(3)((n: Int) ⇒ { + val p = Source.fromIterator(() => Iterator.from(1)).runWith(Sink.foreachParallel(3)((n: Int) => { if (n == 3) { // Error will happen only after elements 1, 2 has been processed errorLatch.await(5, TimeUnit.SECONDS) @@ -122,7 +122,7 @@ class SinkForeachParallelSpec extends StreamSpec { "handle empty source" in assertAllStagesStopped { import system.dispatcher - val p = Source(List.empty[Int]).runWith(Sink.foreachParallel(3)(a ⇒ ())) + val p = Source(List.empty[Int]).runWith(Sink.foreachParallel(3)(a => ())) Await.result(p, 200.seconds) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkSpec.scala index d56fc8f31e..be4820890e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SinkSpec.scala @@ -30,38 +30,38 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "A Sink" must { "be composable without importing modules" in { val probes = Array.fill(3)(TestSubscriber.manualProbe[Int]) - val sink = Sink.fromGraph(GraphDSL.create() { implicit b ⇒ + val sink = Sink.fromGraph(GraphDSL.create() { implicit b => val bcast = b.add(Broadcast[Int](3)) - for (i ← 0 to 2) bcast.out(i).filter(_ == i) ~> Sink.fromSubscriber(probes(i)) + for (i <- 0 to 2) bcast.out(i).filter(_ == i) ~> Sink.fromSubscriber(probes(i)) SinkShape(bcast.in) }) Source(List(0, 1, 2)).runWith(sink) val subscriptions = probes.map(_.expectSubscription()) - subscriptions.foreach { s ⇒ s.request(3) } - probes.zipWithIndex.foreach { case (p, i) ⇒ p.expectNext(i) } - probes.foreach { case p ⇒ p.expectComplete() } + subscriptions.foreach { s => s.request(3) } + probes.zipWithIndex.foreach { case (p, i) => p.expectNext(i) } + probes.foreach { case p => p.expectComplete() } } "be composable with importing 1 module" in { val probes = Array.fill(3)(TestSubscriber.manualProbe[Int]) - val sink = Sink.fromGraph(GraphDSL.create(Sink.fromSubscriber(probes(0))) { implicit b ⇒ s0 ⇒ + val sink = Sink.fromGraph(GraphDSL.create(Sink.fromSubscriber(probes(0))) { implicit b => s0 => val bcast = b.add(Broadcast[Int](3)) bcast.out(0) ~> Flow[Int].filter(_ == 0) ~> s0.in - for (i ← 1 to 2) bcast.out(i).filter(_ == i) ~> Sink.fromSubscriber(probes(i)) + for (i <- 1 to 2) bcast.out(i).filter(_ == i) ~> Sink.fromSubscriber(probes(i)) SinkShape(bcast.in) }) Source(List(0, 1, 2)).runWith(sink) val subscriptions = probes.map(_.expectSubscription()) - subscriptions.foreach { s ⇒ s.request(3) } - probes.zipWithIndex.foreach { case (p, i) ⇒ p.expectNext(i) } - probes.foreach { case p ⇒ p.expectComplete() } + subscriptions.foreach { s => s.request(3) } + probes.zipWithIndex.foreach { case (p, i) => p.expectNext(i) } + probes.foreach { case p => p.expectComplete() } } "be composable with importing 2 modules" in { val probes = Array.fill(3)(TestSubscriber.manualProbe[Int]) - val sink = Sink.fromGraph(GraphDSL.create(Sink.fromSubscriber(probes(0)), Sink.fromSubscriber(probes(1)))(List(_, _)) { implicit b ⇒ (s0, s1) ⇒ + val sink = Sink.fromGraph(GraphDSL.create(Sink.fromSubscriber(probes(0)), Sink.fromSubscriber(probes(1)))(List(_, _)) { implicit b => (s0, s1) => val bcast = b.add(Broadcast[Int](3)) bcast.out(0).filter(_ == 0) ~> s0.in bcast.out(1).filter(_ == 1) ~> s1.in @@ -71,14 +71,14 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { Source(List(0, 1, 2)).runWith(sink) val subscriptions = probes.map(_.expectSubscription()) - subscriptions.foreach { s ⇒ s.request(3) } - probes.zipWithIndex.foreach { case (p, i) ⇒ p.expectNext(i) } - probes.foreach { case p ⇒ p.expectComplete() } + subscriptions.foreach { s => s.request(3) } + probes.zipWithIndex.foreach { case (p, i) => p.expectNext(i) } + probes.foreach { case p => p.expectComplete() } } "be composable with importing 3 modules" in { val probes = Array.fill(3)(TestSubscriber.manualProbe[Int]) - val sink = Sink.fromGraph(GraphDSL.create(Sink.fromSubscriber(probes(0)), Sink.fromSubscriber(probes(1)), Sink.fromSubscriber(probes(2)))(List(_, _, _)) { implicit b ⇒ (s0, s1, s2) ⇒ + val sink = Sink.fromGraph(GraphDSL.create(Sink.fromSubscriber(probes(0)), Sink.fromSubscriber(probes(1)), Sink.fromSubscriber(probes(2)))(List(_, _, _)) { implicit b => (s0, s1, s2) => val bcast = b.add(Broadcast[Int](3)) bcast.out(0).filter(_ == 0) ~> s0.in bcast.out(1).filter(_ == 1) ~> s1.in @@ -88,9 +88,9 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { Source(List(0, 1, 2)).runWith(sink) val subscriptions = probes.map(_.expectSubscription()) - subscriptions.foreach { s ⇒ s.request(3) } - probes.zipWithIndex.foreach { case (p, i) ⇒ p.expectNext(i) } - probes.foreach { case p ⇒ p.expectComplete() } + subscriptions.foreach { s => s.request(3) } + probes.zipWithIndex.foreach { case (p, i) => p.expectNext(i) } + probes.foreach { case p => p.expectComplete() } } "combine to many outputs with simplified API" in { @@ -101,11 +101,11 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { val subscriptions = probes.map(_.expectSubscription()) - subscriptions.foreach { s ⇒ s.request(1) } - probes.foreach { p ⇒ p.expectNext(0) } + subscriptions.foreach { s => s.request(1) } + probes.foreach { p => p.expectNext(0) } - subscriptions.foreach { s ⇒ s.request(2) } - probes.foreach { p ⇒ + subscriptions.foreach { s => s.request(2) } + probes.foreach { p => p.expectNextN(List(1, 2)) p.expectComplete } @@ -119,11 +119,11 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { val subscriptions = probes.map(_.expectSubscription()) - subscriptions.foreach { s ⇒ s.request(1) } - probes.foreach { p ⇒ p.expectNext(0) } + subscriptions.foreach { s => s.request(1) } + probes.foreach { p => p.expectNext(0) } - subscriptions.foreach { s ⇒ s.request(2) } - probes.foreach { p ⇒ + subscriptions.foreach { s => s.request(2) } + probes.foreach { p => p.expectNextN(List(1, 2)) p.expectComplete } @@ -187,10 +187,10 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "Java collector Sink" must { class TestCollector( - _supplier: () ⇒ Supplier[Array[Int]], - _accumulator: () ⇒ BiConsumer[Array[Int], Int], - _combiner: () ⇒ BinaryOperator[Array[Int]], - _finisher: () ⇒ function.Function[Array[Int], Int]) extends Collector[Int, Array[Int], Int] { + _supplier: () => Supplier[Array[Int]], + _accumulator: () => BiConsumer[Array[Int], Int], + _combiner: () => BinaryOperator[Array[Int]], + _finisher: () => function.Function[Array[Int], Int]) extends Collector[Int, Array[Int], Int] { override def supplier(): Supplier[Array[Int]] = _supplier() override def combiner(): BinaryOperator[Array[Int]] = _combiner() override def finisher(): function.Function[Array[Int], Int] = _finisher() @@ -219,19 +219,19 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { } "work in the happy case" in { - Source(1 to 100).map(_.toString).runWith(StreamConverters.javaCollector(() ⇒ Collectors.joining(", "))) + Source(1 to 100).map(_.toString).runWith(StreamConverters.javaCollector(() => Collectors.joining(", "))) .futureValue should ===((1 to 100).mkString(", ")) } "work parallelly in the happy case" in { Source(1 to 100).runWith(StreamConverters .javaCollectorParallelUnordered(4)( - () ⇒ Collectors.summingInt[Int](intIdentity))) + () => Collectors.summingInt[Int](intIdentity))) .futureValue.toInt should ===(5050) } "be reusable" in { - val sink = StreamConverters.javaCollector[Int, Integer](() ⇒ Collectors.summingInt[Int](intIdentity)) + val sink = StreamConverters.javaCollector[Int, Integer](() => Collectors.summingInt[Int](intIdentity)) Source(1 to 4).runWith(sink).futureValue.toInt should ===(10) // Collector has state so it preserves all previous elements that went though @@ -239,7 +239,7 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { } "be reusable with parallel version" in { - val sink = StreamConverters.javaCollectorParallelUnordered(4)(() ⇒ Collectors.summingInt[Int](intIdentity)) + val sink = StreamConverters.javaCollectorParallelUnordered(4)(() => Collectors.summingInt[Int](intIdentity)) Source(1 to 4).runWith(sink).futureValue.toInt should ===(10) Source(4 to 6).runWith(sink).futureValue.toInt should ===(15) @@ -248,7 +248,7 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "fail if getting the supplier fails" in { def failedSupplier(): Supplier[Array[Int]] = throw TE("") val future = Source(1 to 100).runWith(StreamConverters.javaCollector( - () ⇒ new TestCollector(failedSupplier _, accumulator _, combiner _, finisher _))) + () => new TestCollector(failedSupplier _, accumulator _, combiner _, finisher _))) a[TE] shouldBe thrownBy { Await.result(future, 300.millis) } @@ -259,7 +259,7 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { override def get(): Array[Int] = throw TE("") } val future = Source(1 to 100).runWith(StreamConverters.javaCollector( - () ⇒ new TestCollector(failedSupplier _, accumulator _, combiner _, finisher _))) + () => new TestCollector(failedSupplier _, accumulator _, combiner _, finisher _))) a[TE] shouldBe thrownBy { Await.result(future, 300.millis) } @@ -269,7 +269,7 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { def failedAccumulator(): BiConsumer[Array[Int], Int] = throw TE("") val future = Source(1 to 100).runWith(StreamConverters.javaCollector( - () ⇒ new TestCollector(supplier _, failedAccumulator _, combiner _, finisher _))) + () => new TestCollector(supplier _, failedAccumulator _, combiner _, finisher _))) a[TE] shouldBe thrownBy { Await.result(future, 300.millis) } @@ -281,7 +281,7 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { } val future = Source(1 to 100).runWith(StreamConverters.javaCollector( - () ⇒ new TestCollector(supplier _, failedAccumulator _, combiner _, finisher _))) + () => new TestCollector(supplier _, failedAccumulator _, combiner _, finisher _))) a[TE] shouldBe thrownBy { Await.result(future, 300.millis) } @@ -291,7 +291,7 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { def failedFinisher(): function.Function[Array[Int], Int] = throw TE("") val future = Source(1 to 100).runWith(StreamConverters.javaCollector( - () ⇒ new TestCollector(supplier _, accumulator _, combiner _, failedFinisher _))) + () => new TestCollector(supplier _, accumulator _, combiner _, failedFinisher _))) a[TE] shouldBe thrownBy { Await.result(future, 300.millis) } @@ -302,7 +302,7 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { override def apply(a: Array[Int]): Int = throw TE("") } val future = Source(1 to 100).runWith(StreamConverters.javaCollector( - () ⇒ new TestCollector(supplier _, accumulator _, combiner _, failedFinisher _))) + () => new TestCollector(supplier _, accumulator _, combiner _, failedFinisher _))) a[TE] shouldBe thrownBy { Await.result(future, 300.millis) } @@ -327,7 +327,7 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "sum up 1 to 10 correctly" in { //#reduce-operator-example val source = Source(1 to 10) - val result = source.runWith(Sink.reduce[Int]((a, b) ⇒ a + b)) + val result = source.runWith(Sink.reduce[Int]((a, b) => a + b)) result.map(println)(system.dispatcher) // 55 //#reduce-operator-example diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SourceSpec.scala index d20e114090..25b66ddffc 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SourceSpec.scala @@ -34,7 +34,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { implicit val ec = system.dispatcher //#source-single val s: Future[immutable.Seq[Int]] = Source.single(1).runWith(Sink.seq) - s.foreach(list ⇒ println(s"Collected elements: $list")) // prints: Collected elements: List(1) + s.foreach(list => println(s"Collected elements: $list")) // prints: Collected elements: List(1) //#source-single @@ -88,7 +88,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { val source = Source.asSubscriber[Int] val out = TestSubscriber.manualProbe[Int] - val s = Source.fromGraph(GraphDSL.create(source, source, source, source, source)(immutable.Seq(_, _, _, _, _)) { implicit b ⇒ (i0, i1, i2, i3, i4) ⇒ + val s = Source.fromGraph(GraphDSL.create(source, source, source, source, source)(immutable.Seq(_, _, _, _, _)) { implicit b => (i0, i1, i2, i3, i4) => import GraphDSL.Implicits._ val m = b.add(Merge[Int](5)) i0.out ~> m.in(0) @@ -99,39 +99,39 @@ class SourceSpec extends StreamSpec with DefaultTimeout { SourceShape(m.out) }).to(Sink.fromSubscriber(out)).run() - for (i ← 0 to 4) probes(i).subscribe(s(i)) + for (i <- 0 to 4) probes(i).subscribe(s(i)) val sub = out.expectSubscription() sub.request(10) - val subs = for (i ← 0 to 4) { + val subs = for (i <- 0 to 4) { val s = probes(i).expectSubscription() s.expectRequest() s.sendNext(i) s.sendComplete() } - val gotten = for (_ ← 0 to 4) yield out.expectNext() + val gotten = for (_ <- 0 to 4) yield out.expectNext() gotten.toSet should ===(Set(0, 1, 2, 3, 4)) out.expectComplete() } "combine from many inputs with simplified API" in { val probes = immutable.Seq.fill(3)(TestPublisher.manualProbe[Int]()) - val source = for (i ← 0 to 2) yield Source.fromPublisher(probes(i)) + val source = for (i <- 0 to 2) yield Source.fromPublisher(probes(i)) val out = TestSubscriber.manualProbe[Int] Source.combine(source(0), source(1), source(2))(Merge(_)).to(Sink.fromSubscriber(out)).run() val sub = out.expectSubscription() sub.request(3) - for (i ← 0 to 2) { + for (i <- 0 to 2) { val s = probes(i).expectSubscription() s.expectRequest() s.sendNext(i) s.sendComplete() } - val gotten = for (_ ← 0 to 2) yield out.expectNext() + val gotten = for (_ <- 0 to 2) yield out.expectNext() gotten.toSet should ===(Set(0, 1, 2)) out.expectComplete() } @@ -146,14 +146,14 @@ class SourceSpec extends StreamSpec with DefaultTimeout { val sub = out.expectSubscription() sub.request(3) - for (i ← 0 to 1) { + for (i <- 0 to 1) { val s = probes(i).expectSubscription() s.expectRequest() s.sendNext(i) s.sendComplete() } - val gotten = for (_ ← 0 to 1) yield out.expectNext() + val gotten = for (_ <- 0 to 1) yield out.expectNext() gotten.toSet should ===(Set(0, 1)) out.expectComplete() } @@ -226,9 +226,9 @@ class SourceSpec extends StreamSpec with DefaultTimeout { "generate a finite fibonacci sequence" in { Source.unfold((0, 1)) { - case (a, _) if a > 10000000 ⇒ None - case (a, b) ⇒ Some((b, a + b) → a) - }.runFold(List.empty[Int]) { case (xs, x) ⇒ x :: xs } + case (a, _) if a > 10000000 => None + case (a, b) => Some((b, a + b) -> a) + }.runFold(List.empty[Int]) { case (xs, x) => x :: xs } .futureValue should ===(expected) } @@ -237,32 +237,32 @@ class SourceSpec extends StreamSpec with DefaultTimeout { EventFilter[RuntimeException](message = "expected", occurrences = 1) intercept whenReady( Source.unfold((0, 1)) { - case (a, _) if a > 10000000 ⇒ throw t - case (a, b) ⇒ Some((b, a + b) → a) - }.runFold(List.empty[Int]) { case (xs, x) ⇒ x :: xs }.failed) { + case (a, _) if a > 10000000 => throw t + case (a, b) => Some((b, a + b) -> a) + }.runFold(List.empty[Int]) { case (xs, x) => x :: xs }.failed) { _ should be theSameInstanceAs (t) } } "generate a finite fibonacci sequence asynchronously" in { Source.unfoldAsync((0, 1)) { - case (a, _) if a > 10000000 ⇒ Future.successful(None) - case (a, b) ⇒ Future(Some((b, a + b) → a))(system.dispatcher) - }.runFold(List.empty[Int]) { case (xs, x) ⇒ x :: xs } + case (a, _) if a > 10000000 => Future.successful(None) + case (a, b) => Future(Some((b, a + b) -> a))(system.dispatcher) + }.runFold(List.empty[Int]) { case (xs, x) => x :: xs } .futureValue should ===(expected) } "generate an unbounded fibonacci sequence" in { - Source.unfold((0, 1))({ case (a, b) ⇒ Some((b, a + b) → a) }) + Source.unfold((0, 1))({ case (a, b) => Some((b, a + b) -> a) }) .take(36) - .runFold(List.empty[Int]) { case (xs, x) ⇒ x :: xs } + .runFold(List.empty[Int]) { case (xs, x) => x :: xs } .futureValue should ===(expected) } } "Iterator Source" must { "properly iterate" in { - Source.fromIterator(() ⇒ Iterator.iterate(false)(!_)) + Source.fromIterator(() => Iterator.iterate(false)(!_)) .grouped(10) .runWith(Sink.head) .futureValue should ===(immutable.Seq(false, true, false, true, false, true, false, true, false, true)) @@ -270,26 +270,26 @@ class SourceSpec extends StreamSpec with DefaultTimeout { "fail stream when iterator throws" in { Source - .fromIterator(() ⇒ (1 to 1000).toIterator.map(k ⇒ if (k < 10) k else throw TE("a"))) + .fromIterator(() => (1 to 1000).toIterator.map(k => if (k < 10) k else throw TE("a"))) .runWith(Sink.ignore) .failed.futureValue.getClass should ===(classOf[TE]) Source - .fromIterator(() ⇒ (1 to 1000).toIterator.map(_ ⇒ throw TE("b"))) + .fromIterator(() => (1 to 1000).toIterator.map(_ => throw TE("b"))) .runWith(Sink.ignore) .failed.futureValue.getClass should ===(classOf[TE]) } "use decider when iterator throws" in { Source - .fromIterator(() ⇒ (1 to 5).toIterator.map(k ⇒ if (k != 3) k else throw TE("a"))) + .fromIterator(() => (1 to 5).toIterator.map(k => if (k != 3) k else throw TE("a"))) .withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .grouped(10) .runWith(Sink.head) .futureValue should ===(List(1, 2)) Source - .fromIterator(() ⇒ (1 to 5).toIterator.map(_ ⇒ throw TE("b"))) + .fromIterator(() => (1 to 5).toIterator.map(_ => throw TE("b"))) .withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .grouped(10) .runWith(Sink.headOption) @@ -331,7 +331,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { "continuously generate the same sequence" in { val expected = Seq(1, 2, 3, 1, 2, 3, 1, 2, 3) //#cycle - Source.cycle(() ⇒ List(1, 2, 3).iterator) + Source.cycle(() => List(1, 2, 3).iterator) .grouped(9) .runWith(Sink.head) // This will produce the Seq(1, 2, 3, 1, 2, 3, 1, 2, 3) @@ -342,7 +342,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { "throw an exception in case of empty iterator" in { //#cycle-error val empty = Iterator.empty - Source.cycle(() ⇒ empty) + Source.cycle(() => empty) .runWith(Sink.head) // This will return a failed future with an `IllegalArgumentException` //#cycle-error @@ -361,7 +361,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { import scala.compat.java8.FunctionConverters._ import java.util.stream.{ Stream, IntStream } - def javaStreamInts = IntStream.iterate(1, { i: Int ⇒ i + 1 }.asJava) + def javaStreamInts = IntStream.iterate(1, { i: Int => i + 1 }.asJava) "work with Java collections" in { val list = new java.util.LinkedList[Integer]() @@ -369,23 +369,23 @@ class SourceSpec extends StreamSpec with DefaultTimeout { list.add(1) list.add(2) - StreamConverters.fromJavaStream(() ⇒ list.stream()).map(_.intValue).runWith(Sink.seq).futureValue should ===(List(0, 1, 2)) + StreamConverters.fromJavaStream(() => list.stream()).map(_.intValue).runWith(Sink.seq).futureValue should ===(List(0, 1, 2)) } "work with primitive streams" in { - StreamConverters.fromJavaStream(() ⇒ IntStream.rangeClosed(1, 10)).map(_.intValue).runWith(Sink.seq).futureValue should ===(1 to 10) + StreamConverters.fromJavaStream(() => IntStream.rangeClosed(1, 10)).map(_.intValue).runWith(Sink.seq).futureValue should ===(1 to 10) } "work with an empty stream" in { - StreamConverters.fromJavaStream(() ⇒ Stream.empty[Int]()).runWith(Sink.seq).futureValue should ===(Nil) + StreamConverters.fromJavaStream(() => Stream.empty[Int]()).runWith(Sink.seq).futureValue should ===(Nil) } "work with an infinite stream" in { - StreamConverters.fromJavaStream(() ⇒ javaStreamInts).take(1000).runFold(0)(_ + _).futureValue should ===(500500) + StreamConverters.fromJavaStream(() => javaStreamInts).take(1000).runFold(0)(_ + _).futureValue should ===(500500) } "work with a filtered stream" in { - StreamConverters.fromJavaStream(() ⇒ javaStreamInts.filter({ i: Int ⇒ i % 2 == 0 }.asJava)) + StreamConverters.fromJavaStream(() => javaStreamInts.filter({ i: Int => i % 2 == 0 }.asJava)) .take(1000).runFold(0)(_ + _).futureValue should ===(1001000) } @@ -393,11 +393,11 @@ class SourceSpec extends StreamSpec with DefaultTimeout { import akka.stream.testkit.Utils.TE // Filtering is lazy on Java Stream - val failyFilter: Int ⇒ Boolean = i ⇒ throw TE("failing filter") + val failyFilter: Int => Boolean = i => throw TE("failing filter") a[TE] must be thrownBy { Await.result( - StreamConverters.fromJavaStream(() ⇒ javaStreamInts.filter(failyFilter.asJava)).runWith(Sink.ignore), + StreamConverters.fromJavaStream(() => javaStreamInts.filter(failyFilter.asJava)).runWith(Sink.ignore), 3.seconds) } } @@ -422,7 +422,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { override def close(): Unit = closed = true } - Await.ready(StreamConverters.fromJavaStream(() ⇒ new EmptyStream[Unit]).runWith(Sink.ignore), 3.seconds) + Await.ready(StreamConverters.fromJavaStream(() => new EmptyStream[Unit]).runWith(Sink.ignore), 3.seconds) closed should ===(true) } @@ -447,7 +447,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { override def close(): Unit = closed = true } - Await.ready(StreamConverters.fromJavaStream(() ⇒ new FailingStream[Unit]).runWith(Sink.ignore), 3.seconds) + Await.ready(StreamConverters.fromJavaStream(() => new FailingStream[Unit]).runWith(Sink.ignore), 3.seconds) closed should ===(true) } @@ -510,7 +510,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { } "correctly propagate materialization failures" in { - val matValPoweredSource = Source.empty.mapMaterializedValue(_ ⇒ throw new RuntimeException("boom")) + val matValPoweredSource = Source.empty.mapMaterializedValue(_ => throw new RuntimeException("boom")) a[RuntimeException] shouldBe thrownBy(matValPoweredSource.preMaterialize()) } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SourceWithContextSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SourceWithContextSpec.scala index c283e1d900..90769a57a5 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SourceWithContextSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SourceWithContextSpec.scala @@ -43,7 +43,7 @@ class SourceWithContextSpec extends StreamSpec { Source(Vector(msg)) .asSourceWithContext(_.offset) .map(_.data) - .asSource.map { case (e, _) ⇒ e } + .asSource.map { case (e, _) => e } .runWith(TestSink.probe[String]) .request(1) .expectNext("a") @@ -73,7 +73,7 @@ class SourceWithContextSpec extends StreamSpec { Source(Vector(Message("a", 1L))) .asSourceWithContext(_.offset) .map(_.data) - .via(flowWithContext.map(s ⇒ s + "b")) + .via(flowWithContext.map(s => s + "b")) .runWith(TestSink.probe[(String, Long)]) .request(1) .expectNext(("ab", 1L)) @@ -84,8 +84,8 @@ class SourceWithContextSpec extends StreamSpec { Source(Vector(Message("a", 1L))) .asSourceWithContext(_.offset) .map(_.data) - .mapConcat { str ⇒ - List(1, 2, 3).map(i ⇒ s"$str-$i") + .mapConcat { str => + List(1, 2, 3).map(i => s"$str-$i") } .runWith(TestSink.probe[(String, Long)]) .request(3) @@ -97,8 +97,8 @@ class SourceWithContextSpec extends StreamSpec { Source(Vector(Message("a", 1L))) .asSourceWithContext(_.offset) .map(_.data) - .mapConcat { str ⇒ - List(1, 2, 3, 4).map(i ⇒ s"$str-$i") + .mapConcat { str => + List(1, 2, 3, 4).map(i => s"$str-$i") } .grouped(2) .toMat(TestSink.probe[(Seq[String], Seq[Long])])(Keep.right) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/StageActorRefSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/StageActorRefSpec.scala index 514332e836..e4c7743baf 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/StageActorRefSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/StageActorRefSpec.scala @@ -139,8 +139,8 @@ class StageActorRefSpec extends StreamSpec with ImplicitSender { stageRef ! Add(40) val filter = EventFilter.custom { - case e: Logging.Warning ⇒ true - case _ ⇒ false + case e: Logging.Warning => true + case _ => false } system.eventStream.publish(TestEvent.Mute(filter)) system.eventStream.subscribe(testActor, classOf[Logging.Warning]) @@ -150,12 +150,12 @@ class StageActorRefSpec extends StreamSpec with ImplicitSender { val expectedMsg = s"[PoisonPill|Kill] message sent to StageActorRef($actorName) will be ignored,since it is not a real Actor. " + "Use a custom message type to communicate with it instead." expectMsgPF(1.second, expectedMsg) { - case Logging.Warning(_, _, msg) ⇒ expectedMsg.r.pattern.matcher(msg.toString).matches() + case Logging.Warning(_, _, msg) => expectedMsg.r.pattern.matcher(msg.toString).matches() } stageRef ! Kill // should log a warning, and NOT stop the stage. expectMsgPF(1.second, expectedMsg) { - case Logging.Warning(_, _, msg) ⇒ expectedMsg.r.pattern.matcher(msg.toString).matches() + case Logging.Warning(_, _, msg) => expectedMsg.r.pattern.matcher(msg.toString).matches() } source.success(Some(2)) @@ -197,17 +197,17 @@ object StageActorRefSpec { def behavior(m: (ActorRef, Any)): Unit = { m match { - case (sender, Add(n)) ⇒ sum += n - case (sender, PullNow) ⇒ pull(in) - case (sender, CallInitStageActorRef) ⇒ sender ! getStageActor(behavior).ref - case (sender, BecomeStringEcho) ⇒ + case (sender, Add(n)) => sum += n + case (sender, PullNow) => pull(in) + case (sender, CallInitStageActorRef) => sender ! getStageActor(behavior).ref + case (sender, BecomeStringEcho) => getStageActor { - case (theSender, msg) ⇒ theSender ! msg.toString + case (theSender, msg) => theSender ! msg.toString } - case (sender, StopNow) ⇒ + case (sender, StopNow) => p.trySuccess(sum) completeStage() - case (sender, AddAndTell(n)) ⇒ + case (sender, AddAndTell(n)) => sum += n sender ! sum } @@ -232,7 +232,7 @@ object StageActorRefSpec { }) } - logic → p.future + logic -> p.future } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/StreamRefsSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/StreamRefsSpec.scala index 211f6b7d9a..61dfdc4c7e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/StreamRefsSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/StreamRefsSpec.scala @@ -33,7 +33,7 @@ object StreamRefsSpec { implicit val mat = ActorMaterializer() def receive = { - case "give" ⇒ + case "give" => /* * Here we're able to send a source to a remote recipient * @@ -44,32 +44,32 @@ object StreamRefsSpec { ref pipeTo sender() - case "give-infinite" ⇒ - val source: Source[String, NotUsed] = Source.fromIterator(() ⇒ Iterator.from(1)).map("ping-" + _) + case "give-infinite" => + val source: Source[String, NotUsed] = Source.fromIterator(() => Iterator.from(1)).map("ping-" + _) val (r: NotUsed, ref: Future[SourceRef[String]]) = source.toMat(StreamRefs.sourceRef())(Keep.both).run() ref pipeTo sender() - case "give-fail" ⇒ + case "give-fail" => val ref = Source.failed[String](new Exception("Booooom!") with NoStackTrace) .runWith(StreamRefs.sourceRef()) ref pipeTo sender() - case "give-complete-asap" ⇒ + case "give-complete-asap" => val ref = Source.empty .runWith(StreamRefs.sourceRef()) ref pipeTo sender() - case "give-subscribe-timeout" ⇒ + case "give-subscribe-timeout" => val ref = Source.repeat("is anyone there?") .toMat(StreamRefs.sourceRef())(Keep.right) // attributes like this so they apply to the Sink.sourceRef .withAttributes(StreamRefAttributes.subscriptionTimeout(500.millis)) .run() ref pipeTo sender() - // case "send-bulk" ⇒ + // case "send-bulk" => // /* // * Here we're able to send a source to a remote recipient // * The source is a "bulk transfer one, in which we're ready to send a lot of data" @@ -80,7 +80,7 @@ object StreamRefsSpec { // val ref: SourceRef[ByteString] = source.runWith(SourceRef.bulkTransfer()) // sender() ! BulkSourceMsg(ref) - case "receive" ⇒ + case "receive" => /* * We write out code, knowing that the other side will stream the data into it. * @@ -93,7 +93,7 @@ object StreamRefsSpec { sink pipeTo sender() - case "receive-ignore" ⇒ + case "receive-ignore" => val sink = StreamRefs.sinkRef[String]() .to(Sink.ignore) @@ -101,7 +101,7 @@ object StreamRefsSpec { sink pipeTo sender() - case "receive-subscribe-timeout" ⇒ + case "receive-subscribe-timeout" => val sink = StreamRefs.sinkRef[String]() .withAttributes(StreamRefAttributes.subscriptionTimeout(500.millis)) .to(Sink.actorRef(probe, "")) @@ -109,7 +109,7 @@ object StreamRefsSpec { sink pipeTo sender() - case "receive-32" ⇒ + case "receive-32" => val (sink, driver) = StreamRefs.sinkRef[String]() .toMat(TestSink.probe(context.system))(Keep.both) .run() @@ -129,7 +129,7 @@ object StreamRefsSpec { sink pipeTo sender() - // case "receive-bulk" ⇒ + // case "receive-bulk" => // /* // * We write out code, knowing that the other side will stream the data into it. // * This will open a dedicated connection per transfer. @@ -252,7 +252,7 @@ class StreamRefsSpec(config: Config) extends AkkaSpec(config) with ImplicitSende probe.expectNoMessage(100.millis) probe.request(20) - probe.expectNextN((1 to 20).map(i ⇒ "ping-" + (i + 1))) + probe.expectNextN((1 to 20).map(i => "ping-" + (i + 1))) probe.cancel() // since no demand anyway @@ -344,12 +344,12 @@ class StreamRefsSpec(config: Config) extends AkkaSpec(config) with ImplicitSende remoteActor ! "receive" val remoteSink: SinkRef[String] = expectMsgType[SinkRef[String]] - val msgs = (1 to 100).toList.map(i ⇒ s"payload-$i") + val msgs = (1 to 100).toList.map(i => s"payload-$i") Source(msgs) .runWith(remoteSink) - msgs.foreach(t ⇒ p.expectMsg(t)) + msgs.foreach(t => p.expectMsg(t)) p.expectMsg("") } @@ -380,7 +380,7 @@ class StreamRefsSpec(config: Config) extends AkkaSpec(config) with ImplicitSende .take(10) // the timeout is 500ms, so this makes sure we run more time than that .runWith(remoteSink) - (0 to 9).foreach { _ ⇒ + (0 to 9).foreach { _ => p.expectMsg("whatever") } p.expectMsg("") diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SubscriberSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SubscriberSourceSpec.scala index ded00c3d7e..8e6e48f646 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SubscriberSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SubscriberSourceSpec.scala @@ -19,7 +19,7 @@ class SubscriberSourceSpec extends StreamSpec { "be able to use Subscriber in materialized value transformation" in { val f = - Source.asSubscriber[Int].mapMaterializedValue(s ⇒ Source(1 to 3).runWith(Sink.fromSubscriber(s))) + Source.asSubscriber[Int].mapMaterializedValue(s => Source(1 to 3).runWith(Sink.fromSubscriber(s))) .runWith(Sink.fold[Int, Int](0)(_ + _)) Await.result(f, 3.seconds) should be(6) diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SubstreamSubscriptionTimeoutSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SubstreamSubscriptionTimeoutSpec.scala index cba7b2248d..1cbcc4af94 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SubstreamSubscriptionTimeoutSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/SubstreamSubscriptionTimeoutSpec.scala @@ -73,7 +73,7 @@ class SubstreamSubscriptionTimeoutSpec(conf: String) extends StreamSpec(conf) { Thread.sleep(1500) // Must be a Sink.seq, otherwise there is a race due to the concat in the `lift` implementation - val f = s3.runWith(Sink.seq).recover { case _: SubscriptionTimeoutException ⇒ "expected" } + val f = s3.runWith(Sink.seq).recover { case _: SubscriptionTimeoutException => "expected" } Await.result(f, remainingOrDefault) should equal("expected") publisherProbe.sendComplete() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/TakeLastSinkSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/TakeLastSinkSpec.scala index 9453b65c5d..18c2a40661 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/TakeLastSinkSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/TakeLastSinkSpec.scala @@ -37,9 +37,9 @@ class TakeLastSinkSpec extends StreamSpec { val result: Future[Seq[Student]] = sourceOfStudents.runWith(Sink.takeLast(3)) - result.foreach { topThree ⇒ + result.foreach { topThree => println("#### Top students ####") - topThree.reverse foreach { s ⇒ + topThree.reverse foreach { s => println(s"Name: ${s.name}, GPA: ${s.gpa}") } } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/TickSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/TickSourceSpec.scala index 906950903b..5f8147a459 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/TickSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/TickSourceSpec.scala @@ -63,12 +63,12 @@ class TickSourceSpec extends StreamSpec { "be usable with zip for a simple form of rate limiting" taggedAs TimingTest in { val c = TestSubscriber.manualProbe[Int]() - RunnableGraph.fromGraph(GraphDSL.create() { implicit b ⇒ + RunnableGraph.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val zip = b.add(Zip[Int, String]()) Source(1 to 100) ~> zip.in0 Source.tick(1.second, 1.second, "tick") ~> zip.in1 - zip.out ~> Flow[(Int, String)].map { case (n, _) ⇒ n } ~> Sink.fromSubscriber(c) + zip.out ~> Flow[(Int, String)].map { case (n, _) => n } ~> Sink.fromSubscriber(c) ClosedShape }).run() diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/UnfoldResourceAsyncSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/UnfoldResourceAsyncSourceSpec.scala index c3f1bacee7..6d1dc8750d 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/UnfoldResourceAsyncSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/UnfoldResourceAsyncSourceSpec.scala @@ -39,12 +39,12 @@ object UnfoldResourceAsyncSourceSpec { def create: Future[ResourceDummy[T]] = { createdP.trySuccess(Done) - createFuture.map(_ ⇒ this) + createFuture.map(_ => this) } def read: Future[Option[T]] = { if (!firstReadP.isCompleted) firstReadP.trySuccess(Done) - firstReadFuture.map { _ ⇒ + firstReadFuture.map { _ => if (iterator.hasNext) Some(iterator.next()) else None } @@ -88,7 +88,7 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { probe.expectNoMsg(200.millis) createPromise.success(Done) - values.foreach { n ⇒ + values.foreach { n => resource.firstElementRead.futureValue probe.expectNext() should ===(n) probe.request(1) @@ -124,9 +124,9 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "fail when create throws exception" in assertAllStagesStopped { val probe = TestSubscriber.probe[Unit]() Source.unfoldResourceAsync[Unit, Unit]( - () ⇒ throw TE("create failed"), - _ ⇒ ???, - _ ⇒ ???).runWith(Sink.fromSubscriber(probe)) + () => throw TE("create failed"), + _ => ???, + _ => ???).runWith(Sink.fromSubscriber(probe)) probe.ensureSubscription() probe.expectError(TE("create failed")) @@ -135,9 +135,9 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "fail when create returns failed future" in assertAllStagesStopped { val probe = TestSubscriber.probe[Unit]() Source.unfoldResourceAsync[Unit, Unit]( - () ⇒ Future.failed(TE("create failed")), - _ ⇒ ???, - _ ⇒ ???).runWith(Sink.fromSubscriber(probe)) + () => Future.failed(TE("create failed")), + _ => ???, + _ => ???).runWith(Sink.fromSubscriber(probe)) probe.ensureSubscription() probe.expectError(TE("create failed")) @@ -146,9 +146,9 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "fail when close throws exception" in assertAllStagesStopped { val probe = TestSubscriber.probe[Unit]() Source.unfoldResourceAsync[Unit, Unit]( - () ⇒ Future.successful(()), - _ ⇒ Future.successful[Option[Unit]](None), - _ ⇒ throw TE("")) + () => Future.successful(()), + _ => Future.successful[Option[Unit]](None), + _ => throw TE("")) .runWith(Sink.fromSubscriber(probe)) probe.ensureSubscription() probe.request(1L) @@ -158,9 +158,9 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "fail when close returns failed future" in assertAllStagesStopped { val probe = TestSubscriber.probe[Unit]() Source.unfoldResourceAsync[Unit, Unit]( - () ⇒ Future.successful(()), - _ ⇒ Future.successful[Option[Unit]](None), - _ ⇒ Future.failed(throw TE(""))) + () => Future.successful(()), + _ => Future.successful[Option[Unit]](None), + _ => Future.failed(throw TE(""))) .runWith(Sink.fromSubscriber(probe)) probe.ensureSubscription() probe.request(1L) @@ -169,15 +169,15 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "continue when Strategy is Resume and read throws" in assertAllStagesStopped { val result = Source.unfoldResourceAsync[Int, Iterator[Any]]( - () ⇒ Future.successful(List(1, 2, TE("read-error"), 3).iterator), - iterator ⇒ + () => Future.successful(List(1, 2, TE("read-error"), 3).iterator), + iterator => if (iterator.hasNext) { iterator.next() match { - case n: Int ⇒ Future.successful(Some(n)) - case e: TE ⇒ throw e + case n: Int => Future.successful(Some(n)) + case e: TE => throw e } } else Future.successful(None), - _ ⇒ Future.successful(Done) + _ => Future.successful(Done) ).withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider)) .runWith(Sink.seq) @@ -186,15 +186,15 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "continue when Strategy is Resume and read returns failed future" in assertAllStagesStopped { val result = Source.unfoldResourceAsync[Int, Iterator[Any]]( - () ⇒ Future.successful(List(1, 2, TE("read-error"), 3).iterator), - iterator ⇒ + () => Future.successful(List(1, 2, TE("read-error"), 3).iterator), + iterator => if (iterator.hasNext) { iterator.next() match { - case n: Int ⇒ Future.successful(Some(n)) - case e: TE ⇒ Future.failed(e) + case n: Int => Future.successful(Some(n)) + case e: TE => Future.failed(e) } } else Future.successful(None), - _ ⇒ Future.successful(Done) + _ => Future.successful(Done) ).withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider)) .runWith(Sink.seq) @@ -206,17 +206,17 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val startCount = new AtomicInteger(0) val result = Source.unfoldResourceAsync[Int, Iterator[Int]]( - () ⇒ Future.successful { + () => Future.successful { startCount.incrementAndGet() List(1, 2, 3).iterator }, - reader ⇒ + reader => if (!failed) { failed = true throw TE("read-error") } else if (reader.hasNext) Future.successful(Some(reader.next)) else Future.successful(None), - _ ⇒ Future.successful(Done) + _ => Future.successful(Done) ).withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .runWith(Sink.seq) @@ -229,17 +229,17 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val startCount = new AtomicInteger(0) val result = Source.unfoldResourceAsync[Int, Iterator[Int]]( - () ⇒ Future.successful { + () => Future.successful { startCount.incrementAndGet() List(1, 2, 3).iterator }, - reader ⇒ + reader => if (!failed) { failed = true Future.failed(TE("read-error")) } else if (reader.hasNext) Future.successful(Some(reader.next)) else Future.successful(None), - _ ⇒ Future.successful(Done) + _ => Future.successful(Done) ).withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .runWith(Sink.seq) @@ -250,9 +250,9 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "fail stream when restarting and close throws" in assertAllStagesStopped { val out = TestSubscriber.probe[Int]() Source.unfoldResourceAsync[Int, Iterator[Int]]( - () ⇒ Future.successful(List(1, 2, 3).iterator), - reader ⇒ throw TE("read-error"), - _ ⇒ throw new TE("close-error") + () => Future.successful(List(1, 2, 3).iterator), + reader => throw TE("read-error"), + _ => throw new TE("close-error") ).withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .runWith(Sink.fromSubscriber(out)) @@ -263,9 +263,9 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "fail stream when restarting and close returns failed future" in assertAllStagesStopped { val out = TestSubscriber.probe[Int]() Source.unfoldResourceAsync[Int, Iterator[Int]]( - () ⇒ Future.successful(List(1, 2, 3).iterator), - reader ⇒ throw TE("read-error"), - _ ⇒ Future.failed(new TE("close-error")) + () => Future.successful(List(1, 2, 3).iterator), + reader => throw TE("read-error"), + _ => Future.failed(new TE("close-error")) ).withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .runWith(Sink.fromSubscriber(out)) @@ -277,11 +277,11 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val startCounter = new AtomicInteger(0) val out = TestSubscriber.probe[Int]() Source.unfoldResourceAsync[Int, Iterator[Int]]( - () ⇒ + () => if (startCounter.incrementAndGet() < 2) Future.successful(List(1, 2, 3).iterator) else throw TE("start-error"), - reader ⇒ throw TE("read-error"), - _ ⇒ Future.successful(Done) + reader => throw TE("read-error"), + _ => Future.successful(Done) ).withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .runWith(Sink.fromSubscriber(out)) @@ -293,11 +293,11 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val startCounter = new AtomicInteger(0) val out = TestSubscriber.probe[Int]() Source.unfoldResourceAsync[Int, Iterator[Int]]( - () ⇒ + () => if (startCounter.incrementAndGet() < 2) Future.successful(List(1, 2, 3).iterator) else Future.failed(TE("start-error")), - reader ⇒ throw TE("read-error"), - _ ⇒ Future.successful(Done) + reader => throw TE("read-error"), + _ => Future.successful(Done) ).withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .runWith(Sink.fromSubscriber(out)) @@ -310,9 +310,9 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val materializer = ActorMaterializer()(sys) try { val p = Source.unfoldResourceAsync[String, Unit]( - () ⇒ Promise[Unit].future, // never complete - _ ⇒ ???, - _ ⇒ ???).runWith(Sink.ignore)(materializer) + () => Promise[Unit].future, // never complete + _ => ???, + _ => ???).runWith(Sink.ignore)(materializer) materializer.asInstanceOf[PhasedFusingActorMaterializer].supervisor.tell(StreamSupervisor.GetChildren, testActor) val ref = expectMsgType[Children].children.find(_.path.toString contains "unfoldResourceSourceAsync").get @@ -325,10 +325,10 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val closeLatch = TestLatch(1) val mat = ActorMaterializer() val p = Source.unfoldResourceAsync[String, Unit]( - () ⇒ Future.successful(()), + () => Future.successful(()), // a slow trickle of elements that never ends - _ ⇒ akka.pattern.after(100.millis, system.scheduler)(Future.successful(Some("element"))), - _ ⇒ Future.successful { + _ => akka.pattern.after(100.millis, system.scheduler)(Future.successful(Some("element"))), + _ => Future.successful { closeLatch.countDown() Done }) @@ -346,9 +346,9 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val closePromise = Promise[Done]() Source.unfoldResourceAsync[String, Unit]( // delay it a bit to give cancellation time to come upstream - () ⇒ akka.pattern.after(100.millis, system.scheduler)(Future.successful(())), - _ ⇒ Future.successful(Some("whatever")), - _ ⇒ closePromise.success(Done).future + () => akka.pattern.after(100.millis, system.scheduler)(Future.successful(())), + _ => Future.successful(Some("whatever")), + _ => closePromise.success(Done).future ).runWith(Sink.cancelled) closePromise.future.futureValue should ===(Done) @@ -358,11 +358,11 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val closed = Promise[Done]() Source .unfoldResourceAsync[String, Iterator[String]]( - { () ⇒ Future(Iterator("a", "b", "c")) }, - { m ⇒ Future(if (m.hasNext) Some(m.next()) else None) }, - { _ ⇒ closed.success(Done).future } + { () => Future(Iterator("a", "b", "c")) }, + { m => Future(if (m.hasNext) Some(m.next()) else None) }, + { _ => closed.success(Done).future } ) - .map(m ⇒ println(s"Elem=> $m")) + .map(m => println(s"Elem=> $m")) .runWith(Sink.cancelled) closed.future.futureValue // will timeout if bug is still here diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/UnfoldResourceSourceSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/UnfoldResourceSourceSpec.scala index 43073ed461..8fa5e7445e 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/UnfoldResourceSourceSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/UnfoldResourceSourceSpec.scala @@ -51,9 +51,9 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "Unfold Resource Source" must { "read contents from a file" in assertAllStagesStopped { val p = Source.unfoldResource[String, BufferedReader]( - () ⇒ newBufferedReader(), - reader ⇒ Option(reader.readLine()), - reader ⇒ reader.close()) + () => newBufferedReader(), + reader => Option(reader.readLine()), + reader => reader.close()) .runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[String]() p.subscribe(c) @@ -78,19 +78,19 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "continue when Strategy is Resume and exception happened" in assertAllStagesStopped { val p = Source.unfoldResource[String, BufferedReader]( - () ⇒ newBufferedReader(), - reader ⇒ { + () => newBufferedReader(), + reader => { val s = reader.readLine() if (s != null && s.contains("b")) throw TE("") else Option(s) }, - reader ⇒ reader.close()).withAttributes(supervisionStrategy(resumingDecider)) + reader => reader.close()).withAttributes(supervisionStrategy(resumingDecider)) .runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[String]() p.subscribe(c) val sub = c.expectSubscription() - (0 to 49).foreach(i ⇒ { + (0 to 49).foreach(i => { sub.request(1) c.expectNext() should ===(if (i < 10) manyLinesArray(i) else manyLinesArray(i + 10)) }) @@ -100,19 +100,19 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "close and open stream again when Strategy is Restart" in assertAllStagesStopped { val p = Source.unfoldResource[String, BufferedReader]( - () ⇒ newBufferedReader(), - reader ⇒ { + () => newBufferedReader(), + reader => { val s = reader.readLine() if (s != null && s.contains("b")) throw TE("") else Option(s) }, - reader ⇒ reader.close()).withAttributes(supervisionStrategy(restartingDecider)) + reader => reader.close()).withAttributes(supervisionStrategy(restartingDecider)) .runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[String]() p.subscribe(c) val sub = c.expectSubscription() - (0 to 19).foreach(i ⇒ { + (0 to 19).foreach(i => { sub.request(1) c.expectNext() should ===(manyLinesArray(0)) }) @@ -123,12 +123,12 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val chunkSize = 50 val buffer = new Array[Char](chunkSize) val p = Source.unfoldResource[ByteString, Reader]( - () ⇒ newBufferedReader(), - reader ⇒ { + () => newBufferedReader(), + reader => { val s = reader.read(buffer) if (s > 0) Some(ByteString(buffer.mkString("")).take(s)) else None }, - reader ⇒ reader.close()) + reader => reader.close()) .runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[ByteString]() @@ -142,7 +142,7 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 121).foreach(i ⇒ { + (0 to 121).foreach(i => { sub.request(1) c.expectNext().utf8String should ===(nextChunk().toString) }) @@ -155,9 +155,9 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val materializer = ActorMaterializer()(sys) try { val p = Source.unfoldResource[String, BufferedReader]( - () ⇒ newBufferedReader(), - reader ⇒ Option(reader.readLine()), - reader ⇒ reader.close()).runWith(TestSink.probe)(materializer) + () => newBufferedReader(), + reader => Option(reader.readLine()), + reader => reader.close()).runWith(TestSink.probe)(materializer) materializer.asInstanceOf[PhasedFusingActorMaterializer].supervisor.tell(StreamSupervisor.GetChildren, testActor) val ref = expectMsgType[Children].children.find(_.path.toString contains "unfoldResourceSource").get @@ -168,9 +168,9 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "fail when create throws exception" in assertAllStagesStopped { EventFilter[TE](occurrences = 1).intercept { val p = Source.unfoldResource[String, BufferedReader]( - () ⇒ throw TE(""), - reader ⇒ Option(reader.readLine()), - reader ⇒ reader.close()) + () => throw TE(""), + reader => Option(reader.readLine()), + reader => reader.close()) .runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[String]() p.subscribe(c) @@ -185,9 +185,9 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { EventFilter[TE](occurrences = 1).intercept { Source.unfoldResource[String, Iterator[String]]( - () ⇒ Iterator("a"), - it ⇒ if (it.hasNext) Some(it.next()) else None, - _ ⇒ throw TE("")) + () => Iterator("a"), + it => if (it.hasNext) Some(it.next()) else None, + _ => throw TE("")) .runWith(Sink.fromSubscriber(out)) out.request(61) @@ -200,9 +200,9 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "not close the resource twice when read fails" in { val closedCounter = new AtomicInteger(0) val probe = Source.unfoldResource[Int, Int]( - () ⇒ 23, // the best resource there is - _ ⇒ throw TE("failing read"), - _ ⇒ closedCounter.incrementAndGet() + () => 23, // the best resource there is + _ => throw TE("failing read"), + _ => closedCounter.incrementAndGet() ).runWith(TestSink.probe[Int]) probe.request(1) @@ -214,9 +214,9 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "not close the resource twice when read fails and then close fails" in { val closedCounter = new AtomicInteger(0) val probe = Source.unfoldResource[Int, Int]( - () ⇒ 23, // the best resource there is - _ ⇒ throw TE("failing read"), - { _ ⇒ + () => 23, // the best resource there is + _ => throw TE("failing read"), + { _ => closedCounter.incrementAndGet() if (closedCounter.get == 1) throw TE("boom") } diff --git a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/WithContextUsageSpec.scala b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/WithContextUsageSpec.scala index 57066f1f7f..2d98623974 100644 --- a/akka-stream-tests/src/test/scala/akka/stream/scaladsl/WithContextUsageSpec.scala +++ b/akka-stream-tests/src/test/scala/akka/stream/scaladsl/WithContextUsageSpec.scala @@ -21,22 +21,22 @@ class WithContextUsageSpec extends StreamSpec { "be able to commit on offset change" in { val testRange = 0 to 10 val input = genInput(testRange) - val expectedOffsets = testRange.map(ix ⇒ Offset(ix)).init + val expectedOffsets = testRange.map(ix => Offset(ix)).init - val f: (Record ⇒ Record) = record ⇒ record.copy(value = record.value + 1) + val f: (Record => Record) = record => record.copy(value = record.value + 1) val expectedRecords = toRecords(input).map(f) val src = createSourceWithContext(input) .map(f) .asSource - src.map { case (e, _) ⇒ e } + src.map { case (e, _) => e } .runWith(TestSink.probe[Record]) .request(input.size) .expectNextN(expectedRecords) .expectComplete() - src.map { case (_, ctx) ⇒ ctx } + src.map { case (_, ctx) => ctx } .toMat(commitOffsets)(Keep.right) .run() .request(input.size) @@ -48,21 +48,21 @@ class WithContextUsageSpec extends StreamSpec { val testRange = 0 to 10 val input = genInput(testRange) - val f: (Record ⇒ Boolean) = record ⇒ record.key.endsWith("2") - val expectedOffsets = input.filter(cm ⇒ f(cm.record)).map(cm ⇒ Offset(cm)).init + val f: (Record => Boolean) = record => record.key.endsWith("2") + val expectedOffsets = input.filter(cm => f(cm.record)).map(cm => Offset(cm)).init val expectedRecords = toRecords(input).filter(f) val src = createSourceWithContext(input) .filter(f) .asSource - src.map { case (e, _) ⇒ e } + src.map { case (e, _) => e } .runWith(TestSink.probe[Record]) .request(input.size) .expectNextN(expectedRecords) .expectComplete() - src.map { case (_, ctx) ⇒ ctx } + src.map { case (_, ctx) => ctx } .toMat(commitOffsets)(Keep.right) .run() .request(input.size) @@ -74,21 +74,21 @@ class WithContextUsageSpec extends StreamSpec { val testRange = 0 to 10 val input = genInput(testRange) - val f: (Record ⇒ List[Record]) = record ⇒ List(record, record, record) - val expectedOffsets = testRange.map(ix ⇒ Offset(ix)).init + val f: (Record => List[Record]) = record => List(record, record, record) + val expectedOffsets = testRange.map(ix => Offset(ix)).init val expectedRecords = toRecords(input).flatMap(f) val src = createSourceWithContext(input) .mapConcat(f) .asSource - src.map { case (e, _) ⇒ e } + src.map { case (e, _) => e } .runWith(TestSink.probe[Record]) .request(expectedRecords.size) .expectNextN(expectedRecords) .expectComplete() - src.map { case (_, ctx) ⇒ ctx } + src.map { case (_, ctx) => ctx } .toMat(commitOffsets)(Keep.right) .run() .request(input.size) @@ -101,22 +101,22 @@ class WithContextUsageSpec extends StreamSpec { val testRange = 0 to 10 val input = genInput(testRange) - val expectedOffsets = testRange.grouped(2).map(ixs ⇒ Offset(ixs.last)).toVector.init - val expectedMultiRecords = toRecords(input).grouped(groupSize).map(l ⇒ MultiRecord(l)).toVector + val expectedOffsets = testRange.grouped(2).map(ixs => Offset(ixs.last)).toVector.init + val expectedMultiRecords = toRecords(input).grouped(groupSize).map(l => MultiRecord(l)).toVector val src = createSourceWithContext(input) .grouped(groupSize) - .map(l ⇒ MultiRecord(l)) + .map(l => MultiRecord(l)) .mapContext(_.last) .asSource - src.map { case (e, _) ⇒ e } + src.map { case (e, _) => e } .runWith(TestSink.probe[MultiRecord]) .request(expectedMultiRecords.size) .expectNextN(expectedMultiRecords) .expectComplete() - src.map { case (_, ctx) ⇒ ctx } + src.map { case (_, ctx) => ctx } .toMat(commitOffsets)(Keep.right) .run() .request(input.size) @@ -129,27 +129,27 @@ class WithContextUsageSpec extends StreamSpec { val testRange = 0 to 10 val input = genInput(testRange) - val f: (Record ⇒ List[Record]) = record ⇒ List(record, record, record) + val f: (Record => List[Record]) = record => List(record, record, record) // the mapConcat creates bigger lists than the groups, which is why all offsets are seen. // (The mapContext selects the last offset in a group) - val expectedOffsets = testRange.map(ix ⇒ Offset(ix)).init - val expectedMultiRecords = toRecords(input).flatMap(f).grouped(groupSize).map(l ⇒ MultiRecord(l)).toVector + val expectedOffsets = testRange.map(ix => Offset(ix)).init + val expectedMultiRecords = toRecords(input).flatMap(f).grouped(groupSize).map(l => MultiRecord(l)).toVector val src = createSourceWithContext(input) .mapConcat(f) .grouped(groupSize) - .map(l ⇒ MultiRecord(l)) + .map(l => MultiRecord(l)) .mapContext(_.last) .asSource - src.map { case (e, _) ⇒ e } + src.map { case (e, _) => e } .runWith(TestSink.probe[MultiRecord]) .request(expectedMultiRecords.size) .expectNextN(expectedMultiRecords) .expectComplete() - src.map { case (_, ctx) ⇒ ctx } + src.map { case (_, ctx) => ctx } .toMat(commitOffsets)(Keep.right) .run() .request(input.size) @@ -157,7 +157,7 @@ class WithContextUsageSpec extends StreamSpec { .expectComplete() } - def genInput(range: Range) = range.map(ix ⇒ Consumer.CommittableMessage(Record(genKey(ix), genValue(ix)), Consumer.CommittableOffsetImpl(ix))).toVector + def genInput(range: Range) = range.map(ix => Consumer.CommittableMessage(Record(genKey(ix), genValue(ix)), Consumer.CommittableOffsetImpl(ix))).toVector def toRecords(committableMessages: Vector[Consumer.CommittableMessage[Record]]) = committableMessages.map(_.record) def genKey(ix: Int) = s"k$ix" def genValue(ix: Int) = s"v$ix" @@ -166,16 +166,16 @@ class WithContextUsageSpec extends StreamSpec { def createSourceWithContext(committableMessages: Vector[Consumer.CommittableMessage[Record]]): SourceWithContext[Record, Offset, NotUsed] = Consumer .committableSource(committableMessages) - .asSourceWithContext(m ⇒ Offset(m.committableOffset.offset)) + .asSourceWithContext(m => Offset(m.committableOffset.offset)) .map(_.record) def commitOffsets = commit[Offset](Offset.Uninitialized) def commit[Ctx](uninitialized: Ctx): Sink[Ctx, Probe[Ctx]] = { val testSink = TestSink.probe[Ctx] - Flow[Ctx].statefulMapConcat { () ⇒ + Flow[Ctx].statefulMapConcat { () => { var prevCtx: Ctx = uninitialized - ctx ⇒ { + ctx => { val res = if (prevCtx != uninitialized && ctx != prevCtx) Vector(prevCtx) else Vector.empty[Ctx] diff --git a/akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorFlow.scala b/akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorFlow.scala index 4ffedd8334..541ccd1564 100644 --- a/akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorFlow.scala +++ b/akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorFlow.scala @@ -56,7 +56,7 @@ object ActorFlow { * @tparam A Answer type that the Actor is expected to reply with, it will become the Output type of this Flow */ def ask[I, Q, A](ref: ActorRef[Q], timeout: java.time.Duration, makeMessage: BiFunction[I, ActorRef[A], Q]): Flow[I, A, NotUsed] = - akka.stream.typed.scaladsl.ActorFlow.ask[I, Q, A](parallelism = 2)(ref)((i, ref) ⇒ makeMessage(i, ref))(JavaDurationConverters.asFiniteDuration(timeout)) + akka.stream.typed.scaladsl.ActorFlow.ask[I, Q, A](parallelism = 2)(ref)((i, ref) => makeMessage(i, ref))(JavaDurationConverters.asFiniteDuration(timeout)) .asJava /** @@ -92,8 +92,8 @@ object ActorFlow { * @tparam Q Question message type that is spoken by the target actor * @tparam A Answer type that the Actor is expected to reply with, it will become the Output type of this Flow */ - def ask[I, Q, A](parallelism: Int, ref: ActorRef[Q], timeout: java.time.Duration, makeMessage: (I, ActorRef[A]) ⇒ Q): Flow[I, A, NotUsed] = - akka.stream.typed.scaladsl.ActorFlow.ask[I, Q, A](parallelism)(ref)((i, ref) ⇒ makeMessage(i, ref))(timeout.toMillis.millis) + def ask[I, Q, A](parallelism: Int, ref: ActorRef[Q], timeout: java.time.Duration, makeMessage: (I, ActorRef[A]) => Q): Flow[I, A, NotUsed] = + akka.stream.typed.scaladsl.ActorFlow.ask[I, Q, A](parallelism)(ref)((i, ref) => makeMessage(i, ref))(timeout.toMillis.millis) .asJava } diff --git a/akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorSource.scala b/akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorSource.scala index b167daece9..2517e2b0ff 100644 --- a/akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorSource.scala +++ b/akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorSource.scala @@ -52,7 +52,7 @@ object ActorSource { failureMatcher: PartialFunction[T, Throwable], bufferSize: Int, overflowStrategy: OverflowStrategy): Source[T, ActorRef[T]] = { akka.stream.typed.scaladsl.ActorSource.actorRef( - { case m if completionMatcher.test(m) ⇒ }: PartialFunction[T, Unit], + { case m if completionMatcher.test(m) => }: PartialFunction[T, Unit], failureMatcher, bufferSize, overflowStrategy).asJava } } diff --git a/akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorFlow.scala b/akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorFlow.scala index 0142fab57b..80d2f44109 100644 --- a/akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorFlow.scala +++ b/akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorFlow.scala @@ -60,7 +60,7 @@ object ActorFlow { * @tparam A Answer type that the Actor is expected to reply with, it will become the Output type of this Flow */ @implicitNotFound("Missing an implicit akka.util.Timeout for the ask() stage") - def ask[I, Q, A](ref: ActorRef[Q])(makeMessage: (I, ActorRef[A]) ⇒ Q)(implicit timeout: Timeout): Flow[I, A, NotUsed] = + def ask[I, Q, A](ref: ActorRef[Q])(makeMessage: (I, ActorRef[A]) => Q)(implicit timeout: Timeout): Flow[I, A, NotUsed] = ask(parallelism = 2)(ref)(makeMessage)(timeout) /** @@ -98,27 +98,27 @@ object ActorFlow { * @tparam A answer type that the Actor is expected to reply with, it will become the Output type of this Flow */ @implicitNotFound("Missing an implicit akka.util.Timeout for the ask() stage") - def ask[I, Q, A](parallelism: Int)(ref: ActorRef[Q])(makeMessage: (I, ActorRef[A]) ⇒ Q)(implicit timeout: Timeout): Flow[I, A, NotUsed] = { + def ask[I, Q, A](parallelism: Int)(ref: ActorRef[Q])(makeMessage: (I, ActorRef[A]) => Q)(implicit timeout: Timeout): Flow[I, A, NotUsed] = { import akka.actor.typed.scaladsl.adapter._ val untypedRef = ref.toUntyped val askFlow = Flow[I] .watch(untypedRef) - .mapAsync(parallelism) { el ⇒ - val res = akka.pattern.extended.ask(untypedRef, (replyTo: akka.actor.ActorRef) ⇒ makeMessage(el, replyTo)) + .mapAsync(parallelism) { el => + val res = akka.pattern.extended.ask(untypedRef, (replyTo: akka.actor.ActorRef) => makeMessage(el, replyTo)) // we need to cast manually (yet safely, by construction!) since otherwise we need a ClassTag, // which in Scala is fine, but then we would force JavaDSL to create one, which is a hassle in the Akka Typed DSL, // since one may say "but I already specified the type!", and that we have to go via the untyped ask is an implementation detail res.asInstanceOf[Future[A]] } .mapError { - case ex: AskTimeoutException ⇒ + case ex: AskTimeoutException => // in Akka Typed we use the `TimeoutException` everywhere new java.util.concurrent.TimeoutException(ex.getMessage) // the purpose of this recovery is to change the name of the stage in that exception // we do so in order to help users find which stage caused the failure -- "the ask stage" - case ex: WatchedActorTerminatedException ⇒ + case ex: WatchedActorTerminatedException => new WatchedActorTerminatedException("ask()", ex.ref) } .named("ask") diff --git a/akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorSink.scala b/akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorSink.scala index 5ed27c5278..24502763eb 100644 --- a/akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorSink.scala +++ b/akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorSink.scala @@ -30,7 +30,7 @@ object ActorSink { * to use a bounded mailbox with zero `mailbox-push-timeout-time` or use a rate * limiting stage in front of this `Sink`. */ - def actorRef[T](ref: ActorRef[T], onCompleteMessage: T, onFailureMessage: Throwable ⇒ T): Sink[T, NotUsed] = + def actorRef[T](ref: ActorRef[T], onCompleteMessage: T, onFailureMessage: Throwable => T): Sink[T, NotUsed] = Sink.actorRef(ref.toUntyped, onCompleteMessage, onFailureMessage) /** @@ -48,11 +48,11 @@ object ActorSink { */ def actorRefWithAck[T, M, A]( ref: ActorRef[M], - messageAdapter: (ActorRef[A], T) ⇒ M, - onInitMessage: ActorRef[A] ⇒ M, + messageAdapter: (ActorRef[A], T) => M, + onInitMessage: ActorRef[A] => M, ackMessage: A, onCompleteMessage: M, - onFailureMessage: Throwable ⇒ M): Sink[T, NotUsed] = + onFailureMessage: Throwable => M): Sink[T, NotUsed] = Sink.actorRefWithAck( ref.toUntyped, messageAdapter.curried.compose(actorRefAdapter), diff --git a/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/ActorFlowSpec.scala b/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/ActorFlowSpec.scala index 86909fe47a..9b89138ab8 100644 --- a/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/ActorFlowSpec.scala +++ b/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/ActorFlowSpec.scala @@ -33,10 +33,10 @@ class ActorFlowSpec extends ScalaTestWithActorTestKit with WordSpecLike { "ActorFlow" should { val replier = spawn(Behaviors.receiveMessage[Asking] { - case Asking("TERMINATE", _) ⇒ + case Asking("TERMINATE", _) => Behaviors.stopped - case asking ⇒ + case asking => asking.replyTo ! Reply(asking.s + "!!!") Behaviors.same }) @@ -44,7 +44,7 @@ class ActorFlowSpec extends ScalaTestWithActorTestKit with WordSpecLike { "produce asked elements" in { val in: Future[immutable.Seq[Reply]] = Source.repeat("hello") - .via(ActorFlow.ask(replier)((el, replyTo: ActorRef[Reply]) ⇒ Asking(el, replyTo))) + .via(ActorFlow.ask(replier)((el, replyTo: ActorRef[Reply]) => Asking(el, replyTo))) .take(3) .runWith(Sink.seq) @@ -53,7 +53,7 @@ class ActorFlowSpec extends ScalaTestWithActorTestKit with WordSpecLike { "produce asked elements in order" in { //#ask-actor - val ref = spawn(Behaviors.receiveMessage[Asking] { asking ⇒ + val ref = spawn(Behaviors.receiveMessage[Asking] { asking => asking.replyTo ! Reply(asking.s + "!!!") Behaviors.same }) @@ -63,11 +63,11 @@ class ActorFlowSpec extends ScalaTestWithActorTestKit with WordSpecLike { //#ask val in: Future[immutable.Seq[Reply]] = Source(1 to 50).map(_.toString) - .via(ActorFlow.ask(ref)((el, replyTo: ActorRef[Reply]) ⇒ Asking(el, replyTo))) + .via(ActorFlow.ask(ref)((el, replyTo: ActorRef[Reply]) => Asking(el, replyTo))) .runWith(Sink.seq) //#ask - in.futureValue shouldEqual List.tabulate(51)(i ⇒ Reply(s"$i!!!")).drop(1) + in.futureValue shouldEqual List.tabulate(51)(i => Reply(s"$i!!!")).drop(1) } "signal ask timeout failure" in { @@ -88,7 +88,7 @@ class ActorFlowSpec extends ScalaTestWithActorTestKit with WordSpecLike { "signal failure when target actor is terminated" in { val done = Source.maybe[String] - .via(ActorFlow.ask(replier)((el, replyTo: ActorRef[Reply]) ⇒ Asking(el, replyTo))) + .via(ActorFlow.ask(replier)((el, replyTo: ActorRef[Reply]) => Asking(el, replyTo))) .runWith(Sink.ignore) intercept[RuntimeException] { diff --git a/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/ActorSourceSinkSpec.scala b/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/ActorSourceSinkSpec.scala index aa238c0ca0..d364aaba57 100644 --- a/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/ActorSourceSinkSpec.scala +++ b/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/ActorSourceSinkSpec.scala @@ -35,7 +35,7 @@ class ActorSourceSinkSpec extends ScalaTestWithActorTestKit with WordSpecLike { val in = Source.queue[String](10, OverflowStrategy.dropBuffer) .map(_ + "!") - .to(ActorSink.actorRef(p.ref, "DONE", ex ⇒ "FAILED: " + ex.getMessage)) + .to(ActorSink.actorRef(p.ref, "DONE", ex => "FAILED: " + ex.getMessage)) .run() val msg = "Zug zug" @@ -48,17 +48,17 @@ class ActorSourceSinkSpec extends ScalaTestWithActorTestKit with WordSpecLike { val p = TestProbe[AckProto]() val autoPilot = Behaviors.receive[AckProto] { - (ctx, msg) ⇒ + (ctx, msg) => msg match { - case m @ Init(sender) ⇒ + case m @ Init(sender) => p.ref ! m sender ! "ACK" Behaviors.same - case m @ Msg(sender, _) ⇒ + case m @ Msg(sender, _) => p.ref ! m sender ! "ACK" Behaviors.same - case m ⇒ + case m => p.ref ! m Behaviors.same } @@ -68,7 +68,7 @@ class ActorSourceSinkSpec extends ScalaTestWithActorTestKit with WordSpecLike { val in = Source.queue[String](10, OverflowStrategy.dropBuffer) - .to(ActorSink.actorRefWithAck(pilotRef, Msg.apply, Init.apply, "ACK", Complete, _ ⇒ Failed)) + .to(ActorSink.actorRefWithAck(pilotRef, Msg.apply, Init.apply, "ACK", Complete, _ => Failed)) .run() p.expectMessageType[Init] @@ -86,7 +86,7 @@ class ActorSourceSinkSpec extends ScalaTestWithActorTestKit with WordSpecLike { "ActorSource" should { "send messages and complete" in { - val (in, out) = ActorSource.actorRef[String]({ case "complete" ⇒ }, PartialFunction.empty, 10, OverflowStrategy.dropBuffer) + val (in, out) = ActorSource.actorRef[String]({ case "complete" => }, PartialFunction.empty, 10, OverflowStrategy.dropBuffer) .toMat(Sink.seq)(Keep.both) .run() @@ -98,7 +98,7 @@ class ActorSourceSinkSpec extends ScalaTestWithActorTestKit with WordSpecLike { } "fail the stream" in { - val (in, out) = ActorSource.actorRef[String](PartialFunction.empty, { case msg ⇒ new Error(msg) }, 10, OverflowStrategy.dropBuffer) + val (in, out) = ActorSource.actorRef[String](PartialFunction.empty, { case msg => new Error(msg) }, 10, OverflowStrategy.dropBuffer) .toMat(Sink.seq)(Keep.both) .run() diff --git a/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/CustomGuardianAndMaterializerSpec.scala b/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/CustomGuardianAndMaterializerSpec.scala index de2810ca73..935094f77f 100644 --- a/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/CustomGuardianAndMaterializerSpec.scala +++ b/akka-stream-typed/src/test/scala/akka/stream/typed/scaladsl/CustomGuardianAndMaterializerSpec.scala @@ -27,7 +27,7 @@ class CustomGuardianAndMaterializerSpec extends ScalaTestWithActorTestKit with W import CustomGuardianAndMaterializerSpec._ val guardian = Behaviors.receive[GuardianProtocol] { - (_, msg) ⇒ Behaviors.same + (_, msg) => Behaviors.same } implicit val mat = ActorMaterializer() @@ -43,11 +43,11 @@ class CustomGuardianAndMaterializerSpec extends ScalaTestWithActorTestKit with W "should kill streams with bound actor context" in { var doneF: Future[Done] = null val behavior = - Behaviors.setup[String] { ctx ⇒ + Behaviors.setup[String] { ctx => implicit val mat: ActorMaterializer = ActorMaterializer.boundToActor(ctx) doneF = Source.repeat("hello").runWith(Sink.ignore) - Behaviors.receiveMessage[String](_ ⇒ Behaviors.stopped) + Behaviors.receiveMessage[String](_ => Behaviors.stopped) } val actorRef = spawn(behavior) diff --git a/akka-stream-typed/src/test/scala/docs/akka/stream/typed/ActorSourceSinkExample.scala b/akka-stream-typed/src/test/scala/docs/akka/stream/typed/ActorSourceSinkExample.scala index 10a3bb828b..9d22ca2610 100644 --- a/akka-stream-typed/src/test/scala/docs/akka/stream/typed/ActorSourceSinkExample.scala +++ b/akka-stream-typed/src/test/scala/docs/akka/stream/typed/ActorSourceSinkExample.scala @@ -28,17 +28,17 @@ object ActorSourceSinkExample { val source: Source[Protocol, ActorRef[Protocol]] = ActorSource.actorRef[Protocol]( completionMatcher = { - case Complete ⇒ + case Complete => }, failureMatcher = { - case Fail(ex) ⇒ ex + case Fail(ex) => ex }, bufferSize = 8, overflowStrategy = OverflowStrategy.fail ) val ref = source.collect { - case Message(msg) ⇒ msg + case Message(msg) => msg }.to(Sink.foreach(println)).run() ref ! Message("msg1") diff --git a/akka-stream/src/main/boilerplate/akka/stream/javadsl/GraphCreate.scala.template b/akka-stream/src/main/boilerplate/akka/stream/javadsl/GraphCreate.scala.template index 2cb712eedf..909b20e236 100644 --- a/akka-stream/src/main/boilerplate/akka/stream/javadsl/GraphCreate.scala.template +++ b/akka-stream/src/main/boilerplate/akka/stream/javadsl/GraphCreate.scala.template @@ -14,7 +14,7 @@ private[stream] abstract class GraphCreate { * Creates a new [[Graph]] of the given [[Shape]] by passing a [[GraphDSL.Builder]] to the given create function. */ def create[S <: Shape](block: function.Function[GraphDSL.Builder[NotUsed], S]): Graph[S, NotUsed] = - scaladsl.GraphDSL.create() { b ⇒ block.apply(b.asJava) } + scaladsl.GraphDSL.create() { b => block.apply(b.asJava) } /** * Creates a new [[Graph]] by importing the given graph `g1` and its [[Shape]] @@ -22,7 +22,7 @@ private[stream] abstract class GraphCreate { */ def create[S1 <: Shape, S <: Shape, M](g1: Graph[S1, M], block: function.Function2[GraphDSL.Builder[M], S1, S]): Graph[S, M] = - scaladsl.GraphDSL.create(g1) { b ⇒ s => block.apply(b.asJava, s) } + scaladsl.GraphDSL.create(g1) { b => s => block.apply(b.asJava, s) } /** * Creates a new [[Graph]] by importing the given graphs and passing their [[Shape]]s diff --git a/akka-stream/src/main/boilerplate/akka/stream/scaladsl/GraphApply.scala.template b/akka-stream/src/main/boilerplate/akka/stream/scaladsl/GraphApply.scala.template index ffee4337d4..53755dd418 100644 --- a/akka-stream/src/main/boilerplate/akka/stream/scaladsl/GraphApply.scala.template +++ b/akka-stream/src/main/boilerplate/akka/stream/scaladsl/GraphApply.scala.template @@ -11,7 +11,7 @@ trait GraphApply { /** * Creates a new [[Graph]] by passing a [[GraphDSL.Builder]] to the given create function. */ - def create[S <: Shape]()(buildBlock: GraphDSL.Builder[NotUsed] ⇒ S): Graph[S, NotUsed] = { + def create[S <: Shape]()(buildBlock: GraphDSL.Builder[NotUsed] => S): Graph[S, NotUsed] = { val builder = new GraphDSL.Builder val s = buildBlock(builder) @@ -22,7 +22,7 @@ trait GraphApply { * Creates a new [[Graph]] by importing the given graph `g1` and passing its [[Shape]] * along with the [[GraphDSL.Builder]] to the given create function. */ - def create[S <: Shape, Mat](g1: Graph[Shape, Mat])(buildBlock: GraphDSL.Builder[Mat] ⇒ (g1.Shape) ⇒ S): Graph[S, Mat] = { + def create[S <: Shape, Mat](g1: Graph[Shape, Mat])(buildBlock: GraphDSL.Builder[Mat] => (g1.Shape) => S): Graph[S, Mat] = { val builder = new GraphDSL.Builder val s1 = builder.add(g1, Keep.right) val s = buildBlock(builder)(s1) @@ -37,11 +37,11 @@ trait GraphApply { * Creates a new [[Graph]] by importing the given graphs and passing their [[Shape]]s * along with the [[GraphDSL.Builder]] to the given create function. */ - def create[S <: Shape, Mat, [#M1#]]([#g1: Graph[Shape, M1]#])(combineMat: ([#M1#]) ⇒ Mat)(buildBlock: GraphDSL.Builder[Mat] ⇒ ([#g1.Shape#]) ⇒ S): Graph[S, Mat] = { + def create[S <: Shape, Mat, [#M1#]]([#g1: Graph[Shape, M1]#])(combineMat: ([#M1#]) => Mat)(buildBlock: GraphDSL.Builder[Mat] => ([#g1.Shape#]) => S): Graph[S, Mat] = { val builder = new GraphDSL.Builder val curried = combineMat.curried - val s##1 = builder.add(g##1, (m##1: M##1) ⇒ curried(m##1)) - [2..#val s1 = builder.add(g1, (f: M1 ⇒ Any, m1: M1) ⇒ f(m1))# + val s##1 = builder.add(g##1, (m##1: M##1) => curried(m##1)) + [2..#val s1 = builder.add(g1, (f: M1 => Any, m1: M1) => f(m1))# ] val s = buildBlock(builder)([#s1#]) diff --git a/akka-stream/src/main/boilerplate/akka/stream/scaladsl/UnzipWithApply.scala.template b/akka-stream/src/main/boilerplate/akka/stream/scaladsl/UnzipWithApply.scala.template index 59b5548958..f242d5e8c9 100644 --- a/akka-stream/src/main/boilerplate/akka/stream/scaladsl/UnzipWithApply.scala.template +++ b/akka-stream/src/main/boilerplate/akka/stream/scaladsl/UnzipWithApply.scala.template @@ -14,7 +14,7 @@ object UnzipWithApply { } [2..22#trait UnzipWithCreator1[In, [#A1#]] extends UnzipWithCreator[In, Tuple1[[#A1#]], UnzipWith1[In, [#A1#]]] { - override def create(unzipper: In ⇒ ([#A1#])): UnzipWith1[In, [#A1#]] = { + override def create(unzipper: In => ([#A1#])): UnzipWith1[In, [#A1#]] = { new UnzipWith1(unzipper) } } @@ -33,7 +33,7 @@ trait UnzipWithApply { * * @param unzipper unzipping-function from the input value to 1 output values */ - def apply[In, [#A1#]](unzipper: In ⇒ Tuple1[[#A1#]])(implicit creator: UnzipWithCreator1[Any, [#Any#]]): UnzipWith1[In, [#A1#]] = { + def apply[In, [#A1#]](unzipper: In => Tuple1[[#A1#]])(implicit creator: UnzipWithCreator1[Any, [#Any#]]): UnzipWith1[In, [#A1#]] = { creator.asInstanceOf[UnzipWithCreator1[In, [#A1#]]].create(unzipper) }# @@ -41,7 +41,7 @@ trait UnzipWithApply { } [2..22#/** `UnzipWith` specialized for 1 outputs */ -class UnzipWith1[In, [#A1#]](val unzipper: In ⇒ ([#A1#])) extends GraphStage[FanOutShape1[In, [#A1#]]] { +class UnzipWith1[In, [#A1#]](val unzipper: In => ([#A1#])) extends GraphStage[FanOutShape1[In, [#A1#]]] { override def initialAttributes = Attributes.name("UnzipWith1") override val shape: FanOutShape1[In, [#A1#]] = new FanOutShape1[In, [#A1#]]("UnzipWith1") def in: Inlet[In] = shape.in diff --git a/akka-stream/src/main/boilerplate/akka/stream/scaladsl/ZipLatestWithApply.scala.template b/akka-stream/src/main/boilerplate/akka/stream/scaladsl/ZipLatestWithApply.scala.template index 35a0af15ad..571ae00ad5 100644 --- a/akka-stream/src/main/boilerplate/akka/stream/scaladsl/ZipLatestWithApply.scala.template +++ b/akka-stream/src/main/boilerplate/akka/stream/scaladsl/ZipLatestWithApply.scala.template @@ -14,7 +14,7 @@ trait ZipLatestWithApply { * * @param zipper zipping-function from the input values to the output value */ - def apply[[#A1#], O](zipper: ([#A1#]) ⇒ O): ZipLatestWith1[[#A1#], O] = + def apply[[#A1#], O](zipper: ([#A1#]) => O): ZipLatestWith1[[#A1#], O] = new ZipLatestWith1(zipper) # @@ -23,7 +23,7 @@ trait ZipLatestWithApply { } [2..22#/** `ZipLatestWith` specialized for 1 inputs */ -class ZipLatestWith1[[#A1#], O] (val zipper: ([#A1#]) ⇒ O) extends GraphStage[FanInShape1[[#A1#], O]] { +class ZipLatestWith1[[#A1#], O] (val zipper: ([#A1#]) => O) extends GraphStage[FanInShape1[[#A1#], O]] { override def initialAttributes = Attributes.name("ZipLatestWith1") override val shape: FanInShape1[[#A1#], O] = new FanInShape1[[#A1#], O]("ZipLatestWith1") def out: Outlet[O] = shape.out diff --git a/akka-stream/src/main/boilerplate/akka/stream/scaladsl/ZipWithApply.scala.template b/akka-stream/src/main/boilerplate/akka/stream/scaladsl/ZipWithApply.scala.template index ac8d77082f..c9507acfaf 100644 --- a/akka-stream/src/main/boilerplate/akka/stream/scaladsl/ZipWithApply.scala.template +++ b/akka-stream/src/main/boilerplate/akka/stream/scaladsl/ZipWithApply.scala.template @@ -14,7 +14,7 @@ trait ZipWithApply { * * @param zipper zipping-function from the input values to the output value */ - def apply[[#A1#], O](zipper: ([#A1#]) ⇒ O): ZipWith1[[#A1#], O] = + def apply[[#A1#], O](zipper: ([#A1#]) => O): ZipWith1[[#A1#], O] = new ZipWith1(zipper) # @@ -23,7 +23,7 @@ trait ZipWithApply { } [2..22#/** `ZipWith` specialized for 1 inputs */ -class ZipWith1[[#A1#], O] (val zipper: ([#A1#]) ⇒ O) extends GraphStage[FanInShape1[[#A1#], O]] { +class ZipWith1[[#A1#], O] (val zipper: ([#A1#]) => O) extends GraphStage[FanInShape1[[#A1#], O]] { override def initialAttributes = Attributes.name("ZipWith1") override val shape: FanInShape1[[#A1#], O] = new FanInShape1[[#A1#], O]("ZipWith1") def out: Outlet[O] = shape.out diff --git a/akka-stream/src/main/scala-jdk-9/akka/stream/impl/JavaFlowAndRsConverters.scala b/akka-stream/src/main/scala-jdk-9/akka/stream/impl/JavaFlowAndRsConverters.scala index 77b260a9c0..0a4999daa3 100644 --- a/akka-stream/src/main/scala-jdk-9/akka/stream/impl/JavaFlowAndRsConverters.scala +++ b/akka-stream/src/main/scala-jdk-9/akka/stream/impl/JavaFlowAndRsConverters.scala @@ -7,7 +7,7 @@ package akka.stream.impl import java.util.concurrent.Flow import akka.annotation.InternalApi -import org.{ reactivestreams ⇒ rs } +import org.{ reactivestreams => rs } import JavaFlowAndRsConverters.Implicits._ /** @@ -62,48 +62,48 @@ private[akka] object JavaFlowAndRsConverters { } final def asJava[T](p: rs.Publisher[T]): Flow.Publisher[T] = p match { - case null ⇒ null // null remains null - case adapter: JavaFlowPublisherToRsAdapter[T] ⇒ adapter.delegate // unwrap adapter instead of wrapping again - case delegate ⇒ new RsPublisherToJavaFlowAdapter(delegate) // adapt, it is a real Publisher + case null => null // null remains null + case adapter: JavaFlowPublisherToRsAdapter[T] => adapter.delegate // unwrap adapter instead of wrapping again + case delegate => new RsPublisherToJavaFlowAdapter(delegate) // adapt, it is a real Publisher } final def asRs[T](p: Flow.Publisher[T]): rs.Publisher[T] = p match { - case null ⇒ null // null remains null - case adapter: RsPublisherToJavaFlowAdapter[T] ⇒ adapter.delegate // unwrap adapter instead of wrapping again - case _ ⇒ new JavaFlowPublisherToRsAdapter[T](p) + case null => null // null remains null + case adapter: RsPublisherToJavaFlowAdapter[T] => adapter.delegate // unwrap adapter instead of wrapping again + case _ => new JavaFlowPublisherToRsAdapter[T](p) } final def asJava[T](s: rs.Subscription): Flow.Subscription = s match { - case null ⇒ null // null remains null - case adapter: JavaFlowSubscriptionToRsAdapter ⇒ adapter.delegate // unwrap adapter instead of wrapping again - case _ ⇒ new RsSubscriptionToJavaFlowAdapter(s) + case null => null // null remains null + case adapter: JavaFlowSubscriptionToRsAdapter => adapter.delegate // unwrap adapter instead of wrapping again + case _ => new RsSubscriptionToJavaFlowAdapter(s) } final def asRs[T](s: Flow.Subscription): rs.Subscription = s match { - case null ⇒ null // null remains null - case adapter: RsSubscriptionToJavaFlowAdapter ⇒ adapter.delegate // unwrap adapter instead of wrapping again - case _ ⇒ new JavaFlowSubscriptionToRsAdapter(s) + case null => null // null remains null + case adapter: RsSubscriptionToJavaFlowAdapter => adapter.delegate // unwrap adapter instead of wrapping again + case _ => new JavaFlowSubscriptionToRsAdapter(s) } final def asJava[T](s: rs.Subscriber[T]): Flow.Subscriber[T] = s match { - case null ⇒ null // null remains null - case adapter: JavaFlowSubscriberToRsAdapter[T] ⇒ adapter.delegate // unwrap adapter instead of wrapping again - case _ ⇒ new RsSubscriberToJavaFlowAdapter[T](s) + case null => null // null remains null + case adapter: JavaFlowSubscriberToRsAdapter[T] => adapter.delegate // unwrap adapter instead of wrapping again + case _ => new RsSubscriberToJavaFlowAdapter[T](s) } final def asRs[T](s: Flow.Subscriber[T]): rs.Subscriber[T] = s match { - case null ⇒ null // null remains null - case adapter: RsSubscriberToJavaFlowAdapter[T] ⇒ adapter.delegate // unwrap adapter instead of wrapping again - case _ ⇒ new JavaFlowSubscriberToRsAdapter[T](s) + case null => null // null remains null + case adapter: RsSubscriberToJavaFlowAdapter[T] => adapter.delegate // unwrap adapter instead of wrapping again + case _ => new JavaFlowSubscriberToRsAdapter[T](s) } final def asJava[T, R](p: rs.Processor[T, R]): Flow.Processor[T, R] = p match { - case null ⇒ null // null remains null - case adapter: JavaFlowProcessorToRsAdapter[T, R] ⇒ adapter.delegate // unwrap adapter instead of wrapping again - case _ ⇒ new RsProcessorToJavaFlowAdapter[T, R](p) + case null => null // null remains null + case adapter: JavaFlowProcessorToRsAdapter[T, R] => adapter.delegate // unwrap adapter instead of wrapping again + case _ => new RsProcessorToJavaFlowAdapter[T, R](p) } final def asRs[T, R](p: Flow.Processor[T, R]): rs.Processor[T, R] = p match { - case null ⇒ null // null remains null - case adapter: RsProcessorToJavaFlowAdapter[T, R] ⇒ adapter.delegate // unwrap adapter instead of wrapping again - case _ ⇒ new JavaFlowProcessorToRsAdapter[T, R](p) + case null => null // null remains null + case adapter: RsProcessorToJavaFlowAdapter[T, R] => adapter.delegate // unwrap adapter instead of wrapping again + case _ => new JavaFlowProcessorToRsAdapter[T, R](p) } } diff --git a/akka-stream/src/main/scala-jdk-9/akka/stream/scaladsl/JavaFlowSupport.scala b/akka-stream/src/main/scala-jdk-9/akka/stream/scaladsl/JavaFlowSupport.scala index 7761b57ea1..6a139ee1c3 100644 --- a/akka-stream/src/main/scala-jdk-9/akka/stream/scaladsl/JavaFlowSupport.scala +++ b/akka-stream/src/main/scala-jdk-9/akka/stream/scaladsl/JavaFlowSupport.scala @@ -4,7 +4,7 @@ package akka.stream.scaladsl -import java.util.{ concurrent ⇒ juc } +import java.util.{ concurrent => juc } import akka.NotUsed import akka.stream.impl.JavaFlowAndRsConverters @@ -58,15 +58,15 @@ object JavaFlowSupport { /** * Creates a Flow from a Reactive Streams [[org.reactivestreams.Processor]] */ - def fromProcessor[I, O](processorFactory: () ⇒ juc.Flow.Processor[I, O]): Flow[I, O, NotUsed] = { - fromProcessorMat(() ⇒ (processorFactory(), NotUsed)) + def fromProcessor[I, O](processorFactory: () => juc.Flow.Processor[I, O]): Flow[I, O, NotUsed] = { + fromProcessorMat(() => (processorFactory(), NotUsed)) } /** * Creates a Flow from a Reactive Streams [[java.util.concurrent.Flow.Processor]] and returns a materialized value. */ - def fromProcessorMat[I, O, M](processorFactory: () ⇒ (juc.Flow.Processor[I, O], M)): Flow[I, O, M] = - scaladsl.Flow.fromProcessorMat { () ⇒ + def fromProcessorMat[I, O, M](processorFactory: () => (juc.Flow.Processor[I, O], M)): Flow[I, O, M] = + scaladsl.Flow.fromProcessorMat { () => val (processor, mat) = processorFactory() (processor.asRs, mat) } @@ -82,7 +82,7 @@ object JavaFlowSupport { Source.asSubscriber[In].via(self) .toMat(Sink.asPublisher[Out](fanout = false))(Keep.both) .mapMaterializedValue { - case (sub, pub) ⇒ new juc.Flow.Processor[In, Out] { + case (sub, pub) => new juc.Flow.Processor[In, Out] { override def onError(t: Throwable): Unit = sub.onError(t) override def onSubscribe(s: juc.Flow.Subscription): Unit = sub.onSubscribe(s) override def onComplete(): Unit = sub.onComplete() diff --git a/akka-stream/src/main/scala/akka/stream/ActorMaterializer.scala b/akka-stream/src/main/scala/akka/stream/ActorMaterializer.scala index e7a65a656e..5fabf5fd7d 100644 --- a/akka-stream/src/main/scala/akka/stream/ActorMaterializer.scala +++ b/akka-stream/src/main/scala/akka/stream/ActorMaterializer.scala @@ -70,8 +70,8 @@ object ActorMaterializer { private def actorOfStreamSupervisor(materializerSettings: ActorMaterializerSettings, context: ActorRefFactory, haveShutDown: AtomicBoolean) = { val props = StreamSupervisor.props(materializerSettings, haveShutDown) context match { - case s: ExtendedActorSystem ⇒ s.systemActorOf(props, StreamSupervisor.nextName()) - case a: ActorContext ⇒ a.actorOf(props, StreamSupervisor.nextName()) + case s: ExtendedActorSystem => s.systemActorOf(props, StreamSupervisor.nextName()) + case a: ActorContext => a.actorOf(props, StreamSupervisor.nextName()) } } @@ -148,10 +148,10 @@ object ActorMaterializer { private def actorSystemOf(context: ActorRefFactory): ActorSystem = { val system = context match { - case s: ExtendedActorSystem ⇒ s - case c: ActorContext ⇒ c.system - case null ⇒ throw new IllegalArgumentException("ActorRefFactory context must be defined") - case _ ⇒ + case s: ExtendedActorSystem => s + case c: ActorContext => c.system + case null => throw new IllegalArgumentException("ActorRefFactory context must be defined") + case _ => throw new IllegalArgumentException(s"ActorRefFactory context must be an ActorSystem or ActorContext, got [${context.getClass.getName}]") } system @@ -168,8 +168,8 @@ private[akka] object ActorMaterializerHelper { */ private[akka] def downcast(materializer: Materializer): ActorMaterializer = materializer match { //FIXME this method is going to cause trouble for other Materializer implementations - case m: ActorMaterializer ⇒ m - case _ ⇒ throw new IllegalArgumentException(s"required [${classOf[ActorMaterializer].getName}] " + + case m: ActorMaterializer => m + case _ => throw new IllegalArgumentException(s"required [${classOf[ActorMaterializer].getName}] " + s"but got [${materializer.getClass.getName}]") } } @@ -497,10 +497,10 @@ final class ActorMaterializerSettings @InternalApi private ( def withSupervisionStrategy(decider: function.Function[Throwable, Supervision.Directive]): ActorMaterializerSettings = { import Supervision._ copy(supervisionDecider = decider match { - case `resumingDecider` ⇒ resumingDecider - case `restartingDecider` ⇒ restartingDecider - case `stoppingDecider` ⇒ stoppingDecider - case other ⇒ other.apply _ + case `resumingDecider` => resumingDecider + case `restartingDecider` => restartingDecider + case `stoppingDecider` => stoppingDecider + case other => other.apply _ }) } @@ -579,7 +579,7 @@ final class ActorMaterializerSettings @InternalApi private ( } override def equals(other: Any): Boolean = other match { - case s: ActorMaterializerSettings ⇒ + case s: ActorMaterializerSettings => s.initialInputBufferSize == initialInputBufferSize && s.maxInputBufferSize == maxInputBufferSize && s.dispatcher == dispatcher && @@ -592,7 +592,7 @@ final class ActorMaterializerSettings @InternalApi private ( s.autoFusing == autoFusing && s.ioSettings == ioSettings && s.blockingIoDispatcher == blockingIoDispatcher - case _ ⇒ false + case _ => false } override def toString: String = s"ActorMaterializerSettings($initialInputBufferSize,$maxInputBufferSize," + @@ -630,8 +630,8 @@ final class IOSettings private (val tcpWriteBufferSize: Int) { tcpWriteBufferSize = tcpWriteBufferSize) override def equals(other: Any): Boolean = other match { - case s: IOSettings ⇒ s.tcpWriteBufferSize == tcpWriteBufferSize - case _ ⇒ false + case s: IOSettings => s.tcpWriteBufferSize == tcpWriteBufferSize + case _ => false } override def toString = @@ -666,9 +666,9 @@ object StreamSubscriptionTimeoutSettings { val c = config.getConfig("subscription-timeout") StreamSubscriptionTimeoutSettings( mode = toRootLowerCase(c.getString("mode")) match { - case "no" | "off" | "false" | "noop" ⇒ NoopTermination - case "warn" ⇒ WarnTermination - case "cancel" ⇒ CancelTermination + case "no" | "off" | "false" | "noop" => NoopTermination + case "warn" => WarnTermination + case "cancel" => CancelTermination }, timeout = c.getDuration("timeout", TimeUnit.MILLISECONDS).millis) } @@ -680,8 +680,8 @@ object StreamSubscriptionTimeoutSettings { */ final class StreamSubscriptionTimeoutSettings(val mode: StreamSubscriptionTimeoutTerminationMode, val timeout: FiniteDuration) { override def equals(other: Any): Boolean = other match { - case s: StreamSubscriptionTimeoutSettings ⇒ s.mode == mode && s.timeout == timeout - case _ ⇒ false + case s: StreamSubscriptionTimeoutSettings => s.mode == mode && s.timeout == timeout + case _ => false } override def toString: String = s"StreamSubscriptionTimeoutSettings($mode,$timeout)" } diff --git a/akka-stream/src/main/scala/akka/stream/Attributes.scala b/akka-stream/src/main/scala/akka/stream/Attributes.scala index e6dc60de5f..01c1c17439 100644 --- a/akka-stream/src/main/scala/akka/stream/Attributes.scala +++ b/akka-stream/src/main/scala/akka/stream/Attributes.scala @@ -44,9 +44,9 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { */ private[stream] def isAsync: Boolean = { attributeList.nonEmpty && attributeList.exists { - case AsyncBoundary ⇒ true - case ActorAttributes.Dispatcher(_) ⇒ true - case _ ⇒ false + case AsyncBoundary => true + case ActorAttributes.Dispatcher(_) => true + case _ => false } } @@ -71,7 +71,7 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { * This is the expected way for operators to access attributes. */ def getAttribute[T <: Attribute](c: Class[T]): Optional[T] = - attributeList.collectFirst { case attr if c.isInstance(attr) ⇒ c.cast(attr) }.asJava + attributeList.collectFirst { case attr if c.isInstance(attr) => c.cast(attr) }.asJava /** * Scala API: Get the most specific attribute value for a given Attribute type or subclass thereof or @@ -84,8 +84,8 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { */ def get[T <: Attribute: ClassTag](default: T): T = get[T] match { - case Some(a) ⇒ a - case None ⇒ default + case Some(a) => a + case None => default } /** @@ -100,7 +100,7 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { */ def get[T <: Attribute: ClassTag]: Option[T] = { val c = classTag[T].runtimeClass.asInstanceOf[Class[T]] - attributeList.collectFirst { case attr if c.isInstance(attr) ⇒ c.cast(attr) } + attributeList.collectFirst { case attr if c.isInstance(attr) => c.cast(attr) } } /** @@ -121,15 +121,15 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { def getMandatoryAttribute[T <: MandatoryAttribute](c: Class[T]): T = { @tailrec def find(list: List[Attribute]): OptionVal[Attribute] = list match { - case Nil ⇒ OptionVal.None - case head :: tail ⇒ + case Nil => OptionVal.None + case head :: tail => if (c.isInstance(head)) OptionVal.Some(head) else find(tail) } find(attributeList) match { - case OptionVal.Some(t) ⇒ t.asInstanceOf[T] - case OptionVal.None ⇒ throw new IllegalStateException(s"Mandatory attribute [$c] not found") + case OptionVal.Some(t) => t.asInstanceOf[T] + case OptionVal.None => throw new IllegalStateException(s"Mandatory attribute [$c] not found") } } @@ -158,13 +158,13 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { @tailrec def concatNames(i: Iterator[Attribute], first: String, buf: java.lang.StringBuilder): String = if (i.hasNext) i.next() match { - case Name(n) ⇒ + case Name(n) => if (buf ne null) concatNames(i, null, buf.append('-').append(n)) else if (first ne null) { val b = new java.lang.StringBuilder((first.length + n.length) * 2) concatNames(i, null, b.append(first).append('-').append(n)) } else concatNames(i, n, null) - case _ ⇒ concatNames(i, first, buf) + case _ => concatNames(i, first, buf) } else if (buf eq null) first else buf.toString @@ -177,9 +177,9 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { */ @InternalApi def nameOrDefault(default: String = "unnamed"): String = { @tailrec def find(attrs: List[Attribute]): String = attrs match { - case Attributes.Name(name) :: _ ⇒ name - case _ :: tail ⇒ find(tail) - case Nil ⇒ default + case Attributes.Name(name) :: _ => name + case _ :: tail => find(tail) + case Nil => default } find(attributeList) } @@ -220,7 +220,7 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { if (attributeList.isEmpty) java.util.Collections.emptyList() else { val result = new java.util.ArrayList[T] - attributeList.foreach { a ⇒ + attributeList.foreach { a => if (c.isInstance(a)) result.add(c.cast(a)) } @@ -238,7 +238,7 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { */ def filtered[T <: Attribute: ClassTag]: List[T] = { val c = implicitly[ClassTag[T]].runtimeClass.asInstanceOf[Class[T]] - attributeList.collect { case attr if c.isAssignableFrom(attr.getClass) ⇒ c.cast(attr) } + attributeList.collect { case attr if c.isAssignableFrom(attr.getClass) => c.cast(attr) } } /** @@ -254,7 +254,7 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { */ @deprecated("Attributes should always be most specific, use get[T]", "2.5.7") def getFirstAttribute[T <: Attribute](c: Class[T]): Optional[T] = - attributeList.reverseIterator.collectFirst { case attr if c.isInstance(attr) ⇒ c cast attr }.asJava + attributeList.reverseIterator.collectFirst { case attr if c.isInstance(attr) => c cast attr }.asJava /** * Scala API: Get the least specific attribute (added first) of a given type parameter T `Class` or subclass thereof. @@ -263,8 +263,8 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { @deprecated("Attributes should always be most specific, use get[T]", "2.5.7") def getFirst[T <: Attribute: ClassTag](default: T): T = { getFirst[T] match { - case Some(a) ⇒ a - case None ⇒ default + case Some(a) => a + case None => default } } @@ -274,7 +274,7 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { @deprecated("Attributes should always be most specific, use get[T]", "2.5.7") def getFirst[T <: Attribute: ClassTag]: Option[T] = { val c = classTag[T].runtimeClass.asInstanceOf[Class[T]] - attributeList.reverseIterator.collectFirst { case attr if c.isInstance(attr) ⇒ c.cast(attr) } + attributeList.reverseIterator.collectFirst { case attr if c.isInstance(attr) => c.cast(attr) } } } @@ -400,8 +400,8 @@ object ActorAttributes { @InternalApi private[akka] def resolve(attributes: Attributes, settings: ActorMaterializerSettings): String = attributes.mandatoryAttribute[Dispatcher] match { - case IODispatcher ⇒ settings.blockingIoDispatcher - case Dispatcher(dispatcher) ⇒ dispatcher + case IODispatcher => settings.blockingIoDispatcher + case Dispatcher(dispatcher) => dispatcher } /** diff --git a/akka-stream/src/main/scala/akka/stream/FanInShape1N.scala b/akka-stream/src/main/scala/akka/stream/FanInShape1N.scala index 6d959ddec5..ff478894d2 100644 --- a/akka-stream/src/main/scala/akka/stream/FanInShape1N.scala +++ b/akka-stream/src/main/scala/akka/stream/FanInShape1N.scala @@ -13,7 +13,7 @@ class FanInShape1N[-T0, -T1, +O](val n: Int, _init: FanInShape.Init[O]) extends //ports get added to `FanInShape.inlets` as a side-effect of calling `newInlet` val in0: Inlet[T0 @uncheckedVariance] = newInlet[T0]("in0") - for (i ← 1 until n) newInlet[T1](s"in$i") + for (i <- 1 until n) newInlet[T1](s"in$i") def this(n: Int) = this(n, FanInShape.Name[O]("FanInShape1N")) def this(n: Int, name: String) = this(n, FanInShape.Name[O](name)) diff --git a/akka-stream/src/main/scala/akka/stream/IOResult.scala b/akka-stream/src/main/scala/akka/stream/IOResult.scala index 96cef4a59c..45810e83ab 100644 --- a/akka-stream/src/main/scala/akka/stream/IOResult.scala +++ b/akka-stream/src/main/scala/akka/stream/IOResult.scala @@ -35,8 +35,8 @@ final case class IOResult(count: Long, status: Try[Done]) { * or throws [[UnsupportedOperationException]] otherwise. */ def getError: Throwable = status match { - case Failure(t) ⇒ t - case Success(_) ⇒ throw new UnsupportedOperationException("IO operation was successful.") + case Failure(t) => t + case Success(_) => throw new UnsupportedOperationException("IO operation was successful.") } } diff --git a/akka-stream/src/main/scala/akka/stream/KillSwitch.scala b/akka-stream/src/main/scala/akka/stream/KillSwitch.scala index 40457808eb..38ee9b4d85 100644 --- a/akka-stream/src/main/scala/akka/stream/KillSwitch.scala +++ b/akka-stream/src/main/scala/akka/stream/KillSwitch.scala @@ -56,16 +56,16 @@ object KillSwitches { abstract class KillableGraphStageLogic(val terminationSignal: Future[Done], _shape: Shape) extends GraphStageLogic(_shape) { override def preStart(): Unit = { terminationSignal.value match { - case Some(status) ⇒ onSwitch(status) - case _ ⇒ + case Some(status) => onSwitch(status) + case _ => // callback.invoke is a simple actor send, so it is fine to run on the invoking thread terminationSignal.onComplete(getAsyncCallback[Try[Done]](onSwitch).invoke)(akka.dispatch.ExecutionContexts.sameThreadExecutionContext) } } private def onSwitch(mode: Try[Done]): Unit = mode match { - case Success(_) ⇒ completeStage() - case Failure(ex) ⇒ failStage(ex) + case Success(_) => completeStage() + case Failure(ex) => failStage(ex) } } @@ -161,18 +161,18 @@ private[stream] final class TerminationSignal { def tryComplete(result: Try[Done]): Unit = { if (_completedWith.compareAndSet(None, Some(result))) { - for ((listener, _) ← _listeners) listener.promise.tryComplete(result) + for ((listener, _) <- _listeners) listener.promise.tryComplete(result) } } def createListener(): Listener = { val listener = new Listener if (_completedWith.get.isEmpty) { - _listeners += (listener → NotUsed) + _listeners += (listener -> NotUsed) } _completedWith.get match { - case Some(result) ⇒ listener.promise.tryComplete(result) - case None ⇒ // Ignore. + case Some(result) => listener.promise.tryComplete(result) + case None => // Ignore. } listener } diff --git a/akka-stream/src/main/scala/akka/stream/MaterializerLoggingProvider.scala b/akka-stream/src/main/scala/akka/stream/MaterializerLoggingProvider.scala index 7969db1dae..db4c5a88d7 100644 --- a/akka-stream/src/main/scala/akka/stream/MaterializerLoggingProvider.scala +++ b/akka-stream/src/main/scala/akka/stream/MaterializerLoggingProvider.scala @@ -10,7 +10,7 @@ import akka.event.LoggingAdapter * SPI intended only to be extended by custom [[Materializer]] implementations, * that also want to provide operators they materialize with specialized [[akka.event.LoggingAdapter]] instances. */ -trait MaterializerLoggingProvider { this: Materializer ⇒ +trait MaterializerLoggingProvider { this: Materializer => def makeLogger(logSource: Class[_]): LoggingAdapter diff --git a/akka-stream/src/main/scala/akka/stream/Shape.scala b/akka-stream/src/main/scala/akka/stream/Shape.scala index f4311f79db..93f9997a8d 100644 --- a/akka-stream/src/main/scala/akka/stream/Shape.scala +++ b/akka-stream/src/main/scala/akka/stream/Shape.scala @@ -16,7 +16,7 @@ import akka.annotation.InternalApi * It is also used in the Java DSL for “untyped Inlets” as a work-around * for otherwise unreasonable existential types. */ -sealed abstract class InPort { self: Inlet[_] ⇒ +sealed abstract class InPort { self: Inlet[_] => final override def hashCode: Int = super.hashCode final override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef] @@ -41,7 +41,7 @@ sealed abstract class InPort { self: Inlet[_] ⇒ * It is also used in the Java DSL for “untyped Outlets” as a work-around * for otherwise unreasonable existential types. */ -sealed abstract class OutPort { self: Outlet[_] ⇒ +sealed abstract class OutPort { self: Outlet[_] => final override def hashCode: Int = super.hashCode final override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef] @@ -150,8 +150,8 @@ final class Outlet[T] private (val s: String) extends OutPort { */ def hasOnePort(ports: immutable.Seq[_]): Boolean = { ports.nonEmpty && (ports match { - case l: List[_] ⇒ l.tail.isEmpty // assuming List is most common - case _ ⇒ ports.size == 1 // e.g. Vector + case l: List[_] => l.tail.isEmpty // assuming List is most common + case _ => ports.size == 1 // e.g. Vector }) } } diff --git a/akka-stream/src/main/scala/akka/stream/Supervision.scala b/akka-stream/src/main/scala/akka/stream/Supervision.scala index 9724dd2a7f..14289336c8 100644 --- a/akka-stream/src/main/scala/akka/stream/Supervision.scala +++ b/akka-stream/src/main/scala/akka/stream/Supervision.scala @@ -4,7 +4,7 @@ package akka.stream -import akka.japi.{ function ⇒ japi } +import akka.japi.{ function => japi } object Supervision { sealed trait Directive diff --git a/akka-stream/src/main/scala/akka/stream/UniformFanInShape.scala b/akka-stream/src/main/scala/akka/stream/UniformFanInShape.scala index eaff768937..279df4ae24 100644 --- a/akka-stream/src/main/scala/akka/stream/UniformFanInShape.scala +++ b/akka-stream/src/main/scala/akka/stream/UniformFanInShape.scala @@ -15,7 +15,7 @@ object UniformFanInShape { class UniformFanInShape[-T, +O](val n: Int, _init: FanInShape.Init[O]) extends FanInShape[O](_init) { //ports get added to `FanInShape.inlets` as a side-effect of calling `newInlet` - for (i ← 0 until n) newInlet[T](s"in$i") + for (i <- 0 until n) newInlet[T](s"in$i") def this(n: Int) = this(n, FanInShape.Name[O]("UniformFanIn")) def this(n: Int, name: String) = this(n, FanInShape.Name[O](name)) diff --git a/akka-stream/src/main/scala/akka/stream/UniformFanOutShape.scala b/akka-stream/src/main/scala/akka/stream/UniformFanOutShape.scala index a282ce30ab..1dbce51b57 100644 --- a/akka-stream/src/main/scala/akka/stream/UniformFanOutShape.scala +++ b/akka-stream/src/main/scala/akka/stream/UniformFanOutShape.scala @@ -15,7 +15,7 @@ object UniformFanOutShape { class UniformFanOutShape[-I, +O](n: Int, _init: FanOutShape.Init[I @uncheckedVariance]) extends FanOutShape[I](_init) { //initialize by side-effect - for (i ← 0 until n) newOutlet[O](s"out$i") + for (i <- 0 until n) newOutlet[O](s"out$i") def this(n: Int) = this(n, FanOutShape.Name[I]("UniformFanOut")) def this(n: Int, name: String) = this(n, FanOutShape.Name[I](name)) diff --git a/akka-stream/src/main/scala/akka/stream/actor/ActorPublisher.scala b/akka-stream/src/main/scala/akka/stream/actor/ActorPublisher.scala index d973f6c4a9..26affe6bcd 100644 --- a/akka-stream/src/main/scala/akka/stream/actor/ActorPublisher.scala +++ b/akka-stream/src/main/scala/akka/stream/actor/ActorPublisher.scala @@ -188,18 +188,18 @@ trait ActorPublisher[T] extends Actor { * otherwise `onNext` will throw `IllegalStateException`. */ def onNext(element: T): Unit = lifecycleState match { - case Active | PreSubscriber ⇒ + case Active | PreSubscriber => if (demand > 0) { demand -= 1 tryOnNext(subscriber, element) } else throw new IllegalStateException( "onNext is not allowed when the stream has not requested elements, totalDemand was 0") - case _: ErrorEmitted ⇒ + case _: ErrorEmitted => throw new IllegalStateException("onNext must not be called after onError") - case Completed | CompleteThenStop ⇒ + case Completed | CompleteThenStop => throw new IllegalStateException("onNext must not be called after onComplete") - case Canceled ⇒ // drop + case Canceled => // drop } /** @@ -207,15 +207,15 @@ trait ActorPublisher[T] extends Actor { * call [[#onNext]], [[#onError]] and [[#onComplete]]. */ def onComplete(): Unit = lifecycleState match { - case Active | PreSubscriber ⇒ + case Active | PreSubscriber => lifecycleState = Completed if (subscriber ne null) // otherwise onComplete will be called when the subscription arrives try tryOnComplete(subscriber) finally subscriber = null - case Completed | CompleteThenStop ⇒ + case Completed | CompleteThenStop => throw new IllegalStateException("onComplete must only be called once") - case _: ErrorEmitted ⇒ + case _: ErrorEmitted => throw new IllegalStateException("onComplete must not be called after onError") - case Canceled ⇒ // drop + case Canceled => // drop } /** @@ -228,11 +228,11 @@ trait ActorPublisher[T] extends Actor { * will be delayed until such [[Subscriber]] arrives. */ def onCompleteThenStop(): Unit = lifecycleState match { - case Active | PreSubscriber ⇒ + case Active | PreSubscriber => lifecycleState = CompleteThenStop if (subscriber ne null) // otherwise onComplete will be called when the subscription arrives try tryOnComplete(subscriber) finally context.stop(self) - case _ ⇒ onComplete() + case _ => onComplete() } /** @@ -240,15 +240,15 @@ trait ActorPublisher[T] extends Actor { * call [[#onNext]], [[#onError]] and [[#onComplete]]. */ def onError(cause: Throwable): Unit = lifecycleState match { - case Active | PreSubscriber ⇒ + case Active | PreSubscriber => lifecycleState = ErrorEmitted(cause, stop = false) if (subscriber ne null) // otherwise onError will be called when the subscription arrives try tryOnError(subscriber, cause) finally subscriber = null - case _: ErrorEmitted ⇒ + case _: ErrorEmitted => throw new IllegalStateException("onError must only be called once") - case Completed | CompleteThenStop ⇒ + case Completed | CompleteThenStop => throw new IllegalStateException("onError must not be called after onComplete") - case Canceled ⇒ // drop + case Canceled => // drop } /** * Terminate the stream with failure. After that you are not allowed to @@ -260,18 +260,18 @@ trait ActorPublisher[T] extends Actor { * will be delayed until such [[Subscriber]] arrives. */ def onErrorThenStop(cause: Throwable): Unit = lifecycleState match { - case Active | PreSubscriber ⇒ + case Active | PreSubscriber => lifecycleState = ErrorEmitted(cause, stop = true) if (subscriber ne null) // otherwise onError will be called when the subscription arrives try tryOnError(subscriber, cause) finally context.stop(self) - case _ ⇒ onError(cause) + case _ => onError(cause) } /** * INTERNAL API */ protected[akka] override def aroundReceive(receive: Receive, msg: Any): Unit = msg match { - case req @ Request(n) ⇒ + case req @ Request(n) => if (req.isProcessed()) { // it's an unstashed Request, demand is already handled super.aroundReceive(receive, req) @@ -288,45 +288,45 @@ trait ActorPublisher[T] extends Actor { } } - case Subscribe(sub: Subscriber[_]) ⇒ + case Subscribe(sub: Subscriber[_]) => lifecycleState match { - case PreSubscriber ⇒ + case PreSubscriber => scheduledSubscriptionTimeout.cancel() subscriber = sub lifecycleState = Active tryOnSubscribe(sub, new ActorPublisherSubscription(self)) - case ErrorEmitted(cause, stop) ⇒ + case ErrorEmitted(cause, stop) => if (stop) context.stop(self) tryOnSubscribe(sub, CancelledSubscription) tryOnError(sub, cause) - case Completed ⇒ + case Completed => tryOnSubscribe(sub, CancelledSubscription) tryOnComplete(sub) - case CompleteThenStop ⇒ + case CompleteThenStop => context.stop(self) tryOnSubscribe(sub, CancelledSubscription) tryOnComplete(sub) - case Active | Canceled ⇒ + case Active | Canceled => if (subscriber eq sub) rejectDuplicateSubscriber(sub) else rejectAdditionalSubscriber(sub, "ActorPublisher") } - case Cancel ⇒ + case Cancel => if (lifecycleState != Canceled) { // possible to receive again in case of stash cancelSelf() super.aroundReceive(receive, msg) } - case SubscriptionTimeoutExceeded ⇒ + case SubscriptionTimeoutExceeded => if (!scheduledSubscriptionTimeout.isCancelled) { cancelSelf() super.aroundReceive(receive, msg) } - case _ ⇒ + case _ => super.aroundReceive(receive, msg) } @@ -344,9 +344,9 @@ trait ActorPublisher[T] extends Actor { import context.dispatcher subscriptionTimeout match { - case timeout: FiniteDuration ⇒ + case timeout: FiniteDuration => scheduledSubscriptionTimeout = context.system.scheduler.scheduleOnce(timeout, self, SubscriptionTimeoutExceeded) - case _ ⇒ + case _ => // ignore... } } @@ -364,7 +364,7 @@ trait ActorPublisher[T] extends Actor { * INTERNAL API */ protected[akka] override def aroundPostRestart(reason: Throwable): Unit = { - state.get(self) foreach { s ⇒ + state.get(self) foreach { s => // restore previous state subscriber = s.subscriber.orNull demand = s.demand diff --git a/akka-stream/src/main/scala/akka/stream/actor/ActorSubscriber.scala b/akka-stream/src/main/scala/akka/stream/actor/ActorSubscriber.scala index bbdedd794d..ebe51335a2 100644 --- a/akka-stream/src/main/scala/akka/stream/actor/ActorSubscriber.scala +++ b/akka-stream/src/main/scala/akka/stream/actor/ActorSubscriber.scala @@ -180,13 +180,13 @@ trait ActorSubscriber extends Actor { * INTERNAL API */ protected[akka] override def aroundReceive(receive: Receive, msg: Any): Unit = msg match { - case _: OnNext ⇒ + case _: OnNext => requested -= 1 if (!_canceled) { super.aroundReceive(receive, msg) request(requestStrategy.requestDemand(remainingRequested)) } - case OnSubscribe(sub) ⇒ + case OnSubscribe(sub) => if (subscription.isEmpty) { subscription = Some(sub) if (_canceled) { @@ -196,12 +196,12 @@ trait ActorSubscriber extends Actor { sub.request(remainingRequested) } else sub.cancel() - case OnComplete | OnError(_) ⇒ + case OnComplete | OnError(_) => if (!_canceled) { _canceled = true super.aroundReceive(receive, msg) } - case _ ⇒ + case _ => super.aroundReceive(receive, msg) request(requestStrategy.requestDemand(remainingRequested)) } @@ -218,7 +218,7 @@ trait ActorSubscriber extends Actor { * INTERNAL API */ protected[akka] override def aroundPostRestart(reason: Throwable): Unit = { - state.get(self) foreach { s ⇒ + state.get(self) foreach { s => // restore previous state subscription = s.subscription requested = s.requested @@ -268,10 +268,10 @@ trait ActorSubscriber extends Actor { protected def cancel(): Unit = if (!_canceled) { subscription match { - case Some(s) ⇒ + case Some(s) => context.stop(self) s.cancel() - case _ ⇒ + case _ => _canceled = true // cancel will be signaled once a subscription arrives } } diff --git a/akka-stream/src/main/scala/akka/stream/extra/Implicits.scala b/akka-stream/src/main/scala/akka/stream/extra/Implicits.scala index f15bd2864e..5993ec95be 100644 --- a/akka-stream/src/main/scala/akka/stream/extra/Implicits.scala +++ b/akka-stream/src/main/scala/akka/stream/extra/Implicits.scala @@ -23,13 +23,13 @@ object Implicits { /** * Measures time from receiving the first element and completion events - one for each subscriber of this `Flow`. */ - def timed[O, Mat2](measuredOps: Source[I, Mat] ⇒ Source[O, Mat2], onComplete: FiniteDuration ⇒ Unit): Source[O, Mat2] = + def timed[O, Mat2](measuredOps: Source[I, Mat] => Source[O, Mat2], onComplete: FiniteDuration => Unit): Source[O, Mat2] = Timed.timed[I, O, Mat, Mat2](source, measuredOps, onComplete) /** * Measures rolling interval between immediately subsequent `matching(o: O)` elements. */ - def timedIntervalBetween(matching: I ⇒ Boolean, onInterval: FiniteDuration ⇒ Unit): Source[I, Mat] = + def timedIntervalBetween(matching: I => Boolean, onInterval: FiniteDuration => Unit): Source[I, Mat] = Timed.timedIntervalBetween[I, Mat](source, matching, onInterval) } @@ -43,13 +43,13 @@ object Implicits { /** * Measures time from receiving the first element and completion events - one for each subscriber of this `Flow`. */ - def timed[Out, Mat2](measuredOps: Flow[I, O, Mat] ⇒ Flow[I, Out, Mat2], onComplete: FiniteDuration ⇒ Unit): Flow[I, Out, Mat2] = + def timed[Out, Mat2](measuredOps: Flow[I, O, Mat] => Flow[I, Out, Mat2], onComplete: FiniteDuration => Unit): Flow[I, Out, Mat2] = Timed.timed[I, O, Out, Mat, Mat2](flow, measuredOps, onComplete) /** * Measures rolling interval between immediately subsequent `matching(o: O)` elements. */ - def timedIntervalBetween(matching: O ⇒ Boolean, onInterval: FiniteDuration ⇒ Unit): Flow[I, O, Mat] = + def timedIntervalBetween(matching: O => Boolean, onInterval: FiniteDuration => Unit): Flow[I, O, Mat] = Timed.timedIntervalBetween[I, O, Mat](flow, matching, onInterval) } diff --git a/akka-stream/src/main/scala/akka/stream/extra/Timed.scala b/akka-stream/src/main/scala/akka/stream/extra/Timed.scala index 5732c798e9..d606b65757 100644 --- a/akka-stream/src/main/scala/akka/stream/extra/Timed.scala +++ b/akka-stream/src/main/scala/akka/stream/extra/Timed.scala @@ -26,7 +26,7 @@ private[akka] trait TimedOps { * Measures time from receiving the first element and completion events - one for each subscriber of this `Flow`. */ @deprecated("Moved to the akka/akka-stream-contrib project", since = "2.4.5") - def timed[I, O, Mat, Mat2](source: Source[I, Mat], measuredOps: Source[I, Mat] ⇒ Source[O, Mat2], onComplete: FiniteDuration ⇒ Unit): Source[O, Mat2] = { + def timed[I, O, Mat, Mat2](source: Source[I, Mat], measuredOps: Source[I, Mat] => Source[O, Mat2], onComplete: FiniteDuration => Unit): Source[O, Mat2] = { val ctx = new TimedFlowContext val startTimed = Flow[I].via(new StartTimed(ctx)).named("startTimed") @@ -41,7 +41,7 @@ private[akka] trait TimedOps { * Measures time from receiving the first element and completion events - one for each subscriber of this `Flow`. */ @deprecated("Moved to the akka/akka-stream-contrib project", since = "2.4.5") - def timed[I, O, Out, Mat, Mat2](flow: Flow[I, O, Mat], measuredOps: Flow[I, O, Mat] ⇒ Flow[I, Out, Mat2], onComplete: FiniteDuration ⇒ Unit): Flow[I, Out, Mat2] = { + def timed[I, O, Out, Mat, Mat2](flow: Flow[I, O, Mat], measuredOps: Flow[I, O, Mat] => Flow[I, Out, Mat2], onComplete: FiniteDuration => Unit): Flow[I, Out, Mat2] = { // todo is there any other way to provide this for Flow, without duplicating impl? // they do share a super-type (FlowOps), but all operations of FlowOps return path dependant type val ctx = new TimedFlowContext @@ -67,7 +67,7 @@ private[akka] trait TimedIntervalBetweenOps { * Measures rolling interval between immediately subsequent `matching(o: O)` elements. */ @deprecated("Moved to the akka/akka-stream-contrib project", since = "2.4.5") - def timedIntervalBetween[O, Mat](source: Source[O, Mat], matching: O ⇒ Boolean, onInterval: FiniteDuration ⇒ Unit): Source[O, Mat] = { + def timedIntervalBetween[O, Mat](source: Source[O, Mat], matching: O => Boolean, onInterval: FiniteDuration => Unit): Source[O, Mat] = { val timedInterval = Flow[O].via(new TimedInterval[O](matching, onInterval)).named("timedInterval") source.via(timedInterval) } @@ -76,7 +76,7 @@ private[akka] trait TimedIntervalBetweenOps { * Measures rolling interval between immediately subsequent `matching(o: O)` elements. */ @deprecated("Moved to the akka/akka-stream-contrib project", since = "2.4.5") - def timedIntervalBetween[I, O, Mat](flow: Flow[I, O, Mat], matching: O ⇒ Boolean, onInterval: FiniteDuration ⇒ Unit): Flow[I, O, Mat] = { + def timedIntervalBetween[I, O, Mat](flow: Flow[I, O, Mat], matching: O => Boolean, onInterval: FiniteDuration => Unit): Flow[I, O, Mat] = { val timedInterval = Flow[O].via(new TimedInterval[O](matching, onInterval)).named("timedInterval") flow.via(timedInterval) } @@ -129,7 +129,7 @@ object Timed extends TimedOps with TimedIntervalBetweenOps { } } - final class StopTimed[T](timedContext: TimedFlowContext, _onComplete: FiniteDuration ⇒ Unit) extends SimpleLinearGraphStage[T] { + final class StopTimed[T](timedContext: TimedFlowContext, _onComplete: FiniteDuration => Unit) extends SimpleLinearGraphStage[T] { override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { @@ -156,7 +156,7 @@ object Timed extends TimedOps with TimedIntervalBetweenOps { } } - final class TimedInterval[T](matching: T ⇒ Boolean, onInterval: FiniteDuration ⇒ Unit) extends SimpleLinearGraphStage[T] { + final class TimedInterval[T](matching: T => Boolean, onInterval: FiniteDuration => Unit) extends SimpleLinearGraphStage[T] { override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { diff --git a/akka-stream/src/main/scala/akka/stream/impl/ActorMaterializerImpl.scala b/akka-stream/src/main/scala/akka/stream/impl/ActorMaterializerImpl.scala index f82dbcc698..ed559ad28a 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ActorMaterializerImpl.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ActorMaterializerImpl.scala @@ -45,12 +45,12 @@ import scala.concurrent.{ Await, ExecutionContextExecutor } */ @InternalApi private[akka] override def actorOf(context: MaterializationContext, props: Props): ActorRef = { val effectiveProps = props.dispatcher match { - case Dispatchers.DefaultDispatcherId ⇒ + case Dispatchers.DefaultDispatcherId => props.withDispatcher(context.effectiveAttributes.mandatoryAttribute[ActorAttributes.Dispatcher].dispatcher) - case ActorAttributes.IODispatcher.dispatcher ⇒ + case ActorAttributes.IODispatcher.dispatcher => // this one is actually not a dispatcher but a relative config key pointing containing the actual dispatcher name props.withDispatcher(settings.blockingIoDispatcher) - case _ ⇒ props + case _ => props } actorOf(effectiveProps, context.islandName) @@ -61,9 +61,9 @@ import scala.concurrent.{ Await, ExecutionContextExecutor } */ @InternalApi private[akka] def actorOf(props: Props, name: String): ActorRef = { supervisor match { - case ref: LocalActorRef ⇒ + case ref: LocalActorRef => ref.underlying.attachChild(props, name, systemService = false) - case ref: RepointableActorRef ⇒ + case ref: RepointableActorRef => if (ref.isStarted) ref.underlying.asInstanceOf[ActorCell].attachChild(props, name, systemService = false) else { @@ -71,7 +71,7 @@ import scala.concurrent.{ Await, ExecutionContextExecutor } val f = (supervisor ? StreamSupervisor.Materialize(props, name)).mapTo[ActorRef] Await.result(f, timeout.duration) } - case unknown ⇒ + case unknown => throw new IllegalStateException(s"Stream supervisor must be a local actor, was [${unknown.getClass.getName}]") } } @@ -94,7 +94,7 @@ import scala.concurrent.{ Await, ExecutionContextExecutor } * * The default phases are left in-tact since we still respect `.async` and other tags that were marked within a sub-fused graph. */ -private[akka] class SubFusingActorMaterializerImpl(val delegate: ExtendedActorMaterializer, registerShell: GraphInterpreterShell ⇒ ActorRef) extends Materializer { +private[akka] class SubFusingActorMaterializerImpl(val delegate: ExtendedActorMaterializer, registerShell: GraphInterpreterShell => ActorRef) extends Materializer { val subFusingPhase = new Phase[Any] { override def apply(settings: ActorMaterializerSettings, attributes: Attributes, materializer: PhasedFusingActorMaterializer, islandName: String): PhaseIsland[Any] = { @@ -106,10 +106,10 @@ private[akka] class SubFusingActorMaterializerImpl(val delegate: ExtendedActorMa override def materialize[Mat](runnable: Graph[ClosedShape, Mat]): Mat = delegate match { - case am: PhasedFusingActorMaterializer ⇒ + case am: PhasedFusingActorMaterializer => materialize(runnable, am.defaultAttributes) - case other ⇒ + case other => throw new IllegalStateException(s"SubFusing only supported by [PhasedFusingActorMaterializer], " + s"yet was used with [${other.getClass.getName}]!") } @@ -179,11 +179,11 @@ private[akka] class SubFusingActorMaterializerImpl(val delegate: ExtendedActorMa override def supervisorStrategy: SupervisorStrategy = SupervisorStrategy.stoppingStrategy def receive = { - case Materialize(props, name) ⇒ + case Materialize(props, name) => val impl = context.actorOf(props, name) sender() ! impl - case GetChildren ⇒ sender() ! Children(context.children.toSet) - case StopChildren ⇒ + case GetChildren => sender() ! Children(context.children.toSet) + case StopChildren => context.children.foreach(context.stop) sender() ! StoppedChildren } diff --git a/akka-stream/src/main/scala/akka/stream/impl/ActorProcessor.scala b/akka-stream/src/main/scala/akka/stream/impl/ActorProcessor.scala index 73b716bc36..6993d5c9a1 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ActorProcessor.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ActorProcessor.scala @@ -135,20 +135,20 @@ import akka.event.Logging } protected def waitingForUpstream: Actor.Receive = { - case OnComplete ⇒ onComplete() - case OnSubscribe(subscription) ⇒ onSubscribe(subscription) - case OnError(cause) ⇒ onError(cause) + case OnComplete => onComplete() + case OnSubscribe(subscription) => onSubscribe(subscription) + case OnError(cause) => onError(cause) } protected def upstreamRunning: Actor.Receive = { - case OnNext(element) ⇒ enqueueInputElement(element) - case OnComplete ⇒ onComplete() - case OnError(cause) ⇒ onError(cause) - case OnSubscribe(subscription) ⇒ subscription.cancel() // spec rule 2.5 + case OnNext(element) => enqueueInputElement(element) + case OnComplete => onComplete() + case OnError(cause) => onError(cause) + case OnSubscribe(subscription) => subscription.cancel() // spec rule 2.5 } protected def completed: Actor.Receive = { - case OnSubscribe(_) ⇒ throw new IllegalStateException("onSubscribe called after onError or onComplete") + case OnSubscribe(_) => throw new IllegalStateException("onSubscribe called after onError or onComplete") } protected def inputOnError(e: Throwable): Unit = { @@ -210,7 +210,7 @@ import akka.event.Logging protected def createSubscription(): Subscription = new ActorSubscription(actor, subscriber) private def subscribePending(subscribers: Seq[Subscriber[Any]]): Unit = - subscribers foreach { sub ⇒ + subscribers foreach { sub => if (subscriber eq null) { subscriber = sub tryOnSubscribe(subscriber, createSubscription()) @@ -219,17 +219,17 @@ import akka.event.Logging } protected def waitingExposedPublisher: Actor.Receive = { - case ExposedPublisher(publisher) ⇒ + case ExposedPublisher(publisher) => exposedPublisher = publisher subreceive.become(downstreamRunning) - case other ⇒ + case other => throw new IllegalStateException(s"The first message must be ExposedPublisher but was [$other]") } protected def downstreamRunning: Actor.Receive = { - case SubscribePending ⇒ + case SubscribePending => subscribePending(exposedPublisher.takePendingSubscribers()) - case RequestMore(_, elements) ⇒ + case RequestMore(_, elements) => if (elements < 1) { error(ReactiveStreamsCompliance.numberOfElementsInRequestMustBePositiveException) } else { @@ -238,7 +238,7 @@ import akka.event.Logging downstreamDemand = Long.MaxValue // Long overflow, Reactive Streams Spec 3:17: effectively unbounded pump.pump() } - case Cancel(_) ⇒ + case Cancel(_) => downstreamCompleted = true exposedPublisher.shutdown(Some(new ActorPublisher.NormalShutdownException)) pump.pump() diff --git a/akka-stream/src/main/scala/akka/stream/impl/ActorPublisher.scala b/akka-stream/src/main/scala/akka/stream/impl/ActorPublisher.scala index a3be9fffef..bcdaf4abc6 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ActorPublisher.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ActorPublisher.scala @@ -75,8 +75,8 @@ import org.reactivestreams.Subscription def shutdown(reason: Option[Throwable]): Unit = { shutdownReason = reason pendingSubscribers.getAndSet(null) match { - case null ⇒ // already called earlier - case pending ⇒ pending foreach reportSubscribeFailure + case null => // already called earlier + case pending => pending foreach reportSubscribeFailure } } @@ -84,15 +84,15 @@ import org.reactivestreams.Subscription private def reportSubscribeFailure(subscriber: Subscriber[_ >: T]): Unit = try shutdownReason match { - case Some(_: SpecViolation) ⇒ // ok, not allowed to call onError - case Some(e) ⇒ + case Some(_: SpecViolation) => // ok, not allowed to call onError + case Some(e) => tryOnSubscribe(subscriber, CancelledSubscription) tryOnError(subscriber, e) - case None ⇒ + case None => tryOnSubscribe(subscriber, CancelledSubscription) tryOnComplete(subscriber) } catch { - case _: SpecViolation ⇒ // nothing to do + case _: SpecViolation => // nothing to do } } @@ -114,7 +114,7 @@ import org.reactivestreams.Subscription /** * INTERNAL API */ -@InternalApi private[akka] trait SoftShutdown { this: Actor ⇒ +@InternalApi private[akka] trait SoftShutdown { this: Actor => def softShutdown(): Unit = { val children = context.children if (children.isEmpty) { @@ -122,8 +122,8 @@ import org.reactivestreams.Subscription } else { context.children foreach context.watch context.become { - case Terminated(_) ⇒ if (context.children.isEmpty) context.stop(self) - case _ ⇒ // ignore all the rest, we’re practically dead + case Terminated(_) => if (context.children.isEmpty) context.stop(self) + case _ => // ignore all the rest, we’re practically dead } } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/ActorRefBackpressureSinkStage.scala b/akka-stream/src/main/scala/akka/stream/impl/ActorRefBackpressureSinkStage.scala index 6220c3f6e4..347996986b 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ActorRefBackpressureSinkStage.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ActorRefBackpressureSinkStage.scala @@ -18,11 +18,11 @@ import akka.stream.stage._ */ @InternalApi private[akka] class ActorRefBackpressureSinkStage[In]( ref: ActorRef, - messageAdapter: ActorRef ⇒ In ⇒ Any, - onInitMessage: ActorRef ⇒ Any, + messageAdapter: ActorRef => In => Any, + onInitMessage: ActorRef => Any, ackMessage: Any, onCompleteMessage: Any, - onFailureMessage: (Throwable) ⇒ Any) + onFailureMessage: (Throwable) => Any) extends GraphStage[SinkShape[In]] { val in: Inlet[In] = Inlet[In]("ActorRefBackpressureSink.in") override def initialAttributes = DefaultAttributes.actorRefWithAck @@ -42,7 +42,7 @@ import akka.stream.stage._ private def receive(evt: (ActorRef, Any)): Unit = { evt._2 match { - case `ackMessage` ⇒ { + case `ackMessage` => { if (buffer.isEmpty) acknowledgementReceived = true else { // onPush might have filled the buffer up and @@ -51,8 +51,8 @@ import akka.stream.stage._ dequeueAndSend() } } - case Terminated(`ref`) ⇒ completeStage() - case _ ⇒ //ignore all other messages + case Terminated(`ref`) => completeStage() + case _ => //ignore all other messages } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/ActorRefSinkActor.scala b/akka-stream/src/main/scala/akka/stream/impl/ActorRefSinkActor.scala index 1248f80f73..fe451e6d4f 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ActorRefSinkActor.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ActorRefSinkActor.scala @@ -16,14 +16,14 @@ import akka.annotation.InternalApi * INTERNAL API */ @InternalApi private[akka] object ActorRefSinkActor { - def props(ref: ActorRef, highWatermark: Int, onCompleteMessage: Any, onFailureMessage: Throwable ⇒ Any): Props = + def props(ref: ActorRef, highWatermark: Int, onCompleteMessage: Any, onFailureMessage: Throwable => Any): Props = Props(new ActorRefSinkActor(ref, highWatermark, onCompleteMessage, onFailureMessage)) } /** * INTERNAL API */ -@InternalApi private[akka] class ActorRefSinkActor(ref: ActorRef, highWatermark: Int, onCompleteMessage: Any, onFailureMessage: Throwable ⇒ Any) +@InternalApi private[akka] class ActorRefSinkActor(ref: ActorRef, highWatermark: Int, onCompleteMessage: Any, onFailureMessage: Throwable => Any) extends ActorSubscriber { import ActorSubscriberMessage._ @@ -32,15 +32,15 @@ import akka.annotation.InternalApi context.watch(ref) def receive = { - case OnNext(elem) ⇒ + case OnNext(elem) => ref.tell(elem, ActorRef.noSender) - case OnError(cause) ⇒ + case OnError(cause) => ref.tell(onFailureMessage(cause), ActorRef.noSender) context.stop(self) - case OnComplete ⇒ + case OnComplete => ref.tell(onCompleteMessage, ActorRef.noSender) context.stop(self) - case Terminated(`ref`) ⇒ + case Terminated(`ref`) => context.stop(self) // will cancel upstream } diff --git a/akka-stream/src/main/scala/akka/stream/impl/ActorRefSourceActor.scala b/akka-stream/src/main/scala/akka/stream/impl/ActorRefSourceActor.scala index e999558109..d3452f8fa7 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ActorRefSourceActor.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ActorRefSourceActor.scala @@ -37,7 +37,7 @@ import akka.stream.ActorMaterializerSettings protected val buffer = if (bufferSize == 0) null else Buffer[Any](bufferSize, maxFixedBufferSize) def receive = ({ - case Cancel ⇒ + case Cancel => context.stop(self) }: Receive) .orElse(requestElem) @@ -45,18 +45,18 @@ import akka.stream.ActorMaterializerSettings .orElse(receiveComplete) .orElse(receiveElem) - def receiveComplete: Receive = completionMatcher.andThen { _ ⇒ + def receiveComplete: Receive = completionMatcher.andThen { _ => if (bufferSize == 0 || buffer.isEmpty) onCompleteThenStop() // will complete the stream successfully else context.become(drainBufferThenComplete) } - def receiveFailure: Receive = failureMatcher.andThen { cause ⇒ + def receiveFailure: Receive = failureMatcher.andThen { cause => if (isActive) onErrorThenStop(cause) } def requestElem: Receive = { - case _: Request ⇒ + case _: Request => // totalDemand is tracked by super if (bufferSize != 0) while (totalDemand > 0L && !buffer.isEmpty) @@ -64,7 +64,7 @@ import akka.stream.ActorMaterializerSettings } def receiveElem: Receive = { - case elem if isActive ⇒ + case elem if isActive => if (totalDemand > 0L) onNext(elem) else if (bufferSize == 0) @@ -72,47 +72,47 @@ import akka.stream.ActorMaterializerSettings else if (!buffer.isFull) buffer.enqueue(elem) else overflowStrategy match { - case s: DropHead ⇒ + case s: DropHead => log.log(s.logLevel, "Dropping the head element because buffer is full and overflowStrategy is: [DropHead]") buffer.dropHead() buffer.enqueue(elem) - case s: DropTail ⇒ + case s: DropTail => log.log(s.logLevel, "Dropping the tail element because buffer is full and overflowStrategy is: [DropTail]") buffer.dropTail() buffer.enqueue(elem) - case s: DropBuffer ⇒ + case s: DropBuffer => log.log(s.logLevel, "Dropping all the buffered elements because buffer is full and overflowStrategy is: [DropBuffer]") buffer.clear() buffer.enqueue(elem) - case s: DropNew ⇒ + case s: DropNew => // do not enqueue new element if the buffer is full log.log(s.logLevel, "Dropping the new element because buffer is full and overflowStrategy is: [DropNew]") - case s: Fail ⇒ + case s: Fail => log.log(s.logLevel, "Failing because buffer is full and overflowStrategy is: [Fail]") onErrorThenStop(BufferOverflowException(s"Buffer overflow (max capacity was: $bufferSize)!")) - case s: Backpressure ⇒ + case s: Backpressure => // there is a precondition check in Source.actorRefSource factory method log.log(s.logLevel, "Backpressuring because buffer is full and overflowStrategy is: [Backpressure]") } } def drainBufferThenComplete: Receive = { - case Cancel ⇒ + case Cancel => context.stop(self) - case Status.Failure(cause) if isActive ⇒ + case Status.Failure(cause) if isActive => // errors must be signaled as soon as possible, // even if previously valid completion was requested via Status.Success onErrorThenStop(cause) - case _: Request ⇒ + case _: Request => // totalDemand is tracked by super while (totalDemand > 0L && !buffer.isEmpty) onNext(buffer.dequeue()) if (buffer.isEmpty) onCompleteThenStop() // will complete the stream successfully - case elem if isActive ⇒ + case elem if isActive => log.debug("Dropping element because Status.Success received already, " + "only draining already buffered elements: [{}] (pending: [{}])", elem, buffer.used) } diff --git a/akka-stream/src/main/scala/akka/stream/impl/Buffers.scala b/akka-stream/src/main/scala/akka/stream/impl/Buffers.scala index 25b32cafa7..c5c0f50dfd 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/Buffers.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/Buffers.scala @@ -4,7 +4,7 @@ package akka.stream.impl -import java.{ util ⇒ ju } +import java.{ util => ju } import akka.annotation.InternalApi import akka.stream._ @@ -37,8 +37,8 @@ private[akka] object Buffer { def apply[T](size: Int, materializer: Materializer): Buffer[T] = materializer match { - case m: ActorMaterializer ⇒ apply(size, m.settings.maxFixedBufferSize) - case _ ⇒ apply(size, 1000000000) + case m: ActorMaterializer => apply(size, m.settings.maxFixedBufferSize) + case _ => apply(size, 1000000000) } def apply[T](size: Int, max: Int): Buffer[T] = diff --git a/akka-stream/src/main/scala/akka/stream/impl/CompletedPublishers.scala b/akka-stream/src/main/scala/akka/stream/impl/CompletedPublishers.scala index 103f2922ce..c747da9f1f 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/CompletedPublishers.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/CompletedPublishers.scala @@ -18,7 +18,7 @@ import org.reactivestreams.{ Publisher, Subscriber, Subscription } tryOnSubscribe(subscriber, CancelledSubscription) tryOnComplete(subscriber) } catch { - case _: SpecViolation ⇒ // nothing we can do + case _: SpecViolation => // nothing we can do } def apply[T]: Publisher[T] = this.asInstanceOf[Publisher[T]] override def toString: String = "already-completed-publisher" @@ -37,7 +37,7 @@ import org.reactivestreams.{ Publisher, Subscriber, Subscription } tryOnSubscribe(subscriber, CancelledSubscription) tryOnError(subscriber, t) } catch { - case _: SpecViolation ⇒ // nothing we can do + case _: SpecViolation => // nothing we can do } def apply[T]: Publisher[T] = this.asInstanceOf[Publisher[T]] override def toString: String = name @@ -70,7 +70,7 @@ import org.reactivestreams.{ Publisher, Subscriber, Subscription } import ReactiveStreamsCompliance._ override def subscribe(subscriber: Subscriber[_ >: Nothing]): Unit = try rejectAdditionalSubscriber(subscriber, "Publisher") catch { - case _: SpecViolation ⇒ // nothing we can do + case _: SpecViolation => // nothing we can do } def apply[T]: Publisher[T] = this.asInstanceOf[Publisher[T]] override def toString: String = "already-subscribed-publisher" diff --git a/akka-stream/src/main/scala/akka/stream/impl/ConstantFun.scala b/akka-stream/src/main/scala/akka/stream/impl/ConstantFun.scala index 63f2bbf452..3ab0f57e9d 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ConstantFun.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ConstantFun.scala @@ -5,8 +5,8 @@ package akka.stream.impl import akka.annotation.InternalApi -import akka.japi.function.{ Function ⇒ JFun, Function2 ⇒ JFun2 } -import akka.japi.{ Pair ⇒ JPair } +import akka.japi.function.{ Function => JFun, Function2 => JFun2 } +import akka.japi.{ Pair => JPair } /** * INTERNAL API @@ -25,22 +25,22 @@ import akka.japi.{ Pair ⇒ JPair } def javaIdentityFunction[T]: JFun[T, T] = JavaIdentityFunction.asInstanceOf[JFun[T, T]] - def scalaIdentityFunction[T]: T ⇒ T = conforms.asInstanceOf[Function[T, T]] + def scalaIdentityFunction[T]: T => T = conforms.asInstanceOf[Function[T, T]] - def scalaAnyToNone[A, B]: A ⇒ Option[B] = none - def scalaAnyTwoToNone[A, B, C]: (A, B) ⇒ Option[C] = two2none - def javaAnyToNone[A, B]: A ⇒ Option[B] = none + def scalaAnyToNone[A, B]: A => Option[B] = none + def scalaAnyTwoToNone[A, B, C]: (A, B) => Option[C] = two2none + def javaAnyToNone[A, B]: A => Option[B] = none - val conforms = (a: Any) ⇒ a + val conforms = (a: Any) => a - val zeroLong = (_: Any) ⇒ 0L + val zeroLong = (_: Any) => 0L - val oneLong = (_: Any) ⇒ 1L + val oneLong = (_: Any) => 1L - val oneInt = (_: Any) ⇒ 1 + val oneInt = (_: Any) => 1 - val none = (_: Any) ⇒ None + val none = (_: Any) => None - val two2none = (_: Any, _: Any) ⇒ None + val two2none = (_: Any, _: Any) => None } diff --git a/akka-stream/src/main/scala/akka/stream/impl/ExposedPublisherReceive.scala b/akka-stream/src/main/scala/akka/stream/impl/ExposedPublisherReceive.scala index 9ce99beee5..85dbf9bf90 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ExposedPublisherReceive.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ExposedPublisherReceive.scala @@ -10,21 +10,21 @@ import akka.annotation.InternalApi /** * INTERNAL API */ -@InternalApi private[akka] abstract class ExposedPublisherReceive(activeReceive: Actor.Receive, unhandled: Any ⇒ Unit) extends Actor.Receive { +@InternalApi private[akka] abstract class ExposedPublisherReceive(activeReceive: Actor.Receive, unhandled: Any => Unit) extends Actor.Receive { private var stash = List.empty[Any] def isDefinedAt(o: Any): Boolean = true def apply(o: Any): Unit = o match { - case ep: ExposedPublisher ⇒ + case ep: ExposedPublisher => receiveExposedPublisher(ep) if (stash.nonEmpty) { // we don't use sender() so this is alright - stash.reverse.foreach { msg ⇒ + stash.reverse.foreach { msg => activeReceive.applyOrElse(msg, unhandled) } } - case other ⇒ + case other => stash ::= other } diff --git a/akka-stream/src/main/scala/akka/stream/impl/FanIn.scala b/akka-stream/src/main/scala/akka/stream/impl/FanIn.scala index 2409324037..17c9759bc4 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/FanIn.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/FanIn.scala @@ -46,7 +46,7 @@ import org.reactivestreams.{ Subscriber, Subscription } abstract class InputBunch(inputCount: Int, bufferSize: Int, pump: Pump) { private var allCancelled = false - private val inputs: Array[BatchingInputBuffer] = Array.tabulate(inputCount) { i ⇒ + private val inputs: Array[BatchingInputBuffer] = Array.tabulate(inputCount) { i => new BatchingInputBuffer(bufferSize, pump) { override protected def onError(e: Throwable): Unit = InputBunch.this.onError(i, e) } @@ -227,14 +227,14 @@ import org.reactivestreams.{ Subscriber, Subscription } // FIXME: Eliminate re-wraps def subreceive: SubReceive = new SubReceive({ - case OnSubscribe(id, subscription) ⇒ + case OnSubscribe(id, subscription) => inputs(id).subreceive(ActorSubscriber.OnSubscribe(subscription)) - case OnNext(id, elem) ⇒ + case OnNext(id, elem) => if (marked(id) && !pending(id)) markedPending += 1 pending(id, on = true) receivedInput = true inputs(id).subreceive(ActorSubscriberMessage.OnNext(elem)) - case OnComplete(id) ⇒ + case OnComplete(id) => if (!pending(id)) { if (marked(id) && !depleted(id)) markedDepleted += 1 depleted(id, on = true) @@ -243,7 +243,7 @@ import org.reactivestreams.{ Subscriber, Subscription } registerCompleted(id) inputs(id).subreceive(ActorSubscriberMessage.OnComplete) if (!receivedInput && isAllCompleted) onCompleteWhenNoInput() - case OnError(id, e) ⇒ + case OnError(id, e) => onError(id, e) }) diff --git a/akka-stream/src/main/scala/akka/stream/impl/FanOut.scala b/akka-stream/src/main/scala/akka/stream/impl/FanOut.scala index df8dec6243..c48bb3e029 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/FanOut.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/FanOut.scala @@ -216,13 +216,13 @@ import org.reactivestreams.Subscription // FIXME: Eliminate re-wraps def subreceive: SubReceive = new SubReceive({ - case ExposedPublishers(publishers) ⇒ + case ExposedPublishers(publishers) => publishers.zip(outputs) foreach { - case (pub, output) ⇒ + case (pub, output) => output.subreceive(ExposedPublisher(pub)) } - case SubstreamRequestMore(id, demand) ⇒ + case SubstreamRequestMore(id, demand) => if (demand < 1) // According to Reactive Streams Spec 3.9, with non-positive demand must yield onError error(id, ReactiveStreamsCompliance.numberOfElementsInRequestMustBePositiveException) else { @@ -230,7 +230,7 @@ import org.reactivestreams.Subscription pending(id) = true outputs(id).subreceive(RequestMore(null, demand)) } - case SubstreamCancel(id) ⇒ + case SubstreamCancel(id) => if (unmarkCancelled) { unmarkOutput(id) } @@ -238,7 +238,7 @@ import org.reactivestreams.Subscription cancelled(id) = true onCancel(id) outputs(id).subreceive(Cancel(null)) - case SubstreamSubscribePending(id) ⇒ + case SubstreamSubscribePending(id) => outputs(id).subreceive(SubscribePending) }) @@ -300,17 +300,17 @@ import org.reactivestreams.Subscription @InternalApi private[akka] class Unzip(_settings: ActorMaterializerSettings) extends FanOut(_settings, outputCount = 2) { outputBunch.markAllOutputs() - initialPhase(1, TransferPhase(primaryInputs.NeedsInput && outputBunch.AllOfMarkedOutputs) { () ⇒ + initialPhase(1, TransferPhase(primaryInputs.NeedsInput && outputBunch.AllOfMarkedOutputs) { () => primaryInputs.dequeueInputElement() match { - case (a, b) ⇒ + case (a, b) => outputBunch.enqueue(0, a) outputBunch.enqueue(1, b) - case t: akka.japi.Pair[_, _] ⇒ + case t: akka.japi.Pair[_, _] => outputBunch.enqueue(0, t.first) outputBunch.enqueue(1, t.second) - case t ⇒ + case t => throw new IllegalArgumentException( s"Unable to unzip elements of type ${t.getClass.getName}, " + s"can only handle Tuple2 and akka.japi.Pair!") diff --git a/akka-stream/src/main/scala/akka/stream/impl/FanoutProcessor.scala b/akka-stream/src/main/scala/akka/stream/impl/FanoutProcessor.scala index 6d65e2e715..9070233ee0 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/FanoutProcessor.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/FanoutProcessor.scala @@ -77,20 +77,20 @@ import org.reactivestreams.Subscriber } protected def waitingExposedPublisher: Actor.Receive = { - case ExposedPublisher(publisher) ⇒ + case ExposedPublisher(publisher) => exposedPublisher = publisher subreceive.become(downstreamRunning) - case other ⇒ + case other => throw new IllegalStateException(s"The first message must be ExposedPublisher but was [$other]") } protected def downstreamRunning: Actor.Receive = { - case SubscribePending ⇒ + case SubscribePending => subscribePending() - case RequestMore(subscription, elements) ⇒ + case RequestMore(subscription, elements) => moreRequested(subscription.asInstanceOf[ActorSubscriptionWithCursor[Any]], elements) pump.pump() - case Cancel(subscription) ⇒ + case Cancel(subscription) => unregisterSubscription(subscription.asInstanceOf[ActorSubscriptionWithCursor[Any]]) pump.pump() } @@ -117,7 +117,7 @@ import org.reactivestreams.Subscriber } } - val running: TransferPhase = TransferPhase(primaryInputs.NeedsInput && primaryOutputs.NeedsDemand) { () ⇒ + val running: TransferPhase = TransferPhase(primaryInputs.NeedsInput && primaryOutputs.NeedsDemand) { () => primaryOutputs.enqueueOutputElement(primaryInputs.dequeueInputElement()) } diff --git a/akka-stream/src/main/scala/akka/stream/impl/JavaStreamSource.scala b/akka-stream/src/main/scala/akka/stream/impl/JavaStreamSource.scala index 3ee702f4ab..eb507ab694 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/JavaStreamSource.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/JavaStreamSource.scala @@ -9,7 +9,7 @@ import akka.stream.stage.{ GraphStage, GraphStageLogic, OutHandler } import akka.annotation.InternalApi /** INTERNAL API */ -@InternalApi private[stream] final class JavaStreamSource[T, S <: java.util.stream.BaseStream[T, S]](open: () ⇒ java.util.stream.BaseStream[T, S]) +@InternalApi private[stream] final class JavaStreamSource[T, S <: java.util.stream.BaseStream[T, S]](open: () => java.util.stream.BaseStream[T, S]) extends GraphStage[SourceShape[T]] { val out: Outlet[T] = Outlet("JavaStreamSource") diff --git a/akka-stream/src/main/scala/akka/stream/impl/JsonObjectParser.scala b/akka-stream/src/main/scala/akka/stream/impl/JsonObjectParser.scala index ad422eb510..eaeb30b241 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/JsonObjectParser.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/JsonObjectParser.scala @@ -29,11 +29,11 @@ import scala.annotation.switch final val Space = 32 // ' ' def isWhitespace(b: Byte): Boolean = (b: @switch) match { - case Space ⇒ true - case LineBreak ⇒ true - case LineBreak2 ⇒ true - case Tab ⇒ true - case _ ⇒ false + case Space => true + case LineBreak => true + case LineBreak2 => true + case Tab => true + case _ => false } } @@ -79,8 +79,8 @@ import scala.annotation.switch if (!foundObject) None else (pos: @switch) match { - case -1 | 0 ⇒ None - case _ ⇒ + case -1 | 0 => None + case _ => val (emit, buf) = buffer.splitAt(pos) buffer = buf.compact pos = 0 diff --git a/akka-stream/src/main/scala/akka/stream/impl/LazySource.scala b/akka-stream/src/main/scala/akka/stream/impl/LazySource.scala index 192a46ee42..e05cd4e35d 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/LazySource.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/LazySource.scala @@ -17,13 +17,13 @@ import scala.util.control.NonFatal * INTERNAL API */ @InternalApi private[akka] object LazySource { - def apply[T, M](sourceFactory: () ⇒ Source[T, M]) = new LazySource[T, M](sourceFactory) + def apply[T, M](sourceFactory: () => Source[T, M]) = new LazySource[T, M](sourceFactory) } /** * INTERNAL API */ -@InternalApi private[akka] final class LazySource[T, M](sourceFactory: () ⇒ Source[T, M]) extends GraphStageWithMaterializedValue[SourceShape[T], Future[M]] { +@InternalApi private[akka] final class LazySource[T, M](sourceFactory: () => Source[T, M]) extends GraphStageWithMaterializedValue[SourceShape[T], Future[M]] { val out = Outlet[T]("LazySource.out") override val shape = SourceShape(out) @@ -64,7 +64,7 @@ import scala.util.control.NonFatal val matVal = subFusingMaterializer.materialize(source.toMat(subSink.sink)(Keep.left), inheritedAttributes) matPromise.trySuccess(matVal) } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => subSink.cancel() failStage(ex) matPromise.tryFailure(ex) diff --git a/akka-stream/src/main/scala/akka/stream/impl/MaybeSource.scala b/akka-stream/src/main/scala/akka/stream/impl/MaybeSource.scala index e578205f01..523d3eb3c1 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/MaybeSource.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/MaybeSource.scala @@ -24,7 +24,7 @@ import scala.util.Try override protected def initialAttributes = DefaultAttributes.maybeSource override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, Promise[Option[AnyRef]]) = { - import scala.util.{ Success ⇒ ScalaSuccess, Failure ⇒ ScalaFailure } + import scala.util.{ Success => ScalaSuccess, Failure => ScalaFailure } val promise = Promise[Option[AnyRef]]() val logic = new GraphStageLogic(shape) with OutHandler { @@ -32,10 +32,10 @@ import scala.util.Try override def preStart(): Unit = { promise.future.value match { - case Some(value) ⇒ + case Some(value) => // already completed, shortcut handleCompletion(value) - case None ⇒ + case None => // callback on future completion promise.future.onComplete( getAsyncCallback(handleCompletion).invoke @@ -44,24 +44,24 @@ import scala.util.Try } override def onPull(): Unit = arrivedEarly match { - case OptionVal.Some(value) ⇒ + case OptionVal.Some(value) => push(out, value) completeStage() - case OptionVal.None ⇒ + case OptionVal.None => } private def handleCompletion(elem: Try[Option[AnyRef]]): Unit = { elem match { - case ScalaSuccess(None) ⇒ + case ScalaSuccess(None) => completeStage() - case ScalaSuccess(Some(value)) ⇒ + case ScalaSuccess(Some(value)) => if (isAvailable(out)) { push(out, value) completeStage() } else { arrivedEarly = OptionVal.Some(value) } - case ScalaFailure(ex) ⇒ + case ScalaFailure(ex) => failStage(ex) } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/PhasedFusingActorMaterializer.scala b/akka-stream/src/main/scala/akka/stream/impl/PhasedFusingActorMaterializer.scala index 5989fe1c4f..6a6551ce2b 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/PhasedFusingActorMaterializer.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/PhasedFusingActorMaterializer.scala @@ -41,30 +41,30 @@ import akka.util.OptionVal } val DefaultPhases: Map[IslandTag, Phase[Any]] = Map[IslandTag, Phase[Any]]( - SinkModuleIslandTag → new Phase[Any] { + SinkModuleIslandTag -> new Phase[Any] { override def apply(settings: ActorMaterializerSettings, effectiveAttributes: Attributes, materializer: PhasedFusingActorMaterializer, islandName: String): PhaseIsland[Any] = new SinkModulePhase(materializer, islandName).asInstanceOf[PhaseIsland[Any]] }, - SourceModuleIslandTag → new Phase[Any] { + SourceModuleIslandTag -> new Phase[Any] { override def apply(settings: ActorMaterializerSettings, effectiveAttributes: Attributes, materializer: PhasedFusingActorMaterializer, islandName: String): PhaseIsland[Any] = new SourceModulePhase(materializer, islandName).asInstanceOf[PhaseIsland[Any]] }, - ProcessorModuleIslandTag → new Phase[Any] { + ProcessorModuleIslandTag -> new Phase[Any] { override def apply(settings: ActorMaterializerSettings, effectiveAttributes: Attributes, materializer: PhasedFusingActorMaterializer, islandName: String): PhaseIsland[Any] = new ProcessorModulePhase().asInstanceOf[PhaseIsland[Any]] }, - TlsModuleIslandTag → new Phase[Any] { + TlsModuleIslandTag -> new Phase[Any] { def apply(settings: ActorMaterializerSettings, effectiveAttributes: Attributes, materializer: PhasedFusingActorMaterializer, islandName: String): PhaseIsland[Any] = new TlsModulePhase(materializer, islandName).asInstanceOf[PhaseIsland[Any]] }, - GraphStageTag → DefaultPhase) + GraphStageTag -> DefaultPhase) @InternalApi private[akka] def apply()(implicit context: ActorRefFactory): ActorMaterializer = { val haveShutDown = new AtomicBoolean(false) @@ -86,10 +86,10 @@ import akka.util.OptionVal private def actorSystemOf(context: ActorRefFactory): ActorSystem = { val system = context match { - case s: ExtendedActorSystem ⇒ s - case c: ActorContext ⇒ c.system - case null ⇒ throw new IllegalArgumentException("ActorRefFactory context must be defined") - case _ ⇒ + case s: ExtendedActorSystem => s + case c: ActorContext => c.system + case null => throw new IllegalArgumentException("ActorRefFactory context must be defined") + case _ => throw new IllegalArgumentException(s"ActorRefFactory context must be an ActorSystem or ActorContext, got [${context.getClass.getName}]") } system @@ -393,8 +393,8 @@ private final case class SavedIslandData(islandGlobalOffset: Int, lastVisitedOff } override lazy val executionContext: ExecutionContextExecutor = dispatchers.lookup(settings.dispatcher match { - case Deploy.NoDispatcherGiven ⇒ Dispatchers.DefaultDispatcherId - case other ⇒ other + case Deploy.NoDispatcherGiven => Dispatchers.DefaultDispatcherId + case other => other }) override def schedulePeriodically(initialDelay: FiniteDuration, interval: FiniteDuration, task: Runnable): Cancellable = @@ -446,7 +446,7 @@ private final case class SavedIslandData(islandGlobalOffset: Int, lastVisitedOff while (current ne EmptyTraversal) { var nextStep: Traversal = EmptyTraversal current match { - case MaterializeAtomic(mod, outToSlot) ⇒ + case MaterializeAtomic(mod, outToSlot) => if (Debug) println(s"materializing module: $mod") val matAndStage = islandTracking.getCurrentPhase.materializeAtomic(mod, attributesStack.getLast) val logic = matAndStage._1 @@ -461,37 +461,37 @@ private final case class SavedIslandData(islandGlobalOffset: Int, lastVisitedOff if (Debug) println(s"PUSH: $matValue => $matValueStack") - case Concat(first, next) ⇒ + case Concat(first, next) => if (next ne EmptyTraversal) traversalStack.add(next) nextStep = first - case Pop ⇒ + case Pop => val popped = matValueStack.removeLast() if (Debug) println(s"POP: $popped => $matValueStack") - case PushNotUsed ⇒ + case PushNotUsed => matValueStack.addLast(NotUsed) if (Debug) println(s"PUSH: NotUsed => $matValueStack") - case transform: Transform ⇒ + case transform: Transform => val prev = matValueStack.removeLast() val result = transform(prev) matValueStack.addLast(result) if (Debug) println(s"TRFM: $matValueStack") - case compose: Compose ⇒ + case compose: Compose => val second = matValueStack.removeLast() val first = matValueStack.removeLast() val result = compose(first, second) matValueStack.addLast(result) if (Debug) println(s"COMP: $matValueStack") - case PushAttributes(attr) ⇒ + case PushAttributes(attr) => attributesStack.addLast(attributesStack.getLast and attr) if (Debug) println(s"ATTR PUSH: $attr") - case PopAttributes ⇒ + case PopAttributes => attributesStack.removeLast() if (Debug) println(s"ATTR POP") - case EnterIsland(tag) ⇒ + case EnterIsland(tag) => islandTracking.enterIsland(tag, attributesStack.getLast) - case ExitIsland ⇒ + case ExitIsland => islandTracking.exitIsland() - case _ ⇒ + case _ => } current = nextStep } @@ -605,7 +605,7 @@ private final case class SavedIslandData(islandGlobalOffset: Int, lastVisitedOff effectiveAttributes: Attributes, materializer: PhasedFusingActorMaterializer, islandName: String, - subflowFuser: OptionVal[GraphInterpreterShell ⇒ ActorRef]) extends PhaseIsland[GraphStageLogic] { + subflowFuser: OptionVal[GraphInterpreterShell => ActorRef]) extends PhaseIsland[GraphStageLogic] { // TODO: remove these private val logicArrayType = Array.empty[GraphStageLogic] private[this] val logics = new util.ArrayList[GraphStageLogic](16) @@ -635,8 +635,8 @@ private final case class SavedIslandData(islandGlobalOffset: Int, lastVisitedOff logics.add(logic) logic.stageId = logics.size() - 1 fullIslandName match { - case OptionVal.Some(_) ⇒ // already set - case OptionVal.None ⇒ fullIslandName = OptionVal.Some(islandName + "-" + logic.attributes.nameOrDefault()) + case OptionVal.Some(_) => // already set + case OptionVal.None => fullIslandName = OptionVal.Some(islandName + "-" + logic.attributes.nameOrDefault()) } matAndLogic } @@ -733,16 +733,16 @@ private final case class SavedIslandData(islandGlobalOffset: Int, lastVisitedOff shell.logics = logics.toArray(logicArrayType) subflowFuser match { - case OptionVal.Some(fuseIntoExistingInterpreter) ⇒ + case OptionVal.Some(fuseIntoExistingInterpreter) => fuseIntoExistingInterpreter(shell) - case _ ⇒ + case _ => val props = ActorGraphInterpreter.props(shell).withDispatcher(ActorAttributes.Dispatcher.resolve(effectiveAttributes, settings)) val actorName = fullIslandName match { - case OptionVal.Some(n) ⇒ n - case OptionVal.None ⇒ islandName + case OptionVal.Some(n) => n + case OptionVal.None => islandName } val ref = materializer.actorOf(props, actorName) @@ -756,10 +756,10 @@ private final case class SavedIslandData(islandGlobalOffset: Int, lastVisitedOff val missingHandlerIdx = logic.handlers.indexWhere(_.asInstanceOf[AnyRef] eq null) val isIn = missingHandlerIdx < logic.inCount val portLabel = logic.originalStage match { - case OptionVal.Some(stage) ⇒ + case OptionVal.Some(stage) => if (isIn) s"in port [${stage.shape.inlets(missingHandlerIdx)}]" else s"out port [${stage.shape.outlets(missingHandlerIdx - logic.inCount)}" - case OptionVal.None ⇒ + case OptionVal.None => if (isIn) s"in port id [$missingHandlerIdx]" else s"out port id [$missingHandlerIdx]" } @@ -832,8 +832,8 @@ private final case class SavedIslandData(islandGlobalOffset: Int, lastVisitedOff override def takePublisher(slot: Int, publisher: Publisher[Any]): Unit = { subscriberOrVirtualPublisher match { - case v: VirtualPublisher[_] ⇒ v.registerPublisher(publisher) - case s: Subscriber[Any] @unchecked ⇒ publisher.subscribe(s) + case v: VirtualPublisher[_] => v.registerPublisher(publisher) + case s: Subscriber[Any] @unchecked => publisher.subscribe(s) } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/QueueSource.scala b/akka-stream/src/main/scala/akka/stream/impl/QueueSource.scala index f2eadb9f63..ad04fca781 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/QueueSource.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/QueueSource.scala @@ -63,43 +63,43 @@ import scala.concurrent.{ Future, Promise } if (!buffer.isFull) { enqueueAndSuccess(offer) } else overflowStrategy match { - case s: DropHead ⇒ + case s: DropHead => log.log(s.logLevel, "Dropping the head element because buffer is full and overflowStrategy is: [DropHead]") buffer.dropHead() enqueueAndSuccess(offer) - case s: DropTail ⇒ + case s: DropTail => log.log(s.logLevel, "Dropping the tail element because buffer is full and overflowStrategy is: [DropTail]") buffer.dropTail() enqueueAndSuccess(offer) - case s: DropBuffer ⇒ + case s: DropBuffer => log.log(s.logLevel, "Dropping all the buffered elements because buffer is full and overflowStrategy is: [DropBuffer]") buffer.clear() enqueueAndSuccess(offer) - case s: DropNew ⇒ + case s: DropNew => log.log(s.logLevel, "Dropping the new element because buffer is full and overflowStrategy is: [DropNew]") offer.promise.success(QueueOfferResult.Dropped) - case s: Fail ⇒ + case s: Fail => log.log(s.logLevel, "Failing because buffer is full and overflowStrategy is: [Fail]") val bufferOverflowException = BufferOverflowException(s"Buffer overflow (max capacity was: $maxBuffer)!") offer.promise.success(QueueOfferResult.Failure(bufferOverflowException)) completion.failure(bufferOverflowException) failStage(bufferOverflowException) - case s: Backpressure ⇒ + case s: Backpressure => log.log(s.logLevel, "Backpressuring because buffer is full and overflowStrategy is: [Backpressure]") pendingOffer match { - case Some(_) ⇒ + case Some(_) => offer.promise.failure(new IllegalStateException("You have to wait for previous offer to be resolved to send another request")) - case None ⇒ + case None => pendingOffer = Some(offer) } } } private val callback = getAsyncCallback[Input[T]] { - case Offer(_, promise) if terminating ⇒ + case Offer(_, promise) if terminating => promise.success(QueueOfferResult.Dropped) - case offer @ Offer(elem, promise) ⇒ + case offer @ Offer(elem, promise) => if (maxBuffer != 0) { bufferElem(offer) if (isAvailable(out)) push(out, buffer.dequeue()) @@ -109,32 +109,32 @@ import scala.concurrent.{ Future, Promise } } else if (pendingOffer.isEmpty) pendingOffer = Some(offer) else overflowStrategy match { - case s @ (_: DropHead | _: DropBuffer) ⇒ + case s @ (_: DropHead | _: DropBuffer) => log.log(s.logLevel, "Dropping element because buffer is full and overflowStrategy is: [{}]", s) pendingOffer.get.promise.success(QueueOfferResult.Dropped) pendingOffer = Some(offer) - case s @ (_: DropTail | _: DropNew) ⇒ + case s @ (_: DropTail | _: DropNew) => log.log(s.logLevel, "Dropping element because buffer is full and overflowStrategy is: [{}]", s) promise.success(QueueOfferResult.Dropped) - case s: Fail ⇒ + case s: Fail => log.log(s.logLevel, "Failing because buffer is full and overflowStrategy is: [Fail]") val bufferOverflowException = BufferOverflowException(s"Buffer overflow (max capacity was: $maxBuffer)!") promise.success(QueueOfferResult.Failure(bufferOverflowException)) completion.failure(bufferOverflowException) failStage(bufferOverflowException) - case s: Backpressure ⇒ + case s: Backpressure => log.log(s.logLevel, "Failing because buffer is full and overflowStrategy is: [Backpressure]") promise.failure(new IllegalStateException("You have to wait for previous offer to be resolved to send another request")) } - case Completion ⇒ + case Completion => if (maxBuffer != 0 && buffer.nonEmpty || pendingOffer.nonEmpty) terminating = true else { completion.success(Done) completeStage() } - case Failure(ex) ⇒ + case Failure(ex) => completion.failure(ex) failStage(ex) } @@ -143,10 +143,10 @@ import scala.concurrent.{ Future, Promise } override def onDownstreamFinish(): Unit = { pendingOffer match { - case Some(Offer(_, promise)) ⇒ + case Some(Offer(_, promise)) => promise.success(QueueOfferResult.QueueClosed) pendingOffer = None - case None ⇒ // do nothing + case None => // do nothing } completion.success(Done) completeStage() @@ -155,7 +155,7 @@ import scala.concurrent.{ Future, Promise } override def onPull(): Unit = { if (maxBuffer == 0) { pendingOffer match { - case Some(Offer(elem, promise)) ⇒ + case Some(Offer(elem, promise)) => push(out, elem) promise.success(QueueOfferResult.Enqueued) pendingOffer = None @@ -163,15 +163,15 @@ import scala.concurrent.{ Future, Promise } completion.success(Done) completeStage() } - case None ⇒ + case None => } } else if (buffer.nonEmpty) { push(out, buffer.dequeue()) pendingOffer match { - case Some(offer) ⇒ + case Some(offer) => enqueueAndSuccess(offer) pendingOffer = None - case None ⇒ //do nothing + case None => //do nothing } if (terminating && buffer.isEmpty) { completion.success(Done) @@ -185,8 +185,8 @@ import scala.concurrent.{ Future, Promise } val p = Promise[QueueOfferResult] callback.invokeWithFeedback(Offer(element, p)) .onComplete { - case scala.util.Success(_) ⇒ - case scala.util.Failure(e) ⇒ p.tryFailure(e) + case scala.util.Success(_) => + case scala.util.Failure(e) => p.tryFailure(e) }(akka.dispatch.ExecutionContexts.sameThreadExecutionContext) p.future } diff --git a/akka-stream/src/main/scala/akka/stream/impl/ReactiveStreamsCompliance.scala b/akka-stream/src/main/scala/akka/stream/impl/ReactiveStreamsCompliance.scala index 9aca302059..bf4c7a4d02 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ReactiveStreamsCompliance.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ReactiveStreamsCompliance.scala @@ -83,43 +83,43 @@ import org.reactivestreams.{ Subscriber, Subscription } final def tryOnError[T](subscriber: Subscriber[T], error: Throwable): Unit = error match { - case sv: SpecViolation ⇒ throw new IllegalStateException("It is not legal to try to signal onError with a SpecViolation", sv) - case other ⇒ + case sv: SpecViolation => throw new IllegalStateException("It is not legal to try to signal onError with a SpecViolation", sv) + case other => try subscriber.onError(other) catch { - case NonFatal(t) ⇒ throw new SignalThrewException(subscriber + ".onError", t) + case NonFatal(t) => throw new SignalThrewException(subscriber + ".onError", t) } } final def tryOnNext[T](subscriber: Subscriber[T], element: T): Unit = { requireNonNullElement(element) try subscriber.onNext(element) catch { - case NonFatal(t) ⇒ throw new SignalThrewException(subscriber + ".onNext", t) + case NonFatal(t) => throw new SignalThrewException(subscriber + ".onNext", t) } } final def tryOnSubscribe[T](subscriber: Subscriber[T], subscription: Subscription): Unit = { try subscriber.onSubscribe(subscription) catch { - case NonFatal(t) ⇒ throw new SignalThrewException(subscriber + ".onSubscribe", t) + case NonFatal(t) => throw new SignalThrewException(subscriber + ".onSubscribe", t) } } final def tryOnComplete[T](subscriber: Subscriber[T]): Unit = { try subscriber.onComplete() catch { - case NonFatal(t) ⇒ throw new SignalThrewException(subscriber + ".onComplete", t) + case NonFatal(t) => throw new SignalThrewException(subscriber + ".onComplete", t) } } final def tryRequest(subscription: Subscription, demand: Long): Unit = { if (subscription eq null) throw new IllegalStateException("Subscription must be not null on request() call, rule 1.3") try subscription.request(demand) catch { - case NonFatal(t) ⇒ throw new SignalThrewException("It is illegal to throw exceptions from request(), rule 3.16", t) + case NonFatal(t) => throw new SignalThrewException("It is illegal to throw exceptions from request(), rule 3.16", t) } } final def tryCancel(subscription: Subscription): Unit = { if (subscription eq null) throw new IllegalStateException("Subscription must be not null on cancel() call, rule 1.3") try subscription.cancel() catch { - case NonFatal(t) ⇒ throw new SignalThrewException("It is illegal to throw exceptions from cancel(), rule 3.15", t) + case NonFatal(t) => throw new SignalThrewException("It is illegal to throw exceptions from cancel(), rule 3.15", t) } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/ResizableMultiReaderRingBuffer.scala b/akka-stream/src/main/scala/akka/stream/impl/ResizableMultiReaderRingBuffer.scala index a319a63437..10b3be64fa 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/ResizableMultiReaderRingBuffer.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/ResizableMultiReaderRingBuffer.scala @@ -89,10 +89,10 @@ import akka.annotation.InternalApi System.arraycopy(array, r, newArray, 0, array.length - r) System.arraycopy(array, 0, newArray, array.length - r, r) @tailrec def rebaseCursors(remaining: List[Cursor]): Unit = remaining match { - case head :: tail ⇒ + case head :: tail => head.cursor -= readIx rebaseCursors(tail) - case _ ⇒ // done + case _ => // done } rebaseCursors(cursors.cursors) array = newArray @@ -125,8 +125,8 @@ import akka.annotation.InternalApi private def updateReadIx(): Unit = { @tailrec def minCursor(remaining: List[Cursor], result: Int): Int = remaining match { - case head :: tail ⇒ minCursor(tail, math.min(head.cursor - writeIx, result)) - case _ ⇒ result + case head :: tail => minCursor(tail, math.min(head.cursor - writeIx, result)) + case _ => result } val newReadIx = writeIx + minCursor(cursors.cursors, 0) while (readIx != newReadIx) { diff --git a/akka-stream/src/main/scala/akka/stream/impl/Sinks.scala b/akka-stream/src/main/scala/akka/stream/impl/Sinks.scala index b9674fbb13..eef1d0a7a3 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/Sinks.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/Sinks.scala @@ -157,7 +157,7 @@ import akka.util.ccompat._ /** * INTERNAL API */ -@InternalApi private[akka] final class ActorRefSink[In](ref: ActorRef, onCompleteMessage: Any, onFailureMessage: Throwable ⇒ Any, +@InternalApi private[akka] final class ActorRefSink[In](ref: ActorRef, onCompleteMessage: Any, onFailureMessage: Throwable => Any, val attributes: Attributes, shape: SinkShape[In]) extends SinkModule[In, NotUsed](shape) { @@ -349,36 +349,36 @@ import akka.util.ccompat._ } private val callback = getAsyncCallback[Output[T]] { - case QueueSink.Pull(pullPromise) ⇒ currentRequest match { - case Some(_) ⇒ + case QueueSink.Pull(pullPromise) => currentRequest match { + case Some(_) => pullPromise.failure(new IllegalStateException("You have to wait for previous future to be resolved to send another request")) - case None ⇒ + case None => if (buffer.isEmpty) currentRequest = Some(pullPromise) else { if (buffer.used == maxBuffer) tryPull(in) sendDownstream(pullPromise) } } - case QueueSink.Cancel ⇒ completeStage() + case QueueSink.Cancel => completeStage() } def sendDownstream(promise: Requested[T]): Unit = { val e = buffer.dequeue() promise.complete(e) e match { - case Success(_: Some[_]) ⇒ //do nothing - case Success(None) ⇒ completeStage() - case Failure(t) ⇒ failStage(t) + case Success(_: Some[_]) => //do nothing + case Success(None) => completeStage() + case Failure(t) => failStage(t) } } def enqueueAndNotify(requested: Received[T]): Unit = { buffer.enqueue(requested) currentRequest match { - case Some(p) ⇒ + case Some(p) => sendDownstream(p) currentRequest = None - case None ⇒ //do nothing + case None => //do nothing } } @@ -397,8 +397,8 @@ import akka.util.ccompat._ val p = Promise[Option[T]] callback.invokeWithFeedback(Pull(p)) .failed.foreach { - case NonFatal(e) ⇒ p.tryFailure(e) - case _ ⇒ () + case NonFatal(e) => p.tryFailure(e) + case _ => () }(akka.dispatch.ExecutionContexts.sameThreadExecutionContext) p.future } @@ -415,7 +415,7 @@ import akka.util.ccompat._ * INTERNAL API */ @InternalApi private[akka] final class SinkQueueAdapter[T](delegate: SinkQueueWithCancel[T]) extends akka.stream.javadsl.SinkQueueWithCancel[T] { - import akka.dispatch.ExecutionContexts.{ sameThreadExecutionContext ⇒ same } + import akka.dispatch.ExecutionContexts.{ sameThreadExecutionContext => same } def pull(): CompletionStage[Optional[T]] = delegate.pull().map(_.asJava)(same).toJava def cancel(): Unit = delegate.cancel() @@ -459,7 +459,7 @@ import akka.util.ccompat._ /** * INTERNAL API */ -@InternalApi final private[stream] class LazySink[T, M](sinkFactory: T ⇒ Future[Sink[T, M]]) extends GraphStageWithMaterializedValue[SinkShape[T], Future[Option[M]]] { +@InternalApi final private[stream] class LazySink[T, M](sinkFactory: T => Future[Sink[T, M]]) extends GraphStageWithMaterializedValue[SinkShape[T], Future[Option[M]]] { val in = Inlet[T]("lazySink.in") override def initialAttributes = DefaultAttributes.lazySink override val shape: SinkShape[T] = SinkShape.of(in) @@ -478,7 +478,7 @@ import akka.util.ccompat._ switching = true val cb: AsyncCallback[Try[Sink[T, M]]] = getAsyncCallback { - case Success(sink) ⇒ + case Success(sink) => // check if the stage is still in need for the lazy sink // (there could have been an onUpstreamFailure in the meantime that has completed the promise) if (!promise.isCompleted) { @@ -487,19 +487,19 @@ import akka.util.ccompat._ promise.success(Some(mat)) setKeepGoing(true) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => promise.failure(e) failStage(e) } } - case Failure(e) ⇒ + case Failure(e) => promise.failure(e) failStage(e) } try { sinkFactory(element).onComplete(cb.invoke)(ExecutionContexts.sameThreadExecutionContext) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => promise.failure(e) failStage(e) } diff --git a/akka-stream/src/main/scala/akka/stream/impl/StreamLayout.scala b/akka-stream/src/main/scala/akka/stream/impl/StreamLayout.scala index 6ac3b03286..b580e00f79 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/StreamLayout.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/StreamLayout.scala @@ -125,19 +125,19 @@ import scala.util.control.NonFatal override def subscribe(s: Subscriber[_ >: T]): Unit = { @tailrec def rec(sub: Subscriber[Any]): Unit = { get() match { - case null ⇒ + case null => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(null).subscribe.rec($s) -> sub") if (!compareAndSet(null, s)) rec(sub) - case subscription: Subscription ⇒ + case subscription: Subscription => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($subscription).subscribe.rec($s) -> Establishing(sub)") val establishing = Establishing(sub, false) if (compareAndSet(subscription, establishing)) establishSubscription(establishing, subscription) else rec(sub) - case pub: Publisher[_] ⇒ + case pub: Publisher[_] => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($pub).subscribe.rec($s) -> Inert") if (compareAndSet(pub, Inert)) pub.subscribe(sub) else rec(sub) - case other ⇒ + case other => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($other).subscribe.rec($s): rejectAdditionalSubscriber") rejectAdditionalSubscriber(sub, "VirtualProcessor") } @@ -153,24 +153,24 @@ import scala.util.control.NonFatal override def onSubscribe(s: Subscription): Unit = { @tailrec def rec(obj: AnyRef): Unit = { get() match { - case null ⇒ + case null => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(null).onSubscribe.rec($obj) -> ${obj.getClass}") if (!compareAndSet(null, obj)) rec(obj) - case subscriber: Subscriber[_] ⇒ + case subscriber: Subscriber[_] => obj match { - case subscription: Subscription ⇒ + case subscription: Subscription => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($subscriber).onSubscribe.rec($obj) -> Establishing") val establishing = Establishing.create(subscriber) if (compareAndSet(subscriber, establishing)) establishSubscription(establishing, subscription) else rec(obj) - case pub: Publisher[_] ⇒ + case pub: Publisher[_] => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($subscriber).onSubscribe.rec($obj) -> INert") getAndSet(Inert) match { - case Inert ⇒ // nothing to be done - case _ ⇒ pub.subscribe(subscriber.asInstanceOf[Subscriber[Any]]) + case Inert => // nothing to be done + case _ => pub.subscribe(subscriber.asInstanceOf[Subscriber[Any]]) } } - case _ ⇒ + case _ => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(_).onSubscribe.rec($s) spec violation") // spec violation tryCancel(s) @@ -201,28 +201,28 @@ import scala.util.control.NonFatal } else { // changed by someone else get() match { - case Establishing(sub, _, OptionVal.Some(error)) ⇒ + case Establishing(sub, _, OptionVal.Some(error)) => // there was an onError while establishing if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode.establishSubscription.rec(Establishing(buffered-error) -> Inert") tryOnError(sub, error) set(Inert) - case Establishing(sub, true, _) ⇒ + case Establishing(sub, true, _) => // there was on onComplete while we were establishing if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode.establishSubscription.rec(Establishing(buffered-complete) -> Inert") tryOnComplete(sub) set(Inert) - case Inert ⇒ + case Inert => tryCancel(subscription) - case other ⇒ + case other => throw new IllegalStateException(s"Unexpected state while establishing: [$other], if this ever happens it is a bug.") } } } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => set(Inert) tryCancel(subscription) tryOnError(establishing.subscriber, ex) @@ -237,26 +237,26 @@ import scala.util.control.NonFatal */ @tailrec def rec(ex: Throwable): Unit = get() match { - case null ⇒ + case null => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(null).onError(${ex.getMessage}) -> ErrorPublisher") if (!compareAndSet(null, ErrorPublisher(ex, "failed-VirtualProcessor"))) rec(ex) - case s: Subscription ⇒ + case s: Subscription => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($s).onError(${ex.getMessage}) -> ErrorPublisher") if (!compareAndSet(s, ErrorPublisher(ex, "failed-VirtualProcessor"))) rec(ex) - case Both(s) ⇒ + case Both(s) => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(Both($s)).onError(${ex.getMessage}) -> ErrorPublisher") set(Inert) tryOnError(s, ex) - case s: Subscriber[_] ⇒ // spec violation + case s: Subscriber[_] => // spec violation if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($s).onError(${ex.getMessage}) -> Inert") getAndSet(Inert) match { - case Inert ⇒ // nothing to be done - case _ ⇒ ErrorPublisher(ex, "failed-VirtualProcessor").subscribe(s) + case Inert => // nothing to be done + case _ => ErrorPublisher(ex, "failed-VirtualProcessor").subscribe(s) } - case est @ Establishing(_, false, OptionVal.None) ⇒ + case est @ Establishing(_, false, OptionVal.None) => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($est).onError(${ex.getMessage}), loop") if (!compareAndSet(est, est.copy(onErrorBuffered = OptionVal.Some(ex)))) rec(ex) - case other ⇒ + case other => // spec violation or cancellation race, but nothing we can do if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($other).onError(${ex.getMessage}). spec violation or cancellation race") } @@ -269,24 +269,24 @@ import scala.util.control.NonFatal @tailrec override def onComplete(): Unit = { get() match { - case null ⇒ + case null => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(null).onComplete -> EmptyPublisher") if (!compareAndSet(null, EmptyPublisher)) onComplete() - case s: Subscription ⇒ + case s: Subscription => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($s).onComplete -> EmptyPublisher") if (!compareAndSet(s, EmptyPublisher)) onComplete() - case _@ Both(s) ⇒ + case _@ Both(s) => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($s).onComplete -> Inert") set(Inert) tryOnComplete(s) - case s: Subscriber[_] ⇒ // spec violation + case s: Subscriber[_] => // spec violation if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($s).onComplete -> Inert") set(Inert) EmptyPublisher.subscribe(s) - case est @ Establishing(_, false, OptionVal.None) ⇒ + case est @ Establishing(_, false, OptionVal.None) => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($est).onComplete -> Establishing with buffered complete") if (!est.onCompleteBuffered && !compareAndSet(est, est.copy(onCompleteBuffered = true))) onComplete() - case other ⇒ + case other => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($other).onComplete spec violation") // spec violation or cancellation race, but nothing we can do } @@ -298,40 +298,40 @@ import scala.util.control.NonFatal if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode.onNext(null)") @tailrec def rec(): Unit = get() match { - case x @ (null | _: Subscription) ⇒ if (!compareAndSet(x, ErrorPublisher(ex, "failed-VirtualProcessor"))) rec() - case s: Subscriber[_] ⇒ try s.onError(ex) catch { case NonFatal(_) ⇒ } finally set(Inert) - case Both(s) ⇒ try s.onError(ex) catch { case NonFatal(_) ⇒ } finally set(Inert) - case _ ⇒ // spec violation or cancellation race, but nothing we can do + case x @ (null | _: Subscription) => if (!compareAndSet(x, ErrorPublisher(ex, "failed-VirtualProcessor"))) rec() + case s: Subscriber[_] => try s.onError(ex) catch { case NonFatal(_) => } finally set(Inert) + case Both(s) => try s.onError(ex) catch { case NonFatal(_) => } finally set(Inert) + case _ => // spec violation or cancellation race, but nothing we can do } rec() throw ex // must throw NPE, rule 2:13 } else { @tailrec def rec(): Unit = { get() match { - case h: HasActualSubscriber ⇒ + case h: HasActualSubscriber => val s = h.subscriber try { if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(${h.getClass.getName}($s)).onNext($t).rec()") s.onNext(t) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(Both($s)).onNext($t) threw, spec violation -> Inert") set(Inert) throw new IllegalStateException("Subscriber threw exception, this is in violation of rule 2:13", e) } - case s: Subscriber[_] ⇒ // spec violation + case s: Subscriber[_] => // spec violation if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($s).onNext($t).rec(): spec violation -> Inert") val ex = new IllegalStateException(noDemand) getAndSet(Inert) match { - case Inert ⇒ // nothing to be done - case _ ⇒ ErrorPublisher(ex, "failed-VirtualProcessor").subscribe(s) + case Inert => // nothing to be done + case _ => ErrorPublisher(ex, "failed-VirtualProcessor").subscribe(s) } throw ex - case Inert | _: Publisher[_] ⇒ + case Inert | _: Publisher[_] => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(Inert|Publisher).onNext($t).rec(): nop") // nothing to be done - case other ⇒ + case other => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($other).onNext($t).rec() -> ErrorPublisher") val pub = ErrorPublisher(new IllegalStateException(noDemand), "failed-VirtualPublisher") if (!compareAndSet(other, pub)) rec() @@ -370,10 +370,10 @@ import scala.util.control.NonFatal if (VirtualProcessor.Debug) println(s"VirtualPublisher#${VirtualProcessor.this.hashCode}.WrappedSubscription($real).request($n)") tryCancel(real) VirtualProcessor.this.getAndSet(Inert) match { - case Both(subscriber) ⇒ rejectDueToNonPositiveDemand(subscriber) - case est: Establishing ⇒ rejectDueToNonPositiveDemand(est.subscriber) - case Inert ⇒ // another failure has won the race - case _ ⇒ // this cannot possibly happen, but signaling errors is impossible at this point + case Both(subscriber) => rejectDueToNonPositiveDemand(subscriber) + case est: Establishing => rejectDueToNonPositiveDemand(est.subscriber) + case Inert => // another failure has won the race + case _ => // this cannot possibly happen, but signaling errors is impossible at this point } } else { // NOTE: At this point, batched requests might not have been dispatched, i.e. this can reorder requests. @@ -427,15 +427,15 @@ import scala.util.control.NonFatal requireNonNullSubscriber(subscriber) @tailrec def rec(): Unit = { get() match { - case null ⇒ + case null => if (!compareAndSet(null, subscriber)) rec() // retry - case pub: Publisher[_] ⇒ + case pub: Publisher[_] => if (compareAndSet(pub, Inert.subscriber)) { pub.asInstanceOf[Publisher[T]].subscribe(subscriber) } else rec() // retry - case _: Subscriber[_] ⇒ + case _: Subscriber[_] => rejectAdditionalSubscriber(subscriber, "Sink.asPublisher(fanout = false)") } } @@ -445,17 +445,17 @@ import scala.util.control.NonFatal @tailrec final def registerPublisher(pub: Publisher[_]): Unit = { if (VirtualProcessor.Debug) println(s"$this.registerPublisher: $pub") get() match { - case null ⇒ + case null => if (!compareAndSet(null, pub)) registerPublisher(pub) // retry - case sub: Subscriber[r] ⇒ + case sub: Subscriber[r] => set(Inert.subscriber) pub.asInstanceOf[Publisher[r]].subscribe(sub) - case p: Publisher[_] ⇒ + case p: Publisher[_] => throw new IllegalStateException(s"internal error, already registered [$p], yet attempted to register 2nd publisher [$pub]!") - case unexpected ⇒ + case unexpected => throw new IllegalStateException(s"internal error, unexpected state: $unexpected") } } @@ -467,7 +467,7 @@ import scala.util.control.NonFatal * INTERNAL API */ @InternalApi private[akka] final case class ProcessorModule[In, Out, Mat]( - val createProcessor: () ⇒ (Processor[In, Out], Mat), + val createProcessor: () => (Processor[In, Out], Mat), attributes: Attributes = DefaultAttributes.processor) extends StreamLayout.AtomicModule[FlowShape[In, Out], Mat] { val inPort = Inlet[In]("ProcessorModule.in") val outPort = Outlet[Out]("ProcessorModule.out") diff --git a/akka-stream/src/main/scala/akka/stream/impl/StreamSubscriptionTimeout.scala b/akka-stream/src/main/scala/akka/stream/impl/StreamSubscriptionTimeout.scala index 6dd6aff270..1bbd3f3408 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/StreamSubscriptionTimeout.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/StreamSubscriptionTimeout.scala @@ -57,7 +57,7 @@ import scala.util.control.NoStackTrace * See `akka.stream.materializer.subscription-timeout` for configuration options. */ @InternalApi private[akka] trait StreamSubscriptionTimeoutSupport { - this: Actor with ActorLogging ⇒ + this: Actor with ActorLogging => import StreamSubscriptionTimeoutSupport._ @@ -72,9 +72,9 @@ import scala.util.control.NoStackTrace */ protected def scheduleSubscriptionTimeout(actor: ActorRef, message: Any): Cancellable = subscriptionTimeoutSettings.mode match { - case NoopTermination ⇒ + case NoopTermination => NoopSubscriptionTimeout - case _ ⇒ + case _ => import context.dispatcher val cancellable = context.system.scheduler.scheduleOnce(subscriptionTimeoutSettings.timeout, actor, message) cancellable @@ -83,11 +83,11 @@ import scala.util.control.NoStackTrace private def cancel(target: Publisher[_], timeout: FiniteDuration): Unit = { val millis = timeout.toMillis target match { - case p: Processor[_, _] ⇒ + case p: Processor[_, _] => log.debug("Cancelling {} Processor's publisher and subscriber sides (after {} ms)", p, millis) handleSubscriptionTimeout(target, new SubscriptionTimeoutException(s"Publisher was not attached to upstream within deadline ($millis) ms") with NoStackTrace) - case p: Publisher[_] ⇒ + case p: Publisher[_] => log.debug("Cancelling {} (after: {} ms)", p, millis) handleSubscriptionTimeout(target, new SubscriptionTimeoutException(s"Publisher ($p) you are trying to subscribe to has been shut-down " + s"because exceeding it's subscription-timeout.") with NoStackTrace) @@ -104,9 +104,9 @@ import scala.util.control.NoStackTrace * Called by the actor when a subscription has timed out. Expects the actual `Publisher` or `Processor` target. */ protected def subscriptionTimedOut(target: Publisher[_]): Unit = subscriptionTimeoutSettings.mode match { - case NoopTermination ⇒ // ignore... - case WarnTermination ⇒ warn(target, subscriptionTimeoutSettings.timeout) - case CancelTermination ⇒ cancel(target, subscriptionTimeoutSettings.timeout) + case NoopTermination => // ignore... + case WarnTermination => warn(target, subscriptionTimeoutSettings.timeout) + case CancelTermination => cancel(target, subscriptionTimeoutSettings.timeout) } /** diff --git a/akka-stream/src/main/scala/akka/stream/impl/SubFlowImpl.scala b/akka-stream/src/main/scala/akka/stream/impl/SubFlowImpl.scala index 8fb198f4c7..67ff8d94a2 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/SubFlowImpl.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/SubFlowImpl.scala @@ -26,7 +26,7 @@ import language.higherKinds @InternalApi private[akka] class SubFlowImpl[In, Out, Mat, F[+_], C]( val subFlow: Flow[In, Out, NotUsed], mergeBackFunction: SubFlowImpl.MergeBack[In, F], - finishFunction: Sink[In, NotUsed] ⇒ C) + finishFunction: Sink[In, NotUsed] => C) extends SubFlow[Out, Mat, F, C] { override def via[T, Mat2](flow: Graph[FlowShape[Out, T], Mat2]): Repr[T] = diff --git a/akka-stream/src/main/scala/akka/stream/impl/SubscriberManagement.scala b/akka-stream/src/main/scala/akka/stream/impl/SubscriberManagement.scala index cacd53573d..44df13d18d 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/SubscriberManagement.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/SubscriberManagement.scala @@ -111,7 +111,7 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff finally unregisterSubscriptionInternal(subscription) } else { endOfStream match { - case eos @ (NotReached | Completed) ⇒ + case eos @ (NotReached | Completed) => val d = subscription.totalDemand + elements // Long overflow, Reactive Streams Spec 3:17: effectively unbounded val demand = if (d < 1) Long.MaxValue else d @@ -126,7 +126,7 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff subscription.dispatch(buffer.read(subscription)) true } catch { - case _: SpecViolation ⇒ + case _: SpecViolation => unregisterSubscriptionInternal(subscription) false } @@ -136,14 +136,14 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff else requested dispatchFromBufferAndReturnRemainingRequested(demand, eos) match { - case Long.MinValue ⇒ + case Long.MinValue => eos(subscription.subscriber) unregisterSubscriptionInternal(subscription) - case x ⇒ + case x => subscription.totalDemand = x requestFromUpstreamIfRequired() } - case ErrorCompleted(_) ⇒ // ignore, the Subscriber might not have seen our error event yet + case ErrorCompleted(_) => // ignore, the Subscriber might not have seen our error event yet } } } @@ -151,8 +151,8 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff private[this] final def requestFromUpstreamIfRequired(): Unit = { @tailrec def maxRequested(remaining: Subscriptions, result: Long = 0): Long = remaining match { - case head :: tail ⇒ maxRequested(tail, math.max(head.totalDemand, result)) - case _ ⇒ result + case head :: tail => maxRequested(tail, math.max(head.totalDemand, result)) + case _ => result } val desired = Math.min(Int.MaxValue, Math.min(maxRequested(subscriptions), buffer.maxAvailable) - pendingFromUpstream).toInt if (desired > 0) { @@ -167,22 +167,22 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff protected def pushToDownstream(value: T): Unit = { @tailrec def dispatch(remaining: Subscriptions, sent: Boolean = false): Boolean = remaining match { - case head :: tail ⇒ + case head :: tail => if (head.totalDemand > 0) { val element = buffer.read(head) head.dispatch(element) head.totalDemand -= 1 dispatch(tail, sent = true) } else dispatch(tail, sent) - case _ ⇒ sent + case _ => sent } endOfStream match { - case NotReached ⇒ + case NotReached => pendingFromUpstream -= 1 if (!buffer.write(value)) throw new IllegalStateException("Output buffer overflow") if (dispatch(subscriptions)) requestFromUpstreamIfRequired() - case _ ⇒ + case _ => throw new IllegalStateException("pushToDownStream(...) after completeDownstream() or abortDownstream(...)") } } @@ -195,13 +195,13 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff if (endOfStream eq NotReached) { @tailrec def completeDoneSubscriptions(remaining: Subscriptions, result: Subscriptions = Nil): Subscriptions = remaining match { - case head :: tail ⇒ + case head :: tail => if (buffer.count(head) == 0) { head.active = false Completed(head.subscriber) completeDoneSubscriptions(tail, result) } else completeDoneSubscriptions(tail, head :: result) - case _ ⇒ result + case _ => result } endOfStream = Completed subscriptions = completeDoneSubscriptions(subscriptions) @@ -214,7 +214,7 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff */ protected def abortDownstream(cause: Throwable): Unit = { endOfStream = ErrorCompleted(cause) - subscriptions.foreach(s ⇒ endOfStream(s.subscriber)) + subscriptions.foreach(s => endOfStream(s.subscriber)) subscriptions = Nil } @@ -222,10 +222,10 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff * Register a new subscriber. */ protected def registerSubscriber(subscriber: Subscriber[_ >: T]): Unit = endOfStream match { - case NotReached if subscriptions.exists(_.subscriber == subscriber) ⇒ ReactiveStreamsCompliance.rejectDuplicateSubscriber(subscriber) - case NotReached ⇒ addSubscription(subscriber) - case Completed if buffer.nonEmpty ⇒ addSubscription(subscriber) - case eos ⇒ eos(subscriber) + case NotReached if subscriptions.exists(_.subscriber == subscriber) => ReactiveStreamsCompliance.rejectDuplicateSubscriber(subscriber) + case NotReached => addSubscription(subscriber) + case Completed if buffer.nonEmpty => addSubscription(subscriber) + case eos => eos(subscriber) } private def addSubscription(subscriber: Subscriber[_ >: T]): Unit = { @@ -235,7 +235,7 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff buffer.initCursor(newSubscription) try tryOnSubscribe(subscriber, newSubscription) catch { - case _: SpecViolation ⇒ unregisterSubscriptionInternal(newSubscription) + case _: SpecViolation => unregisterSubscriptionInternal(newSubscription) } } @@ -250,8 +250,8 @@ private[akka] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuff private def unregisterSubscriptionInternal(subscription: S): Unit = { @tailrec def removeFrom(remaining: Subscriptions, result: Subscriptions = Nil): Subscriptions = remaining match { - case head :: tail ⇒ if (head eq subscription) tail reverse_::: result else removeFrom(tail, head :: result) - case _ ⇒ throw new IllegalStateException("Subscription to unregister not found") + case head :: tail => if (head eq subscription) tail reverse_::: result else removeFrom(tail, head :: result) + case _ => throw new IllegalStateException("Subscription to unregister not found") } if (subscription.active) { subscriptions = removeFrom(subscriptions) diff --git a/akka-stream/src/main/scala/akka/stream/impl/Throttle.scala b/akka-stream/src/main/scala/akka/stream/impl/Throttle.scala index 89b2040784..6b362cf2c8 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/Throttle.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/Throttle.scala @@ -27,7 +27,7 @@ import scala.concurrent.duration.{ FiniteDuration, _ } val cost: Int, val per: FiniteDuration, val maximumBurst: Int, - val costCalculation: (T) ⇒ Int, + val costCalculation: (T) => Int, val mode: ThrottleMode) extends SimpleLinearGraphStage[T] { require(cost > 0, "cost must be > 0") @@ -53,8 +53,8 @@ import scala.concurrent.duration.{ FiniteDuration, _ } var willStop = false var currentElement: T = _ val enforcing = mode match { - case Enforcing ⇒ true - case Shaping ⇒ false + case Enforcing => true + case Shaping => false } override def preStart(): Unit = tokenBucket.init() diff --git a/akka-stream/src/main/scala/akka/stream/impl/Timers.scala b/akka-stream/src/main/scala/akka/stream/impl/Timers.scala index a9946ff988..3c3c6a71e0 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/Timers.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/Timers.scala @@ -213,7 +213,7 @@ import scala.concurrent.duration.{ Duration, FiniteDuration } } - final class IdleInject[I, O >: I](val timeout: FiniteDuration, val inject: () ⇒ O) extends GraphStage[FlowShape[I, O]] { + final class IdleInject[I, O >: I](val timeout: FiniteDuration, val inject: () => O) extends GraphStage[FlowShape[I, O]] { val in: Inlet[I] = Inlet("IdleInject.in") val out: Outlet[O] = Outlet("IdleInject.out") diff --git a/akka-stream/src/main/scala/akka/stream/impl/Transfer.scala b/akka-stream/src/main/scala/akka/stream/impl/Transfer.scala index 6cb72a36db..104fcd552d 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/Transfer.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/Transfer.scala @@ -146,15 +146,15 @@ import akka.annotation.InternalApi /** * INTERNAL API */ -@InternalApi private[akka] final case class TransferPhase(precondition: TransferState)(val action: () ⇒ Unit) +@InternalApi private[akka] final case class TransferPhase(precondition: TransferState)(val action: () => Unit) /** * INTERNAL API */ @InternalApi private[akka] trait Pump { private var transferState: TransferState = NotInitialized - private var currentAction: () ⇒ Unit = - () ⇒ throw new IllegalStateException("Pump has been not initialized with a phase") + private var currentAction: () => Unit = + () => throw new IllegalStateException("Pump has been not initialized with a phase") final def initialPhase(waitForUpstream: Int, andThen: TransferPhase): Unit = { require(waitForUpstream >= 1, s"waitForUpstream must be >= 1 (was $waitForUpstream)") @@ -170,20 +170,20 @@ import akka.annotation.InternalApi def gotUpstreamSubscription(): Unit = { transferState match { - case WaitingForUpstreamSubscription(1, andThen) ⇒ + case WaitingForUpstreamSubscription(1, andThen) => transferState = andThen.precondition currentAction = andThen.action - case WaitingForUpstreamSubscription(remaining, andThen) ⇒ + case WaitingForUpstreamSubscription(remaining, andThen) => transferState = WaitingForUpstreamSubscription(remaining - 1, andThen) - case _ ⇒ // ok, initial phase not used, or passed already + case _ => // ok, initial phase not used, or passed already } pump() } final def nextPhase(phase: TransferPhase): Unit = transferState match { - case WaitingForUpstreamSubscription(remaining, _) ⇒ + case WaitingForUpstreamSubscription(remaining, _) => transferState = WaitingForUpstreamSubscription(remaining, phase) - case _ ⇒ + case _ => transferState = phase.precondition currentAction = phase.action } @@ -191,7 +191,7 @@ import akka.annotation.InternalApi final def isPumpFinished: Boolean = transferState.isCompleted protected final val completedPhase = TransferPhase(Completed) { - () ⇒ throw new IllegalStateException("The action of completed phase must be never executed") + () => throw new IllegalStateException("The action of completed phase must be never executed") } // Exchange input buffer elements and output buffer "requests" until one of them becomes empty. @@ -199,7 +199,7 @@ import akka.annotation.InternalApi final def pump(): Unit = { try while (transferState.isExecutable) { currentAction() - } catch { case NonFatal(e) ⇒ pumpFailed(e) } + } catch { case NonFatal(e) => pumpFailed(e) } if (isPumpFinished) pumpFinished() } diff --git a/akka-stream/src/main/scala/akka/stream/impl/TraversalBuilder.scala b/akka-stream/src/main/scala/akka/stream/impl/TraversalBuilder.scala index 472c1f2df2..4b2aef36e0 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/TraversalBuilder.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/TraversalBuilder.scala @@ -65,19 +65,19 @@ import akka.stream.impl.fusing.GraphStages.SingleSource else if (first eq PushNotUsed) { // No need to push NotUsed and Pop it immediately second match { - case Pop ⇒ EmptyTraversal - case Concat(Pop, rest) ⇒ rest - case _ ⇒ Concat(PushNotUsed, second) + case Pop => EmptyTraversal + case Concat(Pop, rest) => rest + case _ => Concat(PushNotUsed, second) } } else { // Limit the tree by rotations first match { - case Concat(firstfirst, firstsecond) ⇒ + case Concat(firstfirst, firstsecond) => // Note that we DON'T use firstfirst.concat(firstsecond.concat(second)) here, // although that would fully linearize the tree. // The reason is to simply avoid going n^2. The rotation below is of constant time and good enough. Concat(firstfirst, Concat(firstsecond, second)) - case _ ⇒ Concat(first, second) + case _ => Concat(first, second) } } } @@ -154,7 +154,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource * INTERNAL API */ @InternalApi private[akka] final case class Transform(mapper: AnyFunction1) extends MaterializedValueOp { - def apply(arg: Any): Any = mapper.asInstanceOf[Any ⇒ Any](arg) + def apply(arg: Any): Any = mapper.asInstanceOf[Any => Any](arg) } /** @@ -163,9 +163,9 @@ import akka.stream.impl.fusing.GraphStages.SingleSource @InternalApi private[akka] final case class Compose(composer: AnyFunction2, reverse: Boolean = false) extends MaterializedValueOp { def apply(arg1: Any, arg2: Any): Any = { if (reverse) - composer.asInstanceOf[(Any, Any) ⇒ Any](arg2, arg1) + composer.asInstanceOf[(Any, Any) => Any](arg2, arg1) else - composer.asInstanceOf[(Any, Any) ⇒ Any](arg1, arg2) + composer.asInstanceOf[(Any, Any) => Any](arg1, arg2) } } @@ -195,8 +195,8 @@ import akka.stream.impl.fusing.GraphStages.SingleSource @InternalApi private[akka] object TraversalBuilder { // The most generic function1 and function2 (also completely useless, as we have thrown away all types) // needs to be casted once to be useful (pending runtime exception in cases of bugs). - type AnyFunction1 = Nothing ⇒ Any - type AnyFunction2 = (Nothing, Nothing) ⇒ Any + type AnyFunction1 = Nothing => Any + type AnyFunction2 = (Nothing, Nothing) => Any private val cachedEmptyCompleted = CompletedTraversalBuilder(PushNotUsed, 0, Map.empty, Attributes.none) @@ -258,7 +258,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource val b = CompletedTraversalBuilder( traversalSoFar = MaterializeAtomic(module, new Array[Int](module.shape.outlets.size)), inSlots = module.shape.inlets.size, - inToOffset = module.shape.inlets.map(in ⇒ in → in.id).toMap, + inToOffset = module.shape.inlets.map(in => in -> in.id).toMap, Attributes.none) b } else { @@ -284,20 +284,20 @@ import akka.stream.impl.fusing.GraphStages.SingleSource var nextStep: Traversal = EmptyTraversal current match { - case PushNotUsed ⇒ prindent("push NotUsed") - case Pop ⇒ prindent("pop mat") - case _: Transform ⇒ prindent("transform mat") - case Compose(_, false) ⇒ prindent("compose mat") - case Compose(_, true) ⇒ prindent("compose reversed mat") - case PushAttributes(attr) ⇒ prindent("push attr " + attr) - case PopAttributes ⇒ prindent("pop attr") - case EnterIsland(tag) ⇒ prindent("enter island " + tag) - case ExitIsland ⇒ prindent("exit island") - case MaterializeAtomic(mod, outToSlots) ⇒ prindent("materialize " + mod + " " + outToSlots.mkString("[", ", ", "]")) - case Concat(first, next) ⇒ + case PushNotUsed => prindent("push NotUsed") + case Pop => prindent("pop mat") + case _: Transform => prindent("transform mat") + case Compose(_, false) => prindent("compose mat") + case Compose(_, true) => prindent("compose reversed mat") + case PushAttributes(attr) => prindent("push attr " + attr) + case PopAttributes => prindent("pop attr") + case EnterIsland(tag) => prindent("enter island " + tag) + case ExitIsland => prindent("exit island") + case MaterializeAtomic(mod, outToSlots) => prindent("materialize " + mod + " " + outToSlots.mkString("[", ", ", "]")) + case Concat(first, next) => printTraversal(first, indent + 1) nextStep = next - case _ ⇒ + case _ => } current = nextStep @@ -315,20 +315,20 @@ import akka.stream.impl.fusing.GraphStages.SingleSource var nextStep: Traversal = EmptyTraversal current match { - case MaterializeAtomic(mod, outToSlots) ⇒ + case MaterializeAtomic(mod, outToSlots) => println(s"materialize $mod") val base = slot - mod.shape.inlets.foreach { in ⇒ + mod.shape.inlets.foreach { in => println(s" wiring $in to $slot") slot += 1 } - mod.shape.outlets.foreach { out ⇒ + mod.shape.outlets.foreach { out => println(s" wiring $out to ${base + outToSlots(out.id)}") } - case Concat(first, next) ⇒ + case Concat(first, next) => slot = printWiring(first, slot) nextStep = next - case _ ⇒ + case _ => } current = nextStep @@ -342,27 +342,27 @@ import akka.stream.impl.fusing.GraphStages.SingleSource */ def getSingleSource[A >: Null](graph: Graph[SourceShape[A], _]): OptionVal[SingleSource[A]] = { graph match { - case single: SingleSource[A] @unchecked ⇒ OptionVal.Some(single) - case _ ⇒ + case single: SingleSource[A] @unchecked => OptionVal.Some(single) + case _ => graph.traversalBuilder match { - case l: LinearTraversalBuilder ⇒ + case l: LinearTraversalBuilder => l.pendingBuilder match { - case OptionVal.Some(a: AtomicTraversalBuilder) ⇒ + case OptionVal.Some(a: AtomicTraversalBuilder) => a.module match { - case m: GraphStageModule[_, _] ⇒ + case m: GraphStageModule[_, _] => m.stage match { - case single: SingleSource[A] @unchecked ⇒ + case single: SingleSource[A] @unchecked => // It would be != EmptyTraversal if mapMaterializedValue was used and then we can't optimize. if ((l.traversalSoFar eq EmptyTraversal) && !l.attributes.isAsync) OptionVal.Some(single) else OptionVal.None - case _ ⇒ OptionVal.None + case _ => OptionVal.None } - case _ ⇒ OptionVal.None + case _ => OptionVal.None } - case _ ⇒ OptionVal.None + case _ => OptionVal.None } - case _ ⇒ OptionVal.None + case _ => OptionVal.None } } } @@ -495,14 +495,14 @@ import akka.stream.impl.fusing.GraphStages.SingleSource reverseBuildSteps = key :: Nil, inSlots = inSlots, inOffsets = inToOffset, - pendingBuilders = Map(key → this), + pendingBuilders = Map(key -> this), attributes = attributes).add(submodule, shape, combineMat) } override def traversal: Traversal = { val withIsland = islandTag match { - case OptionVal.Some(tag) ⇒ EnterIsland(tag).concat(traversalSoFar).concat(ExitIsland) - case _ ⇒ traversalSoFar + case OptionVal.Some(tag) => EnterIsland(tag).concat(traversalSoFar).concat(ExitIsland) + case _ => traversalSoFar } if (attributes eq Attributes.none) withIsland @@ -526,8 +526,8 @@ import akka.stream.impl.fusing.GraphStages.SingleSource override def makeIsland(islandTag: IslandTag): TraversalBuilder = this.islandTag match { - case OptionVal.None ⇒ copy(islandTag = OptionVal(islandTag)) - case OptionVal.Some(_) ⇒ this + case OptionVal.None => copy(islandTag = OptionVal(islandTag)) + case OptionVal.Some(_) => this } override def assign(out: OutPort, relativeSlot: Int): TraversalBuilder = @@ -588,7 +588,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource val inlets = module.shape.inlets if (inlets.isEmpty) Map.empty else if (Shape.hasOnePort(inlets)) new Map1(inlets.head, inlets.head.id) - else inlets.iterator.map(in ⇒ in.asInstanceOf[InPort] → in.id).toMap + else inlets.iterator.map(in => in.asInstanceOf[InPort] -> in.id).toMap } CompletedTraversalBuilder( traversalSoFar = MaterializeAtomic(module, newOutToSlot), @@ -660,15 +660,15 @@ import akka.stream.impl.fusing.GraphStages.SingleSource shape: Shape, combine: AnyFunction2 = Keep.right): LinearTraversalBuilder = { traversalBuilder match { - case linear: LinearTraversalBuilder ⇒ + case linear: LinearTraversalBuilder => if (combine eq Keep.right) linear else empty().append(linear, combine) - case completed: CompletedTraversalBuilder ⇒ + case completed: CompletedTraversalBuilder => val inOpt = OptionVal(shape.inlets.headOption.orNull) val inOffs = inOpt match { - case OptionVal.Some(in) ⇒ completed.offsetOf(in) - case OptionVal.None ⇒ 0 + case OptionVal.Some(in) => completed.offsetOf(in) + case OptionVal.None => 0 } LinearTraversalBuilder( @@ -680,12 +680,12 @@ import akka.stream.impl.fusing.GraphStages.SingleSource pendingBuilder = OptionVal.None, Attributes.none) - case composite ⇒ + case composite => val inOpt = OptionVal(shape.inlets.headOption.orNull) val out = shape.outlets.head // Cannot be empty, otherwise it would be a CompletedTraversalBuilder val inOffs = inOpt match { - case OptionVal.Some(in) ⇒ composite.offsetOf(in) - case OptionVal.None ⇒ 0 + case OptionVal.Some(in) => composite.offsetOf(in) + case OptionVal.None => 0 } LinearTraversalBuilder( @@ -750,8 +750,8 @@ import akka.stream.impl.fusing.GraphStages.SingleSource private def applyIslandAndAttributes(t: Traversal): Traversal = { val withIslandTag = islandTag match { - case OptionVal.None ⇒ t - case OptionVal.Some(tag) ⇒ EnterIsland(tag).concat(t).concat(ExitIsland) + case OptionVal.None => t + case OptionVal.Some(tag) => EnterIsland(tag).concat(t).concat(ExitIsland) } if (attributes eq Attributes.none) withIslandTag @@ -777,7 +777,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource override def wire(out: OutPort, in: InPort): TraversalBuilder = { if (outPort.contains(out) && inPort.contains(in)) { pendingBuilder match { - case OptionVal.Some(composite) ⇒ + case OptionVal.Some(composite) => copy( inPort = OptionVal.None, outPort = OptionVal.None, @@ -788,7 +788,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource .assign(out, inOffset - composite.offsetOfModule(out)) .traversal).concat(traversalSoFar)), pendingBuilder = OptionVal.None, beforeBuilder = EmptyTraversal) - case OptionVal.None ⇒ + case OptionVal.None => copy( inPort = OptionVal.None, outPort = OptionVal.None, @@ -801,8 +801,8 @@ import akka.stream.impl.fusing.GraphStages.SingleSource override def offsetOfModule(out: OutPort): Int = { if (outPort.contains(out)) { pendingBuilder match { - case OptionVal.Some(composite) ⇒ composite.offsetOfModule(out) - case OptionVal.None ⇒ 0 // Output belongs to the last module, which will be materialized *first* + case OptionVal.Some(composite) => composite.offsetOfModule(out) + case OptionVal.None => 0 // Output belongs to the last module, which will be materialized *first* } } else throw new IllegalArgumentException(s"Port $out cannot be accessed in this builder") @@ -820,7 +820,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource override def assign(out: OutPort, relativeSlot: Int): TraversalBuilder = { if (outPort.contains(out)) { pendingBuilder match { - case OptionVal.Some(composite) ⇒ + case OptionVal.Some(composite) => copy( outPort = OptionVal.None, traversalSoFar = @@ -832,7 +832,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource .concat(traversalSoFar))), pendingBuilder = OptionVal.None, beforeBuilder = EmptyTraversal) - case OptionVal.None ⇒ + case OptionVal.None => copy( outPort = OptionVal.None, traversalSoFar = rewireLastOutTo(traversalSoFar, relativeSlot)) @@ -906,7 +906,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource * different. */ val assembledTraversalForThis = this.pendingBuilder match { - case OptionVal.None ⇒ + case OptionVal.None => /* * This is the case where we are a pure linear builder (all composites have been already completed), * which means that traversalSoFar contains everything already, except the final attributes and islands @@ -945,7 +945,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource rewireLastOutTo(traversalSoFar, toAppend.inOffset - toAppend.inSlots) } - case OptionVal.Some(composite) ⇒ + case OptionVal.Some(composite) => /* * This is the case where our last module is a composite, and since it does not have its output port * wired yet, the traversal is split into the parts, traversalSoFar, pendingBuilder and beforeBuilder. @@ -999,7 +999,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource * There are two variants, depending whether toAppend is purely linear or if it has a composite at the end. */ toAppend.pendingBuilder match { - case OptionVal.None ⇒ + case OptionVal.None => /* * This is the simple case, when the other is purely linear. We just concatenate the traversals * and do some bookkeeping. @@ -1018,7 +1018,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource islandTag = OptionVal.None // islandTag is reset for the new enclosing builder ) - case OptionVal.Some(_) ⇒ + case OptionVal.Some(_) => /* * In this case we need to assemble as much as we can, and create a new "sandwich" of * beforeBuilder ~ pendingBuilder ~ traversalSoFar @@ -1032,8 +1032,8 @@ import akka.stream.impl.fusing.GraphStages.SingleSource // First prepare island enter and exit if tags are present toAppend.islandTag match { - case OptionVal.None ⇒ // Nothing changes - case OptionVal.Some(tag) ⇒ + case OptionVal.None => // Nothing changes + case OptionVal.Some(tag) => // Enter the island just before the appended builder (keeping the toAppend.beforeBuilder steps) newBeforeTraversal = EnterIsland(tag).concat(newBeforeTraversal) // Exit the island just after the appended builder (they should not applied to _this_ builder) @@ -1088,8 +1088,8 @@ import akka.stream.impl.fusing.GraphStages.SingleSource */ override def makeIsland(islandTag: IslandTag): LinearTraversalBuilder = this.islandTag match { - case OptionVal.Some(_) ⇒ this // Wrapping with an island, then immediately re-wrapping makes the second island empty, so can be omitted - case OptionVal.None ⇒ copy(islandTag = OptionVal.Some(islandTag)) + case OptionVal.Some(_) => this // Wrapping with an island, then immediately re-wrapping makes the second island empty, so can be omitted + case OptionVal.None => copy(islandTag = OptionVal.Some(islandTag)) } } @@ -1184,18 +1184,18 @@ import akka.stream.impl.fusing.GraphStages.SingleSource var remaining = reverseBuildSteps while (remaining.nonEmpty) { remaining.head match { - case key: BuilderKey ⇒ + case key: BuilderKey => // At this point all the builders we have are completed and we can finally build our traversal traversal = pendingBuilders(key).traversal.concat(traversal) - case AppendTraversal(toAppend) ⇒ + case AppendTraversal(toAppend) => traversal = toAppend.concat(traversal) } remaining = remaining.tail } val finalTraversal = islandTag match { - case OptionVal.None ⇒ traversal - case OptionVal.Some(tag) ⇒ EnterIsland(tag).concat(traversal).concat(ExitIsland) + case OptionVal.None => traversal + case OptionVal.Some(tag) => EnterIsland(tag).concat(traversal).concat(ExitIsland) } // The CompleteTraversalBuilder only keeps the minimum amount of necessary information that is needed for it @@ -1336,8 +1336,8 @@ import akka.stream.impl.fusing.GraphStages.SingleSource override def makeIsland(islandTag: IslandTag): TraversalBuilder = { this.islandTag match { - case OptionVal.None ⇒ copy(islandTag = OptionVal(islandTag)) - case _ ⇒ this // Wrapping with an island, then immediately re-wrapping makes the second island empty, so can be omitted + case OptionVal.None => copy(islandTag = OptionVal(islandTag)) + case _ => this // Wrapping with an island, then immediately re-wrapping makes the second island empty, so can be omitted } } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/Unfold.scala b/akka-stream/src/main/scala/akka/stream/impl/Unfold.scala index 30e8bf978a..b215fb9dfd 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/Unfold.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/Unfold.scala @@ -15,7 +15,7 @@ import scala.util.{ Failure, Success, Try } /** * INTERNAL API */ -@InternalApi private[akka] final class Unfold[S, E](s: S, f: S ⇒ Option[(S, E)]) extends GraphStage[SourceShape[E]] { +@InternalApi private[akka] final class Unfold[S, E](s: S, f: S => Option[(S, E)]) extends GraphStage[SourceShape[E]] { val out: Outlet[E] = Outlet("Unfold.out") override val shape: SourceShape[E] = SourceShape(out) override def initialAttributes: Attributes = DefaultAttributes.unfold @@ -24,8 +24,8 @@ import scala.util.{ Failure, Success, Try } private[this] var state = s def onPull(): Unit = f(state) match { - case None ⇒ complete(out) - case Some((newState, v)) ⇒ { + case None => complete(out) + case Some((newState, v)) => { push(out, v) state = newState } @@ -38,7 +38,7 @@ import scala.util.{ Failure, Success, Try } /** * INTERNAL API */ -@InternalApi private[akka] final class UnfoldAsync[S, E](s: S, f: S ⇒ Future[Option[(S, E)]]) extends GraphStage[SourceShape[E]] { +@InternalApi private[akka] final class UnfoldAsync[S, E](s: S, f: S => Future[Option[(S, E)]]) extends GraphStage[SourceShape[E]] { val out: Outlet[E] = Outlet("UnfoldAsync.out") override val shape: SourceShape[E] = SourceShape(out) override def initialAttributes: Attributes = DefaultAttributes.unfoldAsync @@ -49,9 +49,9 @@ import scala.util.{ Failure, Success, Try } override def preStart() = { val ac = getAsyncCallback[Try[Option[(S, E)]]] { - case Failure(ex) ⇒ fail(out, ex) - case Success(None) ⇒ complete(out) - case Success(Some((newS, elem))) ⇒ + case Failure(ex) => fail(out, ex) + case Success(None) => complete(out) + case Success(Some((newS, elem))) => push(out, elem) state = newS } diff --git a/akka-stream/src/main/scala/akka/stream/impl/UnfoldResourceSource.scala b/akka-stream/src/main/scala/akka/stream/impl/UnfoldResourceSource.scala index ff5cdbd261..e1551c849a 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/UnfoldResourceSource.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/UnfoldResourceSource.scala @@ -17,9 +17,9 @@ import scala.util.control.NonFatal * INTERNAL API */ @InternalApi private[akka] final class UnfoldResourceSource[T, S]( - create: () ⇒ S, - readData: (S) ⇒ Option[T], - close: (S) ⇒ Unit) extends GraphStage[SourceShape[T]] { + create: () => S, + readData: (S) => Option[T], + close: (S) => Unit) extends GraphStage[SourceShape[T]] { val out = Outlet[T]("UnfoldResourceSource.out") override val shape = SourceShape(out) override def initialAttributes: Attributes = DefaultAttributes.unfoldResourceSource @@ -40,20 +40,20 @@ import scala.util.control.NonFatal var resumingMode = false try { readData(blockingStream) match { - case Some(data) ⇒ push(out, data) - case None ⇒ closeStage() + case Some(data) => push(out, data) + case None => closeStage() } } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => decider(ex) match { - case Supervision.Stop ⇒ + case Supervision.Stop => open = false close(blockingStream) failStage(ex) - case Supervision.Restart ⇒ + case Supervision.Restart => restartState() resumingMode = true - case Supervision.Resume ⇒ + case Supervision.Resume => resumingMode = true } } @@ -75,7 +75,7 @@ import scala.util.control.NonFatal open = false completeStage() } catch { - case NonFatal(ex) ⇒ failStage(ex) + case NonFatal(ex) => failStage(ex) } override def postStop(): Unit = { diff --git a/akka-stream/src/main/scala/akka/stream/impl/UnfoldResourceSourceAsync.scala b/akka-stream/src/main/scala/akka/stream/impl/UnfoldResourceSourceAsync.scala index 00927e3d4e..94c8601503 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/UnfoldResourceSourceAsync.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/UnfoldResourceSourceAsync.scala @@ -20,9 +20,9 @@ import scala.util.control.NonFatal * INTERNAL API */ @InternalApi private[akka] final class UnfoldResourceSourceAsync[T, S]( - create: () ⇒ Future[S], - readData: (S) ⇒ Future[Option[T]], - close: (S) ⇒ Future[Done]) extends GraphStage[SourceShape[T]] { + create: () => Future[S], + readData: (S) => Future[Option[T]], + close: (S) => Future[Done]) extends GraphStage[SourceShape[T]] { val out = Outlet[T]("UnfoldResourceSourceAsync.out") override val shape = SourceShape(out) override def initialAttributes: Attributes = DefaultAttributes.unfoldResourceSourceAsync @@ -33,83 +33,83 @@ import scala.util.control.NonFatal private var state: Option[S] = None private val createdCallback = getAsyncCallback[Try[S]] { - case Success(resource) ⇒ + case Success(resource) => state = Some(resource) if (isAvailable(out)) onPull() - case Failure(t) ⇒ failStage(t) + case Failure(t) => failStage(t) }.invokeWithFeedback _ private val errorHandler: PartialFunction[Throwable, Unit] = { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) - case Supervision.Restart ⇒ restartResource() - case Supervision.Resume ⇒ onPull() + case Supervision.Restart => restartResource() + case Supervision.Resume => onPull() } } private val readCallback = getAsyncCallback[Try[Option[T]]] { - case Success(data) ⇒ data match { - case Some(d) ⇒ push(out, d) - case None ⇒ + case Success(data) => data match { + case Some(d) => push(out, d) + case None => // end of resource reached, lets close it state match { - case Some(resource) ⇒ + case Some(resource) => close(resource).onComplete(getAsyncCallback[Try[Done]] { - case Success(Done) ⇒ completeStage() - case Failure(ex) ⇒ failStage(ex) + case Success(Done) => completeStage() + case Failure(ex) => failStage(ex) }.invoke) state = None - case None ⇒ + case None => // cannot happen, but for good measure throw new IllegalStateException("Reached end of data but there is no open resource") } } - case Failure(t) ⇒ errorHandler(t) + case Failure(t) => errorHandler(t) }.invoke _ override def preStart(): Unit = createResource() override def onPull(): Unit = state match { - case Some(resource) ⇒ + case Some(resource) => try { readData(resource).onComplete(readCallback)(sameThreadExecutionContext) } catch errorHandler - case None ⇒ + case None => // we got a pull but there is no open resource, we are either // currently creating/restarting then the read will be triggered when creating the // resource completes, or shutting down and then the pull does not matter anyway } override def postStop(): Unit = { - state.foreach(r ⇒ close(r)) + state.foreach(r => close(r)) } private def restartResource(): Unit = { state match { - case Some(resource) ⇒ + case Some(resource) => // wait for the resource to close before restarting close(resource).onComplete(getAsyncCallback[Try[Done]] { - case Success(Done) ⇒ + case Success(Done) => createResource() - case Failure(ex) ⇒ failStage(ex) + case Failure(ex) => failStage(ex) }.invoke) state = None - case None ⇒ + case None => createResource() } } private def createResource(): Unit = { - create().onComplete { resource ⇒ + create().onComplete { resource => createdCallback(resource).recover { - case _: StreamDetachedException ⇒ + case _: StreamDetachedException => // stream stopped resource match { - case Success(r) ⇒ close(r) - case Failure(ex) ⇒ throw ex // failed to open but stream is stopped already + case Success(r) => close(r) + case Failure(ex) => throw ex // failed to open but stream is stopped already } } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/fusing/ActorGraphInterpreter.scala b/akka-stream/src/main/scala/akka/stream/impl/fusing/ActorGraphInterpreter.scala index 9c58777df2..557cf8b9e0 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/fusing/ActorGraphInterpreter.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/fusing/ActorGraphInterpreter.scala @@ -230,14 +230,14 @@ import scala.util.control.NonFatal complete(out) } } catch { - case s: SpecViolation ⇒ shell.tryAbort(s) + case s: SpecViolation => shell.tryAbort(s) } } override def onDownstreamFinish(): Unit = try cancel() catch { - case s: SpecViolation ⇒ shell.tryAbort(s) + case s: SpecViolation => shell.tryAbort(s) } override def toString: String = s"BatchingActorInputBoundary(forPort=$internalPortName, fill=$inputBufferElements/$size, completed=$upstreamCompleted, canceled=$downstreamCanceled)" @@ -307,8 +307,8 @@ import scala.util.control.NonFatal def shutdown(reason: Option[Throwable]): Unit = { shutdownReason = OptionVal(reason.orNull) pendingSubscribers.getAndSet(null) match { - case null ⇒ // already called earlier - case pending ⇒ pending foreach reportSubscribeFailure + case null => // already called earlier + case pending => pending foreach reportSubscribeFailure } } @@ -316,15 +316,15 @@ import scala.util.control.NonFatal private def reportSubscribeFailure(subscriber: Subscriber[Any]): Unit = try shutdownReason match { - case OptionVal.Some(_: SpecViolation) ⇒ // ok, not allowed to call onError - case OptionVal.Some(e) ⇒ + case OptionVal.Some(_: SpecViolation) => // ok, not allowed to call onError + case OptionVal.Some(e) => tryOnSubscribe(subscriber, CancelledSubscription) tryOnError(subscriber, e) - case OptionVal.None ⇒ + case OptionVal.None => tryOnSubscribe(subscriber, CancelledSubscription) tryOnComplete(subscriber) } catch { - case _: SpecViolation ⇒ // nothing to do + case _: SpecViolation => // nothing to do } override def toString: String = s"Publisher[$internalPortName]" @@ -381,24 +381,24 @@ import scala.util.control.NonFatal if (downstreamCompleted) cancel(in) else if (downstreamDemand > 0) pull(in) } catch { - case s: SpecViolation ⇒ shell.tryAbort(s) + case s: SpecViolation => shell.tryAbort(s) } } override def onUpstreamFinish(): Unit = try complete() catch { - case s: SpecViolation ⇒ shell.tryAbort(s) + case s: SpecViolation => shell.tryAbort(s) } override def onUpstreamFailure(cause: Throwable): Unit = try fail(cause) catch { - case s: SpecViolation ⇒ shell.tryAbort(s) + case s: SpecViolation => shell.tryAbort(s) } def subscribePending(): Unit = - publisher.takePendingSubscribers() foreach { sub ⇒ + publisher.takePendingSubscribers() foreach { sub => if (subscriber eq null) { subscriber = sub val subscription = new Subscription { @@ -462,7 +462,7 @@ import scala.util.control.NonFatal logic: GraphStageLogic, evt: Any, promise: Promise[Done], - handler: (Any) ⇒ Unit) extends BoundaryEvent { + handler: (Any) => Unit) extends BoundaryEvent { override def execute(eventLimit: Int): Int = { if (!waitingForShutdown) { interpreter.runAsyncInput(logic, evt, promise, handler) @@ -495,10 +495,10 @@ import scala.util.control.NonFatal } } - private var enqueueToShortCircuit: (Any) ⇒ Unit = _ + private var enqueueToShortCircuit: (Any) => Unit = _ lazy val interpreter: GraphInterpreter = new GraphInterpreter(mat, log, logics, connections, - (logic, event, promise, handler) ⇒ { + (logic, event, promise, handler) => { val asyncInput = AsyncInput(this, logic, event, promise, handler) val currentInterpreter = GraphInterpreter.currentInterpreterOrNull if (currentInterpreter == null || (currentInterpreter.context ne self)) @@ -533,21 +533,21 @@ import scala.util.control.NonFatal private var resumeScheduled = false def isInitialized: Boolean = self != null - def init(self: ActorRef, subMat: SubFusingActorMaterializerImpl, enqueueToShortCircuit: (Any) ⇒ Unit, eventLimit: Int): Int = { + def init(self: ActorRef, subMat: SubFusingActorMaterializerImpl, enqueueToShortCircuit: (Any) => Unit, eventLimit: Int): Int = { this.self = self this.enqueueToShortCircuit = enqueueToShortCircuit var i = 0 while (i < logics.length) { logics(i) match { - case in: BatchingActorInputBoundary ⇒ + case in: BatchingActorInputBoundary => in.setActor(self) subscribesPending += 1 inputs ::= in - case out: ActorOutputBoundary ⇒ + case out: ActorOutputBoundary => out.setActor(self) out.subscribePending() outputs ::= out - case _ ⇒ + case _ => } i += 1 } @@ -597,7 +597,7 @@ import scala.util.control.NonFatal if (usingShellLimit) actorEventLimit - shellEventLimit + remainingQuota else remainingQuota } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => tryAbort(e) actorEventLimit - 1 } @@ -611,9 +611,9 @@ import scala.util.control.NonFatal */ def tryAbort(ex: Throwable): Unit = { val reason = ex match { - case s: SpecViolation ⇒ + case s: SpecViolation => new IllegalStateException("Shutting down because of violation of the Reactive Streams specification.", s) - case _ ⇒ ex + case _ => ex } // This should handle termination while interpreter is running. If the upstream have been closed already this @@ -623,7 +623,7 @@ import scala.util.control.NonFatal interpreter.execute(abortLimit) interpreter.finish() } catch { - case NonFatal(_) ⇒ + case NonFatal(_) => // We are already handling an abort caused by an error, there is nothing we can do with new errors caused // by the abort itself. We just give up here. } finally { @@ -639,7 +639,7 @@ import scala.util.control.NonFatal if (!isInitialized) UninitializedInterpreterImpl( logics.zipWithIndex.map { - case (logic, idx) ⇒ + case (logic, idx) => LogicSnapshotImpl(idx, logic.originalStage.getOrElse(logic).toString, logic.attributes) }.toVector ) @@ -667,7 +667,7 @@ import scala.util.control.NonFatal true } } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "initialization of GraphInterpreterShell failed for {}", shell) false } @@ -695,8 +695,8 @@ import scala.util.control.NonFatal */ @tailrec private def finishShellRegistration(): Unit = newShells match { - case Nil ⇒ if (activeInterpreters.isEmpty) context.stop(self) - case shell :: tail ⇒ + case Nil => if (activeInterpreters.isEmpty) context.stop(self) + case shell :: tail => newShells = tail if (shell.isInitialized) { // yes, this steals another shell’s Resume, but that’s okay because extra ones will just not do anything @@ -715,8 +715,8 @@ import scala.util.control.NonFatal private def shortCircuitBatch(): Unit = { while (!shortCircuitBuffer.isEmpty && currentLimit > 0 && activeInterpreters.nonEmpty) shortCircuitBuffer.poll() match { - case b: BoundaryEvent ⇒ processEvent(b) - case Resume ⇒ finishShellRegistration() + case b: BoundaryEvent => processEvent(b) + case Resume => finishShellRegistration() } if (!shortCircuitBuffer.isEmpty && currentLimit == 0) self ! Resume } @@ -727,7 +727,7 @@ import scala.util.control.NonFatal if (!shell.isTerminated && (shell.isInitialized || tryInit(shell))) { try currentLimit = shell.processEvent(b, currentLimit) catch { - case NonFatal(e) ⇒ shell.tryAbort(e) + case NonFatal(e) => shell.tryAbort(e) } if (shell.isTerminated) { @@ -738,20 +738,20 @@ import scala.util.control.NonFatal } override def receive: Receive = { - case b: BoundaryEvent ⇒ + case b: BoundaryEvent => currentLimit = eventLimit processEvent(b) if (shortCircuitBuffer != null) shortCircuitBatch() - case Resume ⇒ + case Resume => currentLimit = eventLimit if (shortCircuitBuffer != null) shortCircuitBatch() - case Snapshot ⇒ + case Snapshot => sender() ! StreamSnapshotImpl( self.path, - activeInterpreters.map(shell ⇒ shell.toSnapshot.asInstanceOf[RunningInterpreter]).toSeq, - newShells.map(shell ⇒ shell.toSnapshot.asInstanceOf[UninitializedInterpreter]) + activeInterpreters.map(shell => shell.toSnapshot.asInstanceOf[RunningInterpreter]).toSeq, + newShells.map(shell => shell.toSnapshot.asInstanceOf[UninitializedInterpreter]) ) } @@ -759,6 +759,6 @@ import scala.util.control.NonFatal val ex = AbruptTerminationException(self) activeInterpreters.foreach(_.tryAbort(ex)) activeInterpreters = Set.empty[GraphInterpreterShell] - newShells.foreach(s ⇒ if (tryInit(s)) s.tryAbort(ex)) + newShells.foreach(s => if (tryInit(s)) s.tryAbort(ex)) } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/fusing/GraphInterpreter.scala b/akka-stream/src/main/scala/akka/stream/impl/fusing/GraphInterpreter.scala index 23615fe42a..6abef26342 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/fusing/GraphInterpreter.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/fusing/GraphInterpreter.scala @@ -192,7 +192,7 @@ import akka.stream.snapshot._ val log: LoggingAdapter, val logics: Array[GraphStageLogic], // Array of stage logics val connections: Array[GraphInterpreter.Connection], - val onAsyncInput: (GraphStageLogic, Any, Promise[Done], (Any) ⇒ Unit) ⇒ Unit, + val onAsyncInput: (GraphStageLogic, Any, Promise[Done], (Any) => Unit) => Unit, val fuzzingMode: Boolean, val context: ActorRef) { @@ -210,7 +210,7 @@ import akka.stream.snapshot._ private[this] var runningStages = logics.length // Counts how many active connections a stage has. Once it reaches zero, the stage is automatically stopped. - private[this] val shutdownCounter = Array.tabulate(logics.length) { i ⇒ + private[this] val shutdownCounter = Array.tabulate(logics.length) { i => logics(i).handlers.length } @@ -229,7 +229,7 @@ import akka.stream.snapshot._ private[this] var chasedPull: Connection = NoEvent private def queueStatus: String = { - val contents = (queueHead until queueTail).map(idx ⇒ { + val contents = (queueHead until queueTail).map(idx => { val conn = eventQueue(idx & mask) conn }) @@ -290,7 +290,7 @@ import akka.stream.snapshot._ logic.beforePreStart() logic.preStart() } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "Error during preStart in [{}]: {}", logic.originalStage.getOrElse(logic), e.getMessage) logic.failStage(e) } @@ -324,7 +324,7 @@ import akka.stream.snapshot._ private def outLogicName(connection: Connection): String = logics(connection.outOwner.stageId).toString private def shutdownCounters: String = - shutdownCounter.map(x ⇒ if (x >= KeepGoingFlag) s"${x & KeepGoingMask}(KeepGoing)" else x.toString).mkString(",") + shutdownCounter.map(x => if (x >= KeepGoingFlag) s"${x & KeepGoingMask}(KeepGoing)" else x.toString).mkString(",") /** * Executes pending events until the given limit is met. If there were remaining events, isSuspended will return @@ -346,8 +346,8 @@ import akka.stream.snapshot._ if (activeStage == null) throw e else { val loggingEnabled = activeStage.attributes.get[LogLevels] match { - case Some(levels) ⇒ levels.onFailure != LogLevels.Off - case None ⇒ true + case Some(levels) => levels.onFailure != LogLevels.Off + case None => true } if (loggingEnabled) log.error(e, "Error in stage [{}]: {}", activeStage.originalStage.getOrElse(activeStage), e.getMessage) @@ -373,7 +373,7 @@ import akka.stream.snapshot._ */ try processEvent(connection) catch { - case NonFatal(e) ⇒ reportStageError(e) + case NonFatal(e) => reportStageError(e) } afterStageHasRun(activeStage) @@ -406,7 +406,7 @@ import akka.stream.snapshot._ chasedPush = NoEvent try processPush(connection) catch { - case NonFatal(e) ⇒ reportStageError(e) + case NonFatal(e) => reportStageError(e) } afterStageHasRun(activeStage) } @@ -417,7 +417,7 @@ import akka.stream.snapshot._ chasedPull = NoEvent try processPull(connection) catch { - case NonFatal(e) ⇒ reportStageError(e) + case NonFatal(e) => reportStageError(e) } afterStageHasRun(activeStage) } @@ -438,7 +438,7 @@ import akka.stream.snapshot._ eventsRemaining } - def runAsyncInput(logic: GraphStageLogic, evt: Any, promise: Promise[Done], handler: (Any) ⇒ Unit): Unit = + def runAsyncInput(logic: GraphStageLogic, evt: Any, promise: Promise[Done], handler: (Any) => Unit): Unit = if (!isStageCompleted(logic)) { if (GraphInterpreter.Debug) println(s"$Name ASYNC $evt ($handler) [$logic]") val currentInterpreterHolder = _currentInterpreter.get() @@ -453,7 +453,7 @@ import akka.stream.snapshot._ logic.onFeedbackDispatched() } } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => if (promise ne GraphStageLogic.NoPromise) { promise.failure(ex) logic.onFeedbackDispatched() @@ -567,7 +567,7 @@ import akka.stream.snapshot._ logic.postStop() logic.afterPostStop() } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, s"Error during postStop in [{}]: {}", logic.originalStage.getOrElse(logic), e.getMessage) } } @@ -645,21 +645,21 @@ import akka.stream.snapshot._ def toSnapshot: RunningInterpreter = { val logicSnapshots = logics.zipWithIndex.map { - case (logic, idx) ⇒ + case (logic, idx) => val label = logic.originalStage.getOrElse(logic).toString LogicSnapshotImpl(idx, label, logic.attributes) } - val logicIndexes = logics.zipWithIndex.map { case (stage, idx) ⇒ stage → idx }.toMap + val logicIndexes = logics.zipWithIndex.map { case (stage, idx) => stage -> idx }.toMap val connectionSnapshots = connections.filter(_ != null) - .map { connection ⇒ + .map { connection => ConnectionSnapshotImpl( connection.id, logicSnapshots(logicIndexes(connection.inOwner)), logicSnapshots(logicIndexes(connection.outOwner)), connection.portState match { - case InReady ⇒ ConnectionSnapshot.ShouldPull - case OutReady ⇒ ConnectionSnapshot.ShouldPush - case x if (x | InClosed | OutClosed) == (InClosed | OutClosed) ⇒ ConnectionSnapshot.Closed + case InReady => ConnectionSnapshot.ShouldPull + case OutReady => ConnectionSnapshot.ShouldPush + case x if (x | InClosed | OutClosed) == (InClosed | OutClosed) => ConnectionSnapshot.Closed } ) } @@ -669,7 +669,7 @@ import akka.stream.snapshot._ connectionSnapshots.toVector, queueStatus, runningStages, - shutdownCounter.toList.map(n ⇒ logicSnapshots(n))) + shutdownCounter.toList.map(n => logicSnapshots(n))) } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/fusing/GraphStages.scala b/akka-stream/src/main/scala/akka/stream/impl/fusing/GraphStages.scala index cd7655e691..b749dfcdcf 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/fusing/GraphStages.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/fusing/GraphStages.scala @@ -155,8 +155,8 @@ import scala.concurrent.{ Future, Promise } private class FlowMonitorImpl[T] extends AtomicReference[Any](Initialized) with FlowMonitor[T] { override def state = get match { - case s: StreamState[_] ⇒ s.asInstanceOf[StreamState[T]] - case msg ⇒ Received(msg.asInstanceOf[T]) + case s: StreamState[_] => s.asInstanceOf[StreamState[T]] + case msg => Received(msg.asInstanceOf[T]) } } @@ -195,8 +195,8 @@ import scala.concurrent.{ Future, Promise } override def postStop(): Unit = { monitor.state match { - case Finished | _: Failed ⇒ - case _ ⇒ monitor.set(Failed(new AbruptStageTerminationException(this))) + case Finished | _: Failed => + case _ => monitor.set(Failed(new AbruptStageTerminationException(this))) } } @@ -227,7 +227,7 @@ import scala.concurrent.{ Future, Promise } val cancelCallback: AtomicReference[Option[AsyncCallback[Unit]]] = new AtomicReference(None) override def preStart() = { - cancelCallback.set(Some(getAsyncCallback[Unit](_ ⇒ completeStage()))) + cancelCallback.set(Some(getAsyncCallback[Unit](_ => completeStage()))) if (cancelled.get) completeStage() else @@ -291,10 +291,10 @@ import scala.concurrent.{ Future, Promise } override def preStart(): Unit = futureSource.value match { - case Some(it) ⇒ + case Some(it) => // this optimisation avoids going through any execution context, in similar vein to FastFuture onFutureSourceCompleted(it) - case _ ⇒ + case _ => val cb = getAsyncCallback[Try[Graph[SourceShape[T], M]]](onFutureSourceCompleted).invoke _ futureSource.onComplete(cb)(ExecutionContexts.sameThreadExecutionContext) // could be optimised FastFuture-like } @@ -329,7 +329,7 @@ import scala.concurrent.{ Future, Promise } if (!sinkIn.isClosed) sinkIn.cancel() def onFutureSourceCompleted(result: Try[Graph[SourceShape[T], M]]): Unit = { - result.map { graph ⇒ + result.map { graph => val runnable = Source.fromGraph(graph).toMat(sinkIn.sink)(Keep.left) val matVal = interpreter.subFusingMaterializer.materialize(runnable, defaultAttributes = attr) materialized.success(matVal) @@ -342,7 +342,7 @@ import scala.concurrent.{ Future, Promise } } }.recover { - case t ⇒ + case t => sinkIn.cancel() materialized.failure(t) failStage(t) @@ -373,8 +373,8 @@ import scala.concurrent.{ Future, Promise } def onFutureCompleted(result: Try[T]): Unit = { result match { - case scala.util.Success(v) ⇒ emit(out, v, () ⇒ completeStage()) - case scala.util.Failure(t) ⇒ failStage(t) + case scala.util.Success(v) => emit(out, v, () => completeStage()) + case scala.util.Failure(t) => failStage(t) } } @@ -438,10 +438,10 @@ import scala.concurrent.{ Future, Promise } * which adds a detacher operator to every input. */ @InternalApi private[stream] def withDetachedInputs[T](stage: GraphStage[UniformFanInShape[T, T]]) = - GraphDSL.create() { implicit builder ⇒ + GraphDSL.create() { implicit builder => import GraphDSL.Implicits._ val concat = builder.add(stage) - val ds = concat.inlets.map { inlet ⇒ + val ds = concat.inlets.map { inlet => val detacher = builder.add(GraphStages.detacher[T]) detacher ~> inlet detacher.in diff --git a/akka-stream/src/main/scala/akka/stream/impl/fusing/Ops.scala b/akka-stream/src/main/scala/akka/stream/impl/fusing/Ops.scala index 8a96fb3a12..2168bd10cd 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/fusing/Ops.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/fusing/Ops.scala @@ -14,7 +14,7 @@ import akka.event.{ LogSource, Logging, LoggingAdapter } import akka.stream.Attributes.{ InputBuffer, LogLevels } import akka.stream.OverflowStrategies._ import akka.stream.impl.fusing.GraphStages.SimpleLinearGraphStage -import akka.stream.impl.{ ReactiveStreamsCompliance, Buffer ⇒ BufferImpl } +import akka.stream.impl.{ ReactiveStreamsCompliance, Buffer => BufferImpl } import akka.stream.scaladsl.{ Flow, Keep, Source } import akka.stream.stage._ import akka.stream.{ Supervision, _ } @@ -35,7 +35,7 @@ import akka.util.OptionVal /** * INTERNAL API */ -@InternalApi private[akka] final case class Map[In, Out](f: In ⇒ Out) extends GraphStage[FlowShape[In, Out]] { +@InternalApi private[akka] final case class Map[In, Out](f: In => Out) extends GraphStage[FlowShape[In, Out]] { val in = Inlet[In]("Map.in") val out = Outlet[Out]("Map.out") override val shape = FlowShape(in, out) @@ -51,9 +51,9 @@ import akka.util.OptionVal try { push(out, f(grab(in))) } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case _ ⇒ pull(in) + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case _ => pull(in) } } } @@ -67,7 +67,7 @@ import akka.util.OptionVal /** * INTERNAL API */ -@InternalApi private[akka] final case class Filter[T](p: T ⇒ Boolean) extends SimpleLinearGraphStage[T] { +@InternalApi private[akka] final case class Filter[T](p: T => Boolean) extends SimpleLinearGraphStage[T] { override def initialAttributes: Attributes = DefaultAttributes.filter override def toString: String = "Filter" @@ -85,9 +85,9 @@ import akka.util.OptionVal pull(in) } } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case _ ⇒ pull(in) + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case _ => pull(in) } } } @@ -101,7 +101,7 @@ import akka.util.OptionVal /** * INTERNAL API */ -@InternalApi private[akka] final case class TakeWhile[T](p: T ⇒ Boolean, inclusive: Boolean = false) extends SimpleLinearGraphStage[T] { +@InternalApi private[akka] final case class TakeWhile[T](p: T => Boolean, inclusive: Boolean = false) extends SimpleLinearGraphStage[T] { override def initialAttributes: Attributes = DefaultAttributes.takeWhile override def toString: String = "TakeWhile" @@ -122,9 +122,9 @@ import akka.util.OptionVal completeStage() } } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case _ ⇒ pull(in) + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case _ => pull(in) } } } @@ -138,18 +138,18 @@ import akka.util.OptionVal /** * INTERNAL API */ -@InternalApi private[akka] final case class DropWhile[T](p: T ⇒ Boolean) extends SimpleLinearGraphStage[T] { +@InternalApi private[akka] final case class DropWhile[T](p: T => Boolean) extends SimpleLinearGraphStage[T] { override def initialAttributes: Attributes = DefaultAttributes.dropWhile def createLogic(inheritedAttributes: Attributes) = new SupervisedGraphStageLogic(inheritedAttributes, shape) with InHandler with OutHandler { override def onPush(): Unit = { val elem = grab(in) - withSupervision(() ⇒ p(elem)) match { - case Some(flag) if flag ⇒ pull(in) - case Some(flag) if !flag ⇒ + withSupervision(() => p(elem)) match { + case Some(flag) if flag => pull(in) + case Some(flag) if !flag => push(out, elem) setHandler(in, rest) - case None ⇒ // do nothing + case None => // do nothing } } @@ -173,15 +173,15 @@ import akka.util.OptionVal @DoNotInherit private[akka] abstract class SupervisedGraphStageLogic(inheritedAttributes: Attributes, shape: Shape) extends GraphStageLogic(shape) { private lazy val decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider - def withSupervision[T](f: () ⇒ T): Option[T] = + def withSupervision[T](f: () => T): Option[T] = try { Some(f()) } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => decider(ex) match { - case Supervision.Stop ⇒ onStop(ex) - case Supervision.Resume ⇒ onResume(ex) - case Supervision.Restart ⇒ onRestart(ex) + case Supervision.Stop => onStop(ex) + case Supervision.Resume => onResume(ex) + case Supervision.Restart => onRestart(ex) } None } @@ -197,7 +197,7 @@ private[stream] object Collect { // Cached function that can be used with PartialFunction.applyOrElse to ensure that A) the guard is only applied once, // and the caller can check the returned value with Collect.notApplied to query whether the PF was applied or not. // Prior art: https://github.com/scala/scala/blob/v2.11.4/src/library/scala/collection/immutable/List.scala#L458 - final val NotApplied: Any ⇒ Any = _ ⇒ Collect.NotApplied + final val NotApplied: Any => Any = _ => Collect.NotApplied } /** @@ -214,14 +214,14 @@ private[stream] object Collect { import Collect.NotApplied - val wrappedPf = () ⇒ pf.applyOrElse(grab(in), NotApplied) + val wrappedPf = () => pf.applyOrElse(grab(in), NotApplied) override def onPush(): Unit = withSupervision(wrappedPf) match { - case Some(result) ⇒ result match { - case NotApplied ⇒ pull(in) - case result: Out @unchecked ⇒ push(out, result) + case Some(result) => result match { + case NotApplied => pull(in) + case result: Out @unchecked => push(out, result) } - case None ⇒ //do nothing + case None => //do nothing } override def onResume(t: Throwable): Unit = if (!hasBeenPulled(in)) pull(in) @@ -252,18 +252,18 @@ private[stream] object Collect { override def onPull(): Unit = { recovered match { - case Some(elem) ⇒ + case Some(elem) => push(out, elem) completeStage() - case None ⇒ + case None => pull(in) } } override def onUpstreamFailure(ex: Throwable): Unit = { pf.applyOrElse(ex, NotApplied) match { - case NotApplied ⇒ failStage(ex) - case result: T @unchecked ⇒ { + case NotApplied => failStage(ex) + case result: T @unchecked => { if (isAvailable(out)) { push(out, result) completeStage() @@ -355,7 +355,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final case class Scan[In, Out](zero: Out, f: (Out, In) ⇒ Out) extends GraphStage[FlowShape[In, Out]] { +@InternalApi private[akka] final case class Scan[In, Out](zero: Out, f: (Out, In) => Out) extends GraphStage[FlowShape[In, Out]] { override val shape = FlowShape[In, Out](Inlet("Scan.in"), Outlet("Scan.out")) override def initialAttributes: Attributes = DefaultAttributes.scan @@ -363,7 +363,7 @@ private[stream] object Collect { override def toString: String = "Scan" override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = - new GraphStageLogic(shape) with InHandler with OutHandler { self ⇒ + new GraphStageLogic(shape) with InHandler with OutHandler { self => private var aggregator = zero private lazy val decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider @@ -397,10 +397,10 @@ private[stream] object Collect { aggregator = f(aggregator, grab(in)) push(out, aggregator) } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Resume ⇒ if (!hasBeenPulled(in)) pull(in) - case Stop ⇒ failStage(ex) - case Restart ⇒ + case NonFatal(ex) => decider(ex) match { + case Resume => if (!hasBeenPulled(in)) pull(in) + case Stop => failStage(ex) + case Restart => aggregator = zero push(out, aggregator) } @@ -412,7 +412,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final case class ScanAsync[In, Out](zero: Out, f: (Out, In) ⇒ Future[Out]) extends GraphStage[FlowShape[In, Out]] { +@InternalApi private[akka] final case class ScanAsync[In, Out](zero: Out, f: (Out, In) => Future[Out]) extends GraphStage[FlowShape[In, Out]] { import akka.dispatch.ExecutionContexts @@ -425,7 +425,7 @@ private[stream] object Collect { override val toString: String = "ScanAsync" override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = - new GraphStageLogic(shape) with InHandler with OutHandler { self ⇒ + new GraphStageLogic(shape) with InHandler with OutHandler { self => private var current: Out = zero private var elementHandled: Boolean = false @@ -474,9 +474,9 @@ private[stream] object Collect { private def doSupervision(t: Throwable): Unit = { decider(t) match { - case Supervision.Stop ⇒ failStage(t) - case Supervision.Resume ⇒ safePull() - case Supervision.Restart ⇒ + case Supervision.Stop => failStage(t) + case Supervision.Resume => safePull() + case Supervision.Restart => onRestart(t) safePull() } @@ -484,12 +484,12 @@ private[stream] object Collect { } private val futureCB = getAsyncCallback[Try[Out]] { - case Success(next) if next != null ⇒ + case Success(next) if next != null => current = next pushAndPullOrFinish(next) elementHandled = true - case Success(null) ⇒ doSupervision(ReactiveStreamsCompliance.elementMustNotBeNullException) - case Failure(t) ⇒ doSupervision(t) + case Success(null) => doSupervision(ReactiveStreamsCompliance.elementMustNotBeNullException) + case Failure(t) => doSupervision(t) }.invoke _ setHandlers(in, out, ZeroHandler) @@ -503,15 +503,15 @@ private[stream] object Collect { val eventualCurrent = f(current, grab(in)) eventualCurrent.value match { - case Some(result) ⇒ futureCB(result) - case _ ⇒ eventualCurrent.onComplete(futureCB)(ec) + case Some(result) => futureCB(result) + case _ => eventualCurrent.onComplete(futureCB)(ec) } } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case Supervision.Restart ⇒ onRestart(ex) - case Supervision.Resume ⇒ () + case Supervision.Stop => failStage(ex) + case Supervision.Restart => onRestart(ex) + case Supervision.Resume => () } tryPull(in) elementHandled = true @@ -531,7 +531,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final case class Fold[In, Out](zero: Out, f: (Out, In) ⇒ Out) extends GraphStage[FlowShape[In, Out]] { +@InternalApi private[akka] final case class Fold[In, Out](zero: Out, f: (Out, In) => Out) extends GraphStage[FlowShape[In, Out]] { val in = Inlet[In]("Fold.in") val out = Outlet[Out]("Fold.out") @@ -553,10 +553,10 @@ private[stream] object Collect { try { aggregator = f(aggregator, elem) } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case Supervision.Restart ⇒ aggregator = zero - case _ ⇒ () + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case Supervision.Restart => aggregator = zero + case _ => () } } finally { if (!isClosed(in)) pull(in) @@ -586,7 +586,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final class FoldAsync[In, Out](zero: Out, f: (Out, In) ⇒ Future[Out]) extends GraphStage[FlowShape[In, Out]] { +@InternalApi private[akka] final class FoldAsync[In, Out](zero: Out, f: (Out, In) => Future[Out]) extends GraphStage[FlowShape[In, Out]] { import akka.dispatch.ExecutionContexts @@ -612,7 +612,7 @@ private[stream] object Collect { private def ec = ExecutionContexts.sameThreadExecutionContext private val futureCB = getAsyncCallback[Try[Out]] { - case Success(update) if update != null ⇒ + case Success(update) if update != null => aggregator = update if (isClosed(in)) { @@ -620,10 +620,10 @@ private[stream] object Collect { completeStage() } else if (isAvailable(out) && !hasBeenPulled(in)) tryPull(in) - case other ⇒ + case other => val ex = other match { - case Failure(t) ⇒ t - case Success(s) if s == null ⇒ + case Failure(t) => t + case Success(s) if s == null => ReactiveStreamsCompliance.elementMustNotBeNullException } val supervision = decider(ex) @@ -644,12 +644,12 @@ private[stream] object Collect { aggregating = f(aggregator, grab(in)) handleAggregatingValue() } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case supervision ⇒ { + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case supervision => { supervision match { - case Supervision.Restart ⇒ onRestart(ex) - case _ ⇒ () // just ignore on Resume + case Supervision.Restart => onRestart(ex) + case _ => () // just ignore on Resume } tryPull(in) @@ -666,8 +666,8 @@ private[stream] object Collect { private def handleAggregatingValue(): Unit = { aggregating.value match { - case Some(result) ⇒ futureCB(result) // already completed - case _ ⇒ aggregating.onComplete(futureCB)(ec) + case Some(result) => futureCB(result) // already completed + case _ => aggregating.onComplete(futureCB)(ec) } } @@ -774,7 +774,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final case class LimitWeighted[T](val n: Long, val costFn: T ⇒ Long) extends SimpleLinearGraphStage[T] { +@InternalApi private[akka] final case class LimitWeighted[T](val n: Long, val costFn: T => Long) extends SimpleLinearGraphStage[T] { override def initialAttributes: Attributes = DefaultAttributes.limitWeighted def createLogic(inheritedAttributes: Attributes) = new SupervisedGraphStageLogic(inheritedAttributes, shape) with InHandler with OutHandler { @@ -782,11 +782,11 @@ private[stream] object Collect { override def onPush(): Unit = { val elem = grab(in) - withSupervision(() ⇒ costFn(elem)) match { - case Some(weight) ⇒ + withSupervision(() => costFn(elem)) match { + case Some(weight) => left -= weight if (left >= 0) push(out, elem) else failStage(new StreamLimitReachedException(n)) - case None ⇒ //do nothing + case None => //do nothing } } @@ -873,38 +873,38 @@ private[stream] object Collect { private var buffer: BufferImpl[T] = _ - val enqueueAction: T ⇒ Unit = + val enqueueAction: T => Unit = overflowStrategy match { - case s: DropHead ⇒ elem ⇒ + case s: DropHead => elem => if (buffer.isFull) { log.log(s.logLevel, "Dropping the head element because buffer is full and overflowStrategy is: [DropHead]") buffer.dropHead() } buffer.enqueue(elem) pull(in) - case s: DropTail ⇒ elem ⇒ + case s: DropTail => elem => if (buffer.isFull) { log.log(s.logLevel, "Dropping the tail element because buffer is full and overflowStrategy is: [DropTail]") buffer.dropTail() } buffer.enqueue(elem) pull(in) - case s: DropBuffer ⇒ elem ⇒ + case s: DropBuffer => elem => if (buffer.isFull) { log.log(s.logLevel, "Dropping all the buffered elements because buffer is full and overflowStrategy is: [DropBuffer]") buffer.clear() } buffer.enqueue(elem) pull(in) - case s: DropNew ⇒ elem ⇒ + case s: DropNew => elem => if (!buffer.isFull) buffer.enqueue(elem) else log.log(s.logLevel, "Dropping the new element because buffer is full and overflowStrategy is: [DropNew]") pull(in) - case s: Backpressure ⇒ elem ⇒ + case s: Backpressure => elem => buffer.enqueue(elem) if (!buffer.isFull) pull(in) else log.log(s.logLevel, "Backpressuring because buffer is full and overflowStrategy is: [Backpressure]") - case s: Fail ⇒ elem ⇒ + case s: Fail => elem => if (buffer.isFull) { log.log(s.logLevel, "Failing because buffer is full and overflowStrategy is: [Fail]") failStage(BufferOverflowException(s"Buffer overflow (max capacity was: $size)!")) @@ -953,7 +953,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final case class Batch[In, Out](val max: Long, val costFn: In ⇒ Long, val seed: In ⇒ Out, val aggregate: (Out, In) ⇒ Out) +@InternalApi private[akka] final case class Batch[In, Out](val max: Long, val costFn: In => Long, val seed: In => Out, val aggregate: (Out, In) => Out) extends GraphStage[FlowShape[In, Out]] { val in = Inlet[In]("Batch.in") @@ -980,10 +980,10 @@ private[stream] object Collect { left -= costFn(pending) pending = null.asInstanceOf[In] } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case Supervision.Restart ⇒ restartState() - case Supervision.Resume ⇒ + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case Supervision.Restart => restartState() + case Supervision.Resume => pending = null.asInstanceOf[In] } } @@ -1003,11 +1003,11 @@ private[stream] object Collect { agg = seed(elem) left -= cost } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case Supervision.Restart ⇒ + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case Supervision.Restart => restartState() - case Supervision.Resume ⇒ + case Supervision.Resume => } } } else if (left < cost) { @@ -1017,11 +1017,11 @@ private[stream] object Collect { agg = aggregate(agg, elem) left -= cost } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case Supervision.Restart ⇒ + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case Supervision.Restart => restartState() - case Supervision.Resume ⇒ + case Supervision.Resume => } } } @@ -1045,10 +1045,10 @@ private[stream] object Collect { try { agg = seed(pending) } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case Supervision.Resume ⇒ - case Supervision.Restart ⇒ + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case Supervision.Resume => + case Supervision.Restart => restartState() if (!hasBeenPulled(in)) pull(in) } @@ -1075,7 +1075,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final class Expand[In, Out](val extrapolate: In ⇒ Iterator[Out]) extends GraphStage[FlowShape[In, Out]] { +@InternalApi private[akka] final class Expand[In, Out](val extrapolate: In => Iterator[Out]) extends GraphStage[FlowShape[In, Out]] { private val in = Inlet[In]("expand.in") private val out = Outlet[Out]("expand.out") @@ -1134,7 +1134,7 @@ private[stream] object Collect { final class Holder[T]( var elem: Try[T], val cb: AsyncCallback[Holder[T]] - ) extends (Try[T] ⇒ Unit) { + ) extends (Try[T] => Unit) { // To support both fail-fast when the supervision directive is Stop // and not calling the decider multiple times (#23888) we need to cache the decider result and re-use that @@ -1142,8 +1142,8 @@ private[stream] object Collect { def supervisionDirectiveFor(decider: Supervision.Decider, ex: Throwable): Supervision.Directive = { cachedSupervisionDirective match { - case OptionVal.Some(d) ⇒ d - case OptionVal.None ⇒ + case OptionVal.Some(d) => d + case OptionVal.None => val d = decider(ex) cachedSupervisionDirective = OptionVal.Some(d) d @@ -1152,8 +1152,8 @@ private[stream] object Collect { def setElem(t: Try[T]): Unit = { elem = t match { - case Success(null) ⇒ Failure[T](ReactiveStreamsCompliance.elementMustNotBeNullException) - case other ⇒ other + case Success(null) => Failure[T](ReactiveStreamsCompliance.elementMustNotBeNullException) + case other => other } } @@ -1169,7 +1169,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final case class MapAsync[In, Out](parallelism: Int, f: In ⇒ Future[Out]) +@InternalApi private[akka] final case class MapAsync[In, Out](parallelism: Int, f: In => Future[Out]) extends GraphStage[FlowShape[In, Out]] { import MapAsync._ @@ -1187,14 +1187,14 @@ private[stream] object Collect { lazy val decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider var buffer: BufferImpl[Holder[Out]] = _ - private val futureCB = getAsyncCallback[Holder[Out]](holder ⇒ + private val futureCB = getAsyncCallback[Holder[Out]](holder => holder.elem match { - case Success(_) ⇒ pushNextIfPossible() - case Failure(ex) ⇒ + case Success(_) => pushNextIfPossible() + case Failure(ex) => holder.supervisionDirectiveFor(decider, ex) match { // fail fast as if supervision says so - case Supervision.Stop ⇒ failStage(ex) - case _ ⇒ pushNextIfPossible() + case Supervision.Stop => failStage(ex) + case _ => pushNextIfPossible() } }) @@ -1209,21 +1209,21 @@ private[stream] object Collect { buffer.enqueue(holder) future.value match { - case None ⇒ future.onComplete(holder)(akka.dispatch.ExecutionContexts.sameThreadExecutionContext) - case Some(v) ⇒ + case None => future.onComplete(holder)(akka.dispatch.ExecutionContexts.sameThreadExecutionContext) + case Some(v) => // #20217 the future is already here, optimization: avoid scheduling it on the dispatcher and // run the logic directly on this thread holder.setElem(v) v match { // this optimization also requires us to stop the stage to fail fast if the decider says so: - case Failure(ex) if holder.supervisionDirectiveFor(decider, ex) == Supervision.Stop ⇒ failStage(ex) - case _ ⇒ pushNextIfPossible() + case Failure(ex) if holder.supervisionDirectiveFor(decider, ex) == Supervision.Stop => failStage(ex) + case _ => pushNextIfPossible() } } } catch { // this logic must only be executed if f throws, not if the future is failed - case NonFatal(ex) ⇒ if (decider(ex) == Supervision.Stop) failStage(ex) + case NonFatal(ex) => if (decider(ex) == Supervision.Stop) failStage(ex) } pullIfNeeded() @@ -1240,16 +1240,16 @@ private[stream] object Collect { else if (isAvailable(out)) { val holder = buffer.dequeue() holder.elem match { - case Success(elem) ⇒ + case Success(elem) => push(out, elem) pullIfNeeded() - case Failure(NonFatal(ex)) ⇒ + case Failure(NonFatal(ex)) => holder.supervisionDirectiveFor(decider, ex) match { // this could happen if we are looping in pushNextIfPossible and end up on a failed future before the // onComplete callback has run - case Supervision.Stop ⇒ failStage(ex) - case _ ⇒ + case Supervision.Stop => failStage(ex) + case _ => // try next element pushNextIfPossible() } @@ -1267,7 +1267,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final case class MapAsyncUnordered[In, Out](parallelism: Int, f: In ⇒ Future[Out]) +@InternalApi private[akka] final case class MapAsyncUnordered[In, Out](parallelism: Int, f: In => Future[Out]) extends GraphStage[FlowShape[In, Out]] { private val in = Inlet[In]("MapAsyncUnordered.in") @@ -1294,15 +1294,15 @@ private[stream] object Collect { def futureCompleted(result: Try[Out]): Unit = { inFlight -= 1 result match { - case Success(elem) if elem != null ⇒ + case Success(elem) if elem != null => if (isAvailable(out)) { if (!hasBeenPulled(in)) tryPull(in) push(out, elem) } else buffer.enqueue(elem) - case other ⇒ + case other => val ex = other match { - case Failure(t) ⇒ t - case Success(s) if s == null ⇒ ReactiveStreamsCompliance.elementMustNotBeNullException + case Failure(t) => t + case Success(s) if s == null => ReactiveStreamsCompliance.elementMustNotBeNullException } if (decider(ex) == Supervision.Stop) failStage(ex) else if (isClosed(in) && todo == 0) completeStage() @@ -1311,18 +1311,18 @@ private[stream] object Collect { } private val futureCB = getAsyncCallback(futureCompleted) - private val invokeFutureCB: Try[Out] ⇒ Unit = futureCB.invoke + private val invokeFutureCB: Try[Out] => Unit = futureCB.invoke override def onPush(): Unit = { try { val future = f(grab(in)) inFlight += 1 future.value match { - case None ⇒ future.onComplete(invokeFutureCB)(akka.dispatch.ExecutionContexts.sameThreadExecutionContext) - case Some(v) ⇒ futureCompleted(v) + case None => future.onComplete(invokeFutureCB)(akka.dispatch.ExecutionContexts.sameThreadExecutionContext) + case Some(v) => futureCompleted(v) } } catch { - case NonFatal(ex) ⇒ if (decider(ex) == Supervision.Stop) failStage(ex) + case NonFatal(ex) => if (decider(ex) == Supervision.Stop) failStage(ex) } if (todo < parallelism && !hasBeenPulled(in)) tryPull(in) } @@ -1350,7 +1350,7 @@ private[stream] object Collect { new GraphStageLogic(shape) with InHandler with OutHandler with StageLogging { private lazy val self = getStageActor { - case (_, Terminated(`targetRef`)) ⇒ + case (_, Terminated(`targetRef`)) => failStage(new WatchedActorTerminatedException("Watch", targetRef)) } @@ -1374,7 +1374,7 @@ private[stream] object Collect { */ @InternalApi private[akka] final case class Log[T]( name: String, - extract: T ⇒ Any, + extract: T => Any, logAdapter: Option[LoggingAdapter]) extends SimpleLinearGraphStage[T] { override def toString = "Log" @@ -1393,11 +1393,11 @@ private[stream] object Collect { override def preStart(): Unit = { logLevels = inheritedAttributes.get[LogLevels](DefaultLogLevels) log = logAdapter match { - case Some(l) ⇒ l - case _ ⇒ + case Some(l) => l + case _ => val mat = try ActorMaterializerHelper.downcast(materializer) catch { - case ex: Exception ⇒ + case ex: Exception => throw new RuntimeException("Log stage can only provide LoggingAdapter when used with ActorMaterializer! " + "Provide a LoggingAdapter explicitly or use the actor based flow materializer.", ex) } @@ -1414,9 +1414,9 @@ private[stream] object Collect { push(out, elem) } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case _ ⇒ pull(in) + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case _ => pull(in) } } } @@ -1426,8 +1426,8 @@ private[stream] object Collect { override def onUpstreamFailure(cause: Throwable): Unit = { if (isEnabled(logLevels.onFailure)) logLevels.onFailure match { - case Logging.ErrorLevel ⇒ log.error(cause, "[{}] Upstream failed.", name) - case level ⇒ log.log(level, "[{}] Upstream failed, cause: {}: {}", name, Logging.simpleName(cause + case Logging.ErrorLevel => log.error(cause, "[{}] Upstream failed.", name) + case level => log.log(level, "[{}] Upstream failed, cause: {}: {}", name, Logging.simpleName(cause .getClass), cause.getMessage) } @@ -1471,7 +1471,7 @@ private[stream] object Collect { override def genString(t: Materializer): String = { try s"$DefaultLoggerName(${ActorMaterializerHelper.downcast(t).supervisor.path})" catch { - case _: Exception ⇒ LogSource.fromString.genString(DefaultLoggerName) + case _: Exception => LogSource.fromString.genString(DefaultLoggerName) } } @@ -1503,7 +1503,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final class GroupedWeightedWithin[T](val maxWeight: Long, costFn: T ⇒ Long, val interval: FiniteDuration) extends GraphStage[FlowShape[T, immutable.Seq[T]]] { +@InternalApi private[akka] final class GroupedWeightedWithin[T](val maxWeight: Long, costFn: T => Long, val interval: FiniteDuration) extends GraphStage[FlowShape[T, immutable.Seq[T]]] { require(maxWeight > 0, "maxWeight must be greater than 0") require(interval > Duration.Zero) @@ -1591,7 +1591,7 @@ private[stream] object Collect { push(out, buf.result()) buf.clear() if (!finished) startNewGroup() - else if (pending != null) emit(out, Vector(pending), () ⇒ completeStage()) + else if (pending != null) emit(out, Vector(pending), () => completeStage()) else completeStage() } @@ -1651,9 +1651,9 @@ private[stream] object Collect { override def preStart(): Unit = buffer = BufferImpl(size, materializer) - val onPushWhenBufferFull: () ⇒ Unit = strategy match { - case EmitEarly ⇒ - () ⇒ { + val onPushWhenBufferFull: () => Unit = strategy match { + case EmitEarly => + () => { if (!isTimerActive(timerName)) push(out, buffer.dequeue()._2) else { @@ -1662,32 +1662,32 @@ private[stream] object Collect { } grabAndPull() } - case _: DropHead ⇒ - () ⇒ { + case _: DropHead => + () => { buffer.dropHead() grabAndPull() } - case _: DropTail ⇒ - () ⇒ { + case _: DropTail => + () => { buffer.dropTail() grabAndPull() } - case _: DropNew ⇒ - () ⇒ { + case _: DropNew => + () => { grab(in) if (!isTimerActive(timerName)) scheduleOnce(timerName, d) } - case _: DropBuffer ⇒ - () ⇒ { + case _: DropBuffer => + () => { buffer.clear() grabAndPull() } - case _: Fail ⇒ - () ⇒ { + case _: Fail => + () => { failStage(BufferOverflowException(s"Buffer overflow for delay operator (max capacity was: $size)!")) } - case _: Backpressure ⇒ - () ⇒ { + case _: Backpressure => + () => { throw new IllegalStateException("Delay buffer must never overflow in Backpressure mode") } } @@ -1808,10 +1808,10 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final class Reduce[T](val f: (T, T) ⇒ T) extends SimpleLinearGraphStage[T] { +@InternalApi private[akka] final class Reduce[T](val f: (T, T) => T) extends SimpleLinearGraphStage[T] { override def initialAttributes: Attributes = DefaultAttributes.reduce - override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { self ⇒ + override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { self => override def toString = s"Reduce.Logic(aggregator=$aggregator)" var aggregator: T = _ @@ -1838,12 +1838,12 @@ private[stream] object Collect { try { aggregator = f(aggregator, elem) } catch { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case Supervision.Restart ⇒ + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case Supervision.Restart => aggregator = _: T setInitialInHandler() - case _ ⇒ () + case _ => () } } finally { @@ -1923,7 +1923,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi private[akka] final class StatefulMapConcat[In, Out](val f: () ⇒ In ⇒ immutable.Iterable[Out]) extends GraphStage[FlowShape[In, Out]] { +@InternalApi private[akka] final class StatefulMapConcat[In, Out](val f: () => In => immutable.Iterable[Out]) extends GraphStage[FlowShape[In, Out]] { val in = Inlet[In]("StatefulMapConcat.in") val out = Outlet[Out]("StatefulMapConcat.out") override val shape = FlowShape(in, out) @@ -1962,12 +1962,12 @@ private[stream] object Collect { catch handleException private def handleException: Catcher[Unit] = { - case NonFatal(ex) ⇒ decider(ex) match { - case Supervision.Stop ⇒ failStage(ex) - case Supervision.Resume ⇒ + case NonFatal(ex) => decider(ex) match { + case Supervision.Stop => failStage(ex) + case Supervision.Resume => if (isClosed(in)) completeStage() else if (!hasBeenPulled(in)) pull(in) - case Supervision.Restart ⇒ + case Supervision.Restart => if (isClosed(in)) completeStage() else { restartState() @@ -1989,7 +1989,7 @@ private[stream] object Collect { /** * INTERNAL API */ -@InternalApi final private[akka] class LazyFlow[I, O, M](flowFactory: I ⇒ Future[Flow[I, O, M]]) +@InternalApi final private[akka] class LazyFlow[I, O, M](flowFactory: I => Future[Flow[I, O, M]]) extends GraphStageWithMaterializedValue[FlowShape[I, O], Future[Option[M]]] { val in = Inlet[I]("lazyFlow.in") val out = Outlet[O]("lazyFlow.out") @@ -2015,7 +2015,7 @@ private[stream] object Collect { val element = grab(in) switching = true val cb = getAsyncCallback[Try[Flow[I, O, M]]] { - case Success(flow) ⇒ + case Success(flow) => // check if the stage is still in need for the lazy flow // (there could have been an onUpstreamFailure or onDownstreamFinish in the meantime that has completed the promise) if (!matPromise.isCompleted) { @@ -2023,19 +2023,19 @@ private[stream] object Collect { val mat = switchTo(flow, element) matPromise.success(Some(mat)) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => matPromise.failure(e) failStage(e) } } - case Failure(e) ⇒ + case Failure(e) => matPromise.failure(e) failStage(e) } try { flowFactory(element).onComplete(cb.invoke)(ExecutionContexts.sameThreadExecutionContext) } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => matPromise.failure(e) failStage(e) } diff --git a/akka-stream/src/main/scala/akka/stream/impl/fusing/StreamOfStreams.scala b/akka-stream/src/main/scala/akka/stream/impl/fusing/StreamOfStreams.scala index 132c4371ee..a97f85bf41 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/fusing/StreamOfStreams.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/fusing/StreamOfStreams.scala @@ -22,7 +22,7 @@ import scala.concurrent.duration.FiniteDuration import scala.util.control.NonFatal import scala.annotation.tailrec -import akka.stream.impl.{ Buffer ⇒ BufferImpl } +import akka.stream.impl.{ Buffer => BufferImpl } import scala.collection.JavaConverters._ import akka.stream.impl.TraversalBuilder @@ -51,11 +51,11 @@ import akka.stream.impl.fusing.GraphStages.SingleSource def pushOut(): Unit = { queue.dequeue() match { - case src: SubSinkInlet[T] @unchecked ⇒ + case src: SubSinkInlet[T] @unchecked => push(out, src.grab()) if (!src.isClosed) src.pull() else removeSource(src) - case single: SingleSource[T] @unchecked ⇒ + case single: SingleSource[T] @unchecked => push(out, single.elem) removeSource(single) } @@ -86,14 +86,14 @@ import akka.stream.impl.fusing.GraphStages.SingleSource // If it's a SingleSource or wrapped such we can push the element directly instead of materializing it. // Have to use AnyRef because of OptionVal null value. TraversalBuilder.getSingleSource(source.asInstanceOf[Graph[SourceShape[AnyRef], M]]) match { - case OptionVal.Some(single) ⇒ + case OptionVal.Some(single) => if (isAvailable(out) && queue.isEmpty) { push(out, single.elem.asInstanceOf[T]) } else { queue.enqueue(single) pendingSingleSources += 1 } - case _ ⇒ + case _ => val sinkIn = new SubSinkInlet[T]("FlattenMergeSink") sinkIn.setHandler(new InHandler { override def onPush(): Unit = { @@ -116,9 +116,9 @@ import akka.stream.impl.fusing.GraphStages.SingleSource def removeSource(src: AnyRef): Unit = { val pullSuppressed = activeSources == breadth src match { - case sub: SubSinkInlet[T] @unchecked ⇒ + case sub: SubSinkInlet[T] @unchecked => sources -= sub - case _: SingleSource[_] ⇒ + case _: SingleSource[_] => pendingSingleSources -= 1 } if (pullSuppressed) tryPull(in) @@ -158,12 +158,12 @@ import akka.stream.impl.fusing.GraphStages.SingleSource val timeout = timeoutSettings.timeout timeoutSettings.mode match { - case StreamSubscriptionTimeoutTerminationMode.CancelTermination ⇒ + case StreamSubscriptionTimeoutTerminationMode.CancelTermination => tailSource.timeout(timeout) if (tailSource.isClosed) completeStage() - case StreamSubscriptionTimeoutTerminationMode.NoopTermination ⇒ + case StreamSubscriptionTimeoutTerminationMode.NoopTermination => // do nothing - case StreamSubscriptionTimeoutTerminationMode.WarnTermination ⇒ + case StreamSubscriptionTimeoutTerminationMode.WarnTermination => materializer.logger.warning("Substream subscription timeout triggered after {} in prefixAndTail({}).", timeout, n) } } @@ -213,7 +213,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource override def onUpstreamFinish(): Unit = { if (!prefixComplete) { // This handles the unpulled out case as well - emit(out, (builder.result, Source.empty), () ⇒ completeStage()) + emit(out, (builder.result, Source.empty), () => completeStage()) } else { if (!tailSource.isClosed) tailSource.complete() completeStage() @@ -243,14 +243,14 @@ import akka.stream.impl.fusing.GraphStages.SingleSource /** * INTERNAL API */ -@InternalApi private[akka] final class GroupBy[T, K](val maxSubstreams: Int, val keyFor: T ⇒ K, val allowClosedSubstreamRecreation: Boolean = false) extends GraphStage[FlowShape[T, Source[T, NotUsed]]] { +@InternalApi private[akka] final class GroupBy[T, K](val maxSubstreams: Int, val keyFor: T => K, val allowClosedSubstreamRecreation: Boolean = false) extends GraphStage[FlowShape[T, Source[T, NotUsed]]] { val in: Inlet[T] = Inlet("GroupBy.in") val out: Outlet[Source[T, NotUsed]] = Outlet("GroupBy.out") override val shape: FlowShape[T, Source[T, NotUsed]] = FlowShape(in, out) override def initialAttributes = DefaultAttributes.groupBy override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new TimerGraphStageLogic(shape) with OutHandler with InHandler { - parent ⇒ + parent => lazy val decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider private val activeSubstreamsMap = new java.util.HashMap[Any, SubstreamSource]() @@ -276,7 +276,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource private def tryCompleteAll(): Boolean = if (activeSubstreamsMap.isEmpty || (!hasNextElement && firstPushCounter == 0)) { - for (value ← activeSubstreamsMap.values().asScala) value.complete() + for (value <- activeSubstreamsMap.values().asScala) value.complete() completeStage() true } else false @@ -289,7 +289,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource } else false private def fail(ex: Throwable): Unit = { - for (value ← activeSubstreamsMap.values().asScala) value.fail(ex) + for (value <- activeSubstreamsMap.values().asScala) value.fail(ex) failStage(ex) } @@ -301,11 +301,11 @@ import akka.stream.impl.fusing.GraphStages.SingleSource override def onPull(): Unit = { substreamWaitingToBePushed match { - case Some(substreamSource) ⇒ + case Some(substreamSource) => push(out, Source.fromGraph(substreamSource.source)) scheduleOnce(substreamSource.key, timeout) substreamWaitingToBePushed = None - case None ⇒ + case None => if (hasNextElement) { val subSubstreamSource = activeSubstreamsMap.get(nextElementKey) if (subSubstreamSource.isAvailable) { @@ -341,10 +341,10 @@ import akka.stream.impl.fusing.GraphStages.SingleSource else runSubstream(key, elem) } } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => decider(ex) match { - case Supervision.Stop ⇒ fail(ex) - case Supervision.Resume | Supervision.Restart ⇒ if (!hasBeenPulled(in)) pull(in) + case Supervision.Stop => fail(ex) + case Supervision.Resume | Supervision.Restart => if (!hasBeenPulled(in)) pull(in) } } @@ -437,24 +437,24 @@ import akka.stream.impl.fusing.GraphStages.SingleSource /** Splits after the current element. The current element will be the last element in the current substream. */ case object SplitAfter extends SplitDecision - def when[T](p: T ⇒ Boolean, substreamCancelStrategy: SubstreamCancelStrategy): Graph[FlowShape[T, Source[T, NotUsed]], NotUsed] = + def when[T](p: T => Boolean, substreamCancelStrategy: SubstreamCancelStrategy): Graph[FlowShape[T, Source[T, NotUsed]], NotUsed] = new Split(Split.SplitBefore, p, substreamCancelStrategy) - def after[T](p: T ⇒ Boolean, substreamCancelStrategy: SubstreamCancelStrategy): Graph[FlowShape[T, Source[T, NotUsed]], NotUsed] = + def after[T](p: T => Boolean, substreamCancelStrategy: SubstreamCancelStrategy): Graph[FlowShape[T, Source[T, NotUsed]], NotUsed] = new Split(Split.SplitAfter, p, substreamCancelStrategy) } /** * INTERNAL API */ -@InternalApi private[akka] final class Split[T](val decision: Split.SplitDecision, val p: T ⇒ Boolean, val substreamCancelStrategy: SubstreamCancelStrategy) extends GraphStage[FlowShape[T, Source[T, NotUsed]]] { +@InternalApi private[akka] final class Split[T](val decision: Split.SplitDecision, val p: T => Boolean, val substreamCancelStrategy: SubstreamCancelStrategy) extends GraphStage[FlowShape[T, Source[T, NotUsed]]] { val in: Inlet[T] = Inlet("Split.in") val out: Outlet[Source[T, NotUsed]] = Outlet("Split.out") override val shape: FlowShape[T, Source[T, NotUsed]] = FlowShape(in, out) private val propagateSubstreamCancel = substreamCancelStrategy match { - case SubstreamCancelStrategies.Propagate ⇒ true - case SubstreamCancelStrategies.Drain ⇒ false + case SubstreamCancelStrategies.Propagate => true + case SubstreamCancelStrategies.Drain => false } override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new TimerGraphStageLogic(shape) { @@ -491,10 +491,10 @@ import akka.stream.impl.fusing.GraphStages.SingleSource val elem = grab(in) decision match { - case SplitAfter if p(elem) ⇒ + case SplitAfter if p(elem) => push(out, Source.single(elem)) // Next pull will come from the next substream that we will open - case _ ⇒ + case _ => handler.firstElem = elem } @@ -539,12 +539,12 @@ import akka.stream.impl.fusing.GraphStages.SingleSource // Substreams are always assumed to be pushable position when we enter this method private def closeThis(handler: SubstreamHandler, currentElem: T): Unit = { decision match { - case SplitAfter ⇒ + case SplitAfter => if (!substreamCancelled) { substreamSource.push(currentElem) substreamSource.complete() } - case SplitBefore ⇒ + case SplitBefore => handler.firstElem = currentElem if (!substreamCancelled) substreamSource.complete() } @@ -591,7 +591,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource else substreamSource.push(elem) } } catch { - case NonFatal(ex) ⇒ onUpstreamFailure(ex) + case NonFatal(ex) => onUpstreamFailure(ex) } } @@ -642,7 +642,7 @@ import akka.stream.impl.fusing.GraphStages.SingleSource /** * INTERNAL API */ -@InternalApi private[stream] final class SubSink[T](name: String, externalCallback: ActorSubscriberMessage ⇒ Unit) +@InternalApi private[stream] final class SubSink[T](name: String, externalCallback: ActorSubscriberMessage => Unit) extends GraphStage[SinkShape[T]] { import SubSink._ @@ -659,17 +659,17 @@ import akka.stream.impl.fusing.GraphStages.SingleSource @tailrec private def dispatchCommand(newState: CommandScheduledBeforeMaterialization): Unit = status.get match { - case /* Materialized */ callback: AsyncCallback[Command @unchecked] ⇒ callback.invoke(newState.command) - case Uninitialized ⇒ + case /* Materialized */ callback: AsyncCallback[Command @unchecked] => callback.invoke(newState.command) + case Uninitialized => if (!status.compareAndSet(Uninitialized, newState)) dispatchCommand(newState) // changed to materialized in the meantime - case RequestOneScheduledBeforeMaterialization if newState == CancelScheduledBeforeMaterialization ⇒ + case RequestOneScheduledBeforeMaterialization if newState == CancelScheduledBeforeMaterialization => // cancellation is allowed to replace pull if (!status.compareAndSet(RequestOneScheduledBeforeMaterialization, newState)) dispatchCommand(RequestOneScheduledBeforeMaterialization) - case cmd: CommandScheduledBeforeMaterialization ⇒ + case cmd: CommandScheduledBeforeMaterialization => throw new IllegalStateException(s"${newState.command} on subsink is illegal when ${cmd.command} is still pending") } @@ -681,13 +681,13 @@ import akka.stream.impl.fusing.GraphStages.SingleSource override def onUpstreamFailure(ex: Throwable): Unit = externalCallback(ActorSubscriberMessage.OnError(ex)) @tailrec - private def setCallback(callback: Command ⇒ Unit): Unit = + private def setCallback(callback: Command => Unit): Unit = status.get match { - case Uninitialized ⇒ + case Uninitialized => if (!status.compareAndSet(Uninitialized, /* Materialized */ getAsyncCallback[Command](callback))) setCallback(callback) - case cmd: CommandScheduledBeforeMaterialization ⇒ + case cmd: CommandScheduledBeforeMaterialization => if (status.compareAndSet(cmd, /* Materialized */ getAsyncCallback[Command](callback))) // between those two lines a new command might have been scheduled, but that will go through the // async interface, so that the ordering is still kept @@ -695,14 +695,14 @@ import akka.stream.impl.fusing.GraphStages.SingleSource else setCallback(callback) - case _: /* Materialized */ AsyncCallback[Command @unchecked] ⇒ + case _: /* Materialized */ AsyncCallback[Command @unchecked] => failStage(new IllegalStateException("Substream Source cannot be materialized more than once")) } override def preStart(): Unit = setCallback { - case RequestOne ⇒ tryPull(in) - case Cancel ⇒ completeStage() + case RequestOne => tryPull(in) + case Cancel => completeStage() } } @@ -723,20 +723,20 @@ import akka.stream.impl.fusing.GraphStages.SingleSource private val status = new AtomicReference[AnyRef] def pushSubstream(elem: T): Unit = status.get match { - case f: AsyncCallback[Any] @unchecked ⇒ f.invoke(ActorSubscriberMessage.OnNext(elem)) - case _ ⇒ throw new IllegalStateException("cannot push to uninitialized substream") + case f: AsyncCallback[Any] @unchecked => f.invoke(ActorSubscriberMessage.OnNext(elem)) + case _ => throw new IllegalStateException("cannot push to uninitialized substream") } def completeSubstream(): Unit = status.get match { - case f: AsyncCallback[Any] @unchecked ⇒ f.invoke(ActorSubscriberMessage.OnComplete) - case null ⇒ + case f: AsyncCallback[Any] @unchecked => f.invoke(ActorSubscriberMessage.OnComplete) + case null => if (!status.compareAndSet(null, ActorSubscriberMessage.OnComplete)) status.get.asInstanceOf[AsyncCallback[Any]].invoke(ActorSubscriberMessage.OnComplete) } def failSubstream(ex: Throwable): Unit = status.get match { - case f: AsyncCallback[Any] @unchecked ⇒ f.invoke(ActorSubscriberMessage.OnError(ex)) - case null ⇒ + case f: AsyncCallback[Any] @unchecked => f.invoke(ActorSubscriberMessage.OnError(ex)) + case null => val failure = ActorSubscriberMessage.OnError(ex) if (!status.compareAndSet(null, failure)) status.get.asInstanceOf[AsyncCallback[Any]].invoke(failure) @@ -750,18 +750,18 @@ import akka.stream.impl.fusing.GraphStages.SingleSource @tailrec private def setCB(cb: AsyncCallback[ActorSubscriberMessage]): Unit = { status.get match { - case null ⇒ if (!status.compareAndSet(null, cb)) setCB(cb) - case ActorSubscriberMessage.OnComplete ⇒ completeStage() - case ActorSubscriberMessage.OnError(ex) ⇒ failStage(ex) - case _: AsyncCallback[_] ⇒ failStage(new IllegalStateException("Substream Source cannot be materialized more than once")) + case null => if (!status.compareAndSet(null, cb)) setCB(cb) + case ActorSubscriberMessage.OnComplete => completeStage() + case ActorSubscriberMessage.OnError(ex) => failStage(ex) + case _: AsyncCallback[_] => failStage(new IllegalStateException("Substream Source cannot be materialized more than once")) } } override def preStart(): Unit = { val ourOwnCallback = getAsyncCallback[ActorSubscriberMessage] { - case ActorSubscriberMessage.OnComplete ⇒ completeStage() - case ActorSubscriberMessage.OnError(ex) ⇒ failStage(ex) - case ActorSubscriberMessage.OnNext(elem) ⇒ push(out, elem.asInstanceOf[T]) + case ActorSubscriberMessage.OnComplete => completeStage() + case ActorSubscriberMessage.OnError(ex) => failStage(ex) + case ActorSubscriberMessage.OnNext(elem) => push(out, elem.asInstanceOf[T]) } setCB(ourOwnCallback) } diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/ByteStringParser.scala b/akka-stream/src/main/scala/akka/stream/impl/io/ByteStringParser.scala index a08525eb91..868afdc3f8 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/ByteStringParser.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/ByteStringParser.scala @@ -70,7 +70,7 @@ import scala.util.control.{ NoStackTrace, NonFatal } DontRecurse } } catch { - case NeedMoreData ⇒ + case NeedMoreData => acceptUpstreamFinish = false if (current.canWorkWithPartialData) buffer = reader.remainingData @@ -79,7 +79,7 @@ import scala.util.control.{ NoStackTrace, NonFatal } else pull(bytesIn) DontRecurse - case NonFatal(ex) ⇒ + case NonFatal(ex) => failStage(new ParsingException(s"Parsing failed in step $current", ex)) DontRecurse diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/FileSubscriber.scala b/akka-stream/src/main/scala/akka/stream/impl/io/FileSubscriber.scala index 5a5c6b817c..b7e0bede18 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/FileSubscriber.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/FileSubscriber.scala @@ -46,27 +46,27 @@ import scala.util.{ Failure, Success, Try } super.preStart() } catch { - case ex: Exception ⇒ + case ex: Exception => closeAndComplete(Failure(ex)) cancel() } def receive = { - case ActorSubscriberMessage.OnNext(bytes: ByteString) ⇒ + case ActorSubscriberMessage.OnNext(bytes: ByteString) => try { bytesWritten += chan.write(bytes.asByteBuffer) } catch { - case ex: Exception ⇒ + case ex: Exception => closeAndComplete(Success(IOResult(bytesWritten, Failure(ex)))) cancel() } - case ActorSubscriberMessage.OnError(ex) ⇒ + case ActorSubscriberMessage.OnError(ex) => log.error(ex, "Tearing down FileSink({}) due to upstream error", f) closeAndComplete(Failure(AbruptIOTerminationException(IOResult(bytesWritten, Success(Done)), ex))) context.stop(self) - case ActorSubscriberMessage.OnComplete ⇒ context.stop(self) + case ActorSubscriberMessage.OnComplete => context.stop(self) } override def postStop(): Unit = { @@ -82,11 +82,11 @@ import scala.util.{ Failure, Success, Try } if (chan ne null) chan.close() completionPromise.tryComplete(result) } catch { - case closingException: Exception ⇒ result match { - case Success(ioResult) ⇒ - val statusWithClosingException = ioResult.status.transform(_ ⇒ Failure(closingException), ex ⇒ Failure(closingException.initCause(ex))) + case closingException: Exception => result match { + case Success(ioResult) => + val statusWithClosingException = ioResult.status.transform(_ => Failure(closingException), ex => Failure(closingException.initCause(ex))) completionPromise.trySuccess(ioResult.copy(status = statusWithClosingException)) - case Failure(ex) ⇒ completionPromise.tryFailure(closingException.initCause(ex)) + case Failure(ex) => completionPromise.tryFailure(closingException.initCause(ex)) } } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/IOSinks.scala b/akka-stream/src/main/scala/akka/stream/impl/io/IOSinks.scala index 0ca9c99ad9..f9ffba6543 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/IOSinks.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/IOSinks.scala @@ -50,7 +50,7 @@ import scala.concurrent.{ Future, Promise } * INTERNAL API * Creates simple synchronous Sink which writes all incoming elements to the output stream. */ -@InternalApi private[akka] final class OutputStreamSink(createOutput: () ⇒ OutputStream, val attributes: Attributes, shape: SinkShape[ByteString], autoFlush: Boolean) +@InternalApi private[akka] final class OutputStreamSink(createOutput: () => OutputStream, val attributes: Attributes, shape: SinkShape[ByteString], autoFlush: Boolean) extends SinkModule[ByteString, Future[IOResult]](shape) { override def create(context: MaterializationContext) = { diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/IOSources.scala b/akka-stream/src/main/scala/akka/stream/impl/io/IOSources.scala index dc530fe7f9..3977dd41ae 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/IOSources.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/IOSources.scala @@ -30,13 +30,13 @@ import scala.util.{ Failure, Success, Try } private[akka] object FileSource { - val completionHandler = new CompletionHandler[Integer, Try[Int] ⇒ Unit] { + val completionHandler = new CompletionHandler[Integer, Try[Int] => Unit] { - override def completed(result: Integer, attachment: Try[Int] ⇒ Unit): Unit = { + override def completed(result: Integer, attachment: Try[Int] => Unit): Unit = { attachment(Success(result)) } - override def failed(ex: Throwable, attachment: Try[Int] ⇒ Unit): Unit = { + override def failed(ex: Throwable, attachment: Try[Int] => Unit): Unit = { attachment(Failure(ex)) } } @@ -57,12 +57,12 @@ private[akka] final class FileSource(path: Path, chunkSize: Int, startPosition: val ioResultPromise = Promise[IOResult]() val logic = new GraphStageLogic(shape) with OutHandler { - handler ⇒ + handler => val buffer = ByteBuffer.allocate(chunkSize) val maxReadAhead = inheritedAttributes.get[InputBuffer](InputBuffer(16, 16)).max var channel: FileChannel = _ var position = startPosition - var chunkCallback: Try[Int] ⇒ Unit = _ + var chunkCallback: Try[Int] => Unit = _ var eofEncountered = false var availableChunks: Vector[ByteString] = Vector.empty[ByteString] @@ -79,7 +79,7 @@ private[akka] final class FileSource(path: Path, chunkSize: Int, startPosition: channel = FileChannel.open(path, StandardOpenOption.READ) channel.position(position) } catch { - case ex: Exception ⇒ + case ex: Exception => ioResultPromise.trySuccess(IOResult(position, Failure(ex))) throw ex } @@ -91,7 +91,7 @@ private[akka] final class FileSource(path: Path, chunkSize: Int, startPosition: //if already read something and try if (availableChunks.nonEmpty) { emitMultiple(out, availableChunks.iterator, - () ⇒ if (eofEncountered) success() else setHandler(out, handler) + () => if (eofEncountered) success() else setHandler(out, handler) ) availableChunks = Vector.empty[ByteString] } else if (eofEncountered) success() @@ -106,7 +106,7 @@ private[akka] final class FileSource(path: Path, chunkSize: Int, startPosition: @tailrec def readAhead(maxChunks: Int, chunks: Vector[ByteString]): Vector[ByteString] = if (chunks.size < maxChunks && !eofEncountered) { val readBytes = try channel.read(buffer, position) catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => failStage(ex) ioResultPromise.trySuccess(IOResult(position, Failure(ex))) throw ex @@ -146,7 +146,7 @@ private[akka] final class FileSource(path: Path, chunkSize: Int, startPosition: * INTERNAL API * Source backed by the given input stream. */ -@InternalApi private[akka] final class InputStreamSource(createInputStream: () ⇒ InputStream, chunkSize: Int, val attributes: Attributes, shape: SourceShape[ByteString]) +@InternalApi private[akka] final class InputStreamSource(createInputStream: () => InputStream, chunkSize: Int, val attributes: Attributes, shape: SourceShape[ByteString]) extends SourceModule[ByteString, Future[IOResult]](shape) { override def create(context: MaterializationContext) = { val materializer = ActorMaterializerHelper.downcast(context.materializer) @@ -162,7 +162,7 @@ private[akka] final class FileSource(path: Path, chunkSize: Int, startPosition: val ref = materializer.actorOf(context, props) akka.stream.actor.ActorPublisher[ByteString](ref) } catch { - case ex: Exception ⇒ + case ex: Exception => ioResultPromise.failure(ex) ErrorPublisher(ex, attributes.nameOrDefault("inputStreamSource")).asInstanceOf[Publisher[ByteString]] } diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/InputStreamPublisher.scala b/akka-stream/src/main/scala/akka/stream/impl/io/InputStreamPublisher.scala index 57c6c3bd59..45dba3f745 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/InputStreamPublisher.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/InputStreamPublisher.scala @@ -41,9 +41,9 @@ import scala.util.{ Failure, Success } var readBytesTotal = 0L def receive = { - case ActorPublisherMessage.Request(elements) ⇒ readAndSignal() - case Continue ⇒ readAndSignal() - case ActorPublisherMessage.Cancel ⇒ context.stop(self) + case ActorPublisherMessage.Request(elements) => readAndSignal() + case Continue => readAndSignal() + case ActorPublisherMessage.Cancel => context.stop(self) } def readAndSignal(): Unit = @@ -57,19 +57,19 @@ import scala.util.{ Failure, Success } val readBytes = is.read(arr) readBytes match { - case -1 ⇒ + case -1 => // had nothing to read into this chunk log.debug("No more bytes available to read (got `-1` from `read`)") onCompleteThenStop() - case _ ⇒ + case _ => readBytesTotal += readBytes // emit immediately, as this is the only chance to do it before we might block again onNext(ByteString.fromArray(arr, 0, readBytes)) } } catch { - case ex: Exception ⇒ + case ex: Exception => onErrorThenStop(ex) } @@ -79,7 +79,7 @@ import scala.util.{ Failure, Success } try { if (is ne null) is.close() } catch { - case ex: Exception ⇒ + case ex: Exception => completionPromise.success(IOResult(readBytesTotal, Failure(ex))) } diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/InputStreamSinkStage.scala b/akka-stream/src/main/scala/akka/stream/impl/io/InputStreamSinkStage.scala index efa62d5812..39c7aeeeb8 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/InputStreamSinkStage.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/InputStreamSinkStage.scala @@ -57,8 +57,8 @@ private[stream] object InputStreamSinkStage { private val callback: AsyncCallback[AdapterToStageMessage] = getAsyncCallback { - case ReadElementAcknowledgement ⇒ sendPullIfAllowed() - case Close ⇒ completeStage() + case ReadElementAcknowledgement => sendPullIfAllowed() + case Close => completeStage() } override def wakeUp(msg: AdapterToStageMessage): Unit = callback.invoke(msg) @@ -112,7 +112,7 @@ private[stream] object InputStreamSinkStage { */ @InternalApi private[akka] class InputStreamAdapter( sharedBuffer: BlockingQueue[StreamToAdapterMessage], - sendToStage: (AdapterToStageMessage) ⇒ Unit, + sendToStage: (AdapterToStageMessage) => Unit, readTimeout: FiniteDuration) extends InputStream { @@ -123,7 +123,7 @@ private[stream] object InputStreamSinkStage { var detachedChunk: Option[ByteString] = None @scala.throws(classOf[IOException]) - private[this] def executeIfNotClosed[T](f: () ⇒ T): T = + private[this] def executeIfNotClosed[T](f: () => T): T = if (isActive) { waitIfNotInitialized() f() @@ -133,9 +133,9 @@ private[stream] object InputStreamSinkStage { override def read(): Int = { val a = new Array[Byte](1) read(a, 0, 1) match { - case 1 ⇒ a(0) & 0xff - case -1 ⇒ -1 - case len ⇒ throw new IllegalStateException(s"Invalid length [$len]") + case 1 => a(0) & 0xff + case -1 => -1 + case len => throw new IllegalStateException(s"Invalid length [$len]") } } @@ -149,28 +149,28 @@ private[stream] object InputStreamSinkStage { require(length > 0, "length must be > 0") require(begin + length <= a.length, "begin + length must be smaller or equal to the array length") - executeIfNotClosed(() ⇒ + executeIfNotClosed(() => if (isStageAlive) { detachedChunk match { - case None ⇒ + case None => try { sharedBuffer.poll(readTimeout.toMillis, TimeUnit.MILLISECONDS) match { - case Data(data) ⇒ + case Data(data) => detachedChunk = Some(data) readBytes(a, begin, length) - case Finished ⇒ + case Finished => isStageAlive = false -1 - case Failed(ex) ⇒ + case Failed(ex) => isStageAlive = false throw new IOException(ex) - case null ⇒ throw new IOException("Timeout on waiting for new data") - case Initialized ⇒ throw new IllegalStateException("message 'Initialized' must come first") + case null => throw new IOException("Timeout on waiting for new data") + case Initialized => throw new IllegalStateException("message 'Initialized' must come first") } } catch { - case ex: InterruptedException ⇒ throw new IOException(ex) + case ex: InterruptedException => throw new IOException(ex) } - case Some(data) ⇒ + case Some(data) => readBytes(a, begin, length) } } else -1) @@ -186,7 +186,7 @@ private[stream] object InputStreamSinkStage { @scala.throws(classOf[IOException]) override def close(): Unit = { - executeIfNotClosed(() ⇒ { + executeIfNotClosed(() => { // at this point Subscriber may be already terminated if (isStageAlive) sendToStage(Close) isActive = false @@ -197,7 +197,7 @@ private[stream] object InputStreamSinkStage { private[this] def getData(arr: Array[Byte], begin: Int, length: Int, gotBytes: Int): Int = { grabDataChunk() match { - case Some(data) ⇒ + case Some(data) => val size = data.size if (size <= length) { data.copyToArray(arr, begin, size) @@ -211,34 +211,34 @@ private[stream] object InputStreamSinkStage { detachedChunk = Some(data.drop(length)) gotBytes + length } - case None ⇒ gotBytes + case None => gotBytes } } private[this] def waitIfNotInitialized(): Unit = { if (!isInitialized) { sharedBuffer.poll(readTimeout.toMillis, TimeUnit.MILLISECONDS) match { - case Initialized ⇒ isInitialized = true - case null ⇒ throw new IOException(s"Timeout after $readTimeout waiting for Initialized message from stage") - case entry ⇒ require(false, s"First message must be Initialized notification, got $entry") + case Initialized => isInitialized = true + case null => throw new IOException(s"Timeout after $readTimeout waiting for Initialized message from stage") + case entry => require(false, s"First message must be Initialized notification, got $entry") } } } private[this] def grabDataChunk(): Option[ByteString] = { detachedChunk match { - case None ⇒ + case None => sharedBuffer.poll() match { - case Data(data) ⇒ + case Data(data) => detachedChunk = Some(data) detachedChunk - case Finished ⇒ + case Finished => isStageAlive = false None - case Failed(e) ⇒ throw new IOException(e) - case _ ⇒ None + case Failed(e) => throw new IOException(e) + case _ => None } - case Some(_) ⇒ detachedChunk + case Some(_) => detachedChunk } } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/OutputStreamSourceStage.scala b/akka-stream/src/main/scala/akka/stream/impl/io/OutputStreamSourceStage.scala index 5062c8bcfb..978b95311a 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/OutputStreamSourceStage.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/OutputStreamSourceStage.scala @@ -48,9 +48,9 @@ final private[stream] class OutputStreamSourceStage(writeTimeout: FiniteDuration private def onAsyncMessage(event: AdapterToStageMessage): Unit = { event match { - case Send(data) ⇒ - emit(out, data, () ⇒ semaphore.release()) - case Close ⇒ + case Send(data) => + emit(out, data, () => semaphore.release()) + case Close => completeStage() } } @@ -81,7 +81,7 @@ private[akka] class OutputStreamAdapter( try { Await.result(sendToStage.invokeWithFeedback(Send(data)), writeTimeout) } catch { - case NonFatal(e) ⇒ throw new IOException(e) + case NonFatal(e) => throw new IOException(e) } } @@ -107,7 +107,7 @@ private[akka] class OutputStreamAdapter( try { Await.result(sendToStage.invokeWithFeedback(Close), writeTimeout) } catch { - case NonFatal(e) ⇒ throw new IOException(e) + case NonFatal(e) => throw new IOException(e) } } } diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/OutputStreamSubscriber.scala b/akka-stream/src/main/scala/akka/stream/impl/io/OutputStreamSubscriber.scala index 8f0b2f0519..f034749d2c 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/OutputStreamSubscriber.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/OutputStreamSubscriber.scala @@ -35,24 +35,24 @@ import scala.util.{ Failure, Success } private var bytesWritten: Long = 0 def receive = { - case ActorSubscriberMessage.OnNext(bytes: ByteString) ⇒ + case ActorSubscriberMessage.OnNext(bytes: ByteString) => try { // blocking write os.write(bytes.toArray) bytesWritten += bytes.length if (autoFlush) os.flush() } catch { - case ex: Exception ⇒ + case ex: Exception => completionPromise.success(IOResult(bytesWritten, Failure(ex))) cancel() } - case ActorSubscriberMessage.OnError(ex) ⇒ + case ActorSubscriberMessage.OnError(ex) => log.error(ex, "Tearing down OutputStreamSink due to upstream error, wrote bytes: {}", bytesWritten) completionPromise.failure(AbruptIOTerminationException(IOResult(bytesWritten, Success(Done)), ex)) context.stop(self) - case ActorSubscriberMessage.OnComplete ⇒ + case ActorSubscriberMessage.OnComplete => context.stop(self) os.flush() } @@ -61,7 +61,7 @@ import scala.util.{ Failure, Success } try { if (os ne null) os.close() } catch { - case ex: Exception ⇒ + case ex: Exception => completionPromise.success(IOResult(bytesWritten, Failure(ex))) } diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/TLSActor.scala b/akka-stream/src/main/scala/akka/stream/impl/io/TLSActor.scala index f2aaeb06eb..85503cd1ab 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/TLSActor.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/TLSActor.scala @@ -31,8 +31,8 @@ import scala.util.{ Failure, Success, Try } def props( maxInputBufferSize: Int, - createSSLEngine: ActorSystem ⇒ SSLEngine, // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 - verifySession: (ActorSystem, SSLSession) ⇒ Try[Unit], // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 + createSSLEngine: ActorSystem => SSLEngine, // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 + verifySession: (ActorSystem, SSLSession) => Try[Unit], // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 closing: TLSClosing, tracing: Boolean = false): Props = Props(new TLSActor(maxInputBufferSize, createSSLEngine, verifySession, closing, tracing)).withDeploy(Deploy.local) @@ -49,8 +49,8 @@ import scala.util.{ Failure, Success, Try } */ @InternalApi private[stream] class TLSActor( maxInputBufferSize: Int, - createSSLEngine: ActorSystem ⇒ SSLEngine, // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 - verifySession: (ActorSystem, SSLSession) ⇒ Try[Unit], // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 + createSSLEngine: ActorSystem => SSLEngine, // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 + verifySession: (ActorSystem, SSLSession) => Try[Unit], // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 closing: TLSClosing, tracing: Boolean) extends Actor with ActorLogging with Pump { @@ -94,9 +94,9 @@ import scala.util.{ Failure, Success, Try } if (buffer.isEmpty) { buffer = inputBunch.dequeue(idx) match { // this class handles both UserIn and TransportIn - case bs: ByteString ⇒ bs - case SendBytes(bs) ⇒ bs - case n: NegotiateNewSession ⇒ + case bs: ByteString => bs + case SendBytes(bs) => bs + case n: NegotiateNewSession => setNewSessionParameters(n) ByteString.empty } @@ -154,7 +154,7 @@ import scala.util.{ Failure, Success, Try } // The engine could also be instantiated in ActorMaterializerImpl but if creation fails // during materialization it would be worse than failing later on. val engine = - try createSSLEngine(context.system) catch { case NonFatal(ex) ⇒ fail(ex, closeTransport = true); throw ex } + try createSSLEngine(context.system) catch { case NonFatal(ex) => fail(ex, closeTransport = true); throw ex } engine.beginHandshake() lastHandshakeStatus = engine.getHandshakeStatus @@ -222,7 +222,7 @@ import scala.util.{ Failure, Success, Try } val outboundHalfClosed = engineNeedsWrap && outputBunch.demandAvailableFor(TransportOut) val inboundHalfClosed = transportInChoppingBlock && engineInboundOpen - val bidirectional = TransferPhase(outbound || inbound) { () ⇒ + val bidirectional = TransferPhase(outbound || inbound) { () => if (tracing) log.debug("bidirectional") val continue = doInbound(isOutboundClosed = false, inbound) if (continue) { @@ -231,30 +231,30 @@ import scala.util.{ Failure, Success, Try } } } - val flushingOutbound = TransferPhase(outboundHalfClosed) { () ⇒ + val flushingOutbound = TransferPhase(outboundHalfClosed) { () => if (tracing) log.debug("flushingOutbound") try doWrap() - catch { case ex: SSLException ⇒ nextPhase(completedPhase) } + catch { case ex: SSLException => nextPhase(completedPhase) } } - val awaitingClose = TransferPhase(inputBunch.inputsAvailableFor(TransportIn) && engineInboundOpen) { () ⇒ + val awaitingClose = TransferPhase(inputBunch.inputsAvailableFor(TransportIn) && engineInboundOpen) { () => if (tracing) log.debug("awaitingClose") transportInChoppingBlock.chopInto(transportInBuffer) try doUnwrap(ignoreOutput = true) - catch { case ex: SSLException ⇒ nextPhase(completedPhase) } + catch { case ex: SSLException => nextPhase(completedPhase) } } - val outboundClosed = TransferPhase(outboundHalfClosed || inbound) { () ⇒ + val outboundClosed = TransferPhase(outboundHalfClosed || inbound) { () => if (tracing) log.debug("outboundClosed") val continue = doInbound(isOutboundClosed = true, inbound) if (continue && outboundHalfClosed.isReady) { if (tracing) log.debug("outboundClosed continue") try doWrap() - catch { case ex: SSLException ⇒ nextPhase(completedPhase) } + catch { case ex: SSLException => nextPhase(completedPhase) } } } - val inboundClosed = TransferPhase(outbound || inboundHalfClosed) { () ⇒ + val inboundClosed = TransferPhase(outbound || inboundHalfClosed) { () => if (tracing) log.debug("inboundClosed") val continue = doInbound(isOutboundClosed = false, inboundHalfClosed) if (continue) { @@ -271,7 +271,7 @@ import scala.util.{ Failure, Success, Try } if (inputBunch.isDepleted(TransportIn) && transportInChoppingBlock.isEmpty) { if (tracing) log.debug("closing inbound") try engine.closeInbound() - catch { case ex: SSLException ⇒ outputBunch.enqueue(UserOut, SessionTruncated) } + catch { case ex: SSLException => outputBunch.enqueue(UserOut, SessionTruncated) } lastHandshakeStatus = engine.getHandshakeStatus completeOrFlush() false @@ -292,7 +292,7 @@ import scala.util.{ Failure, Success, Try } doUnwrap() true } catch { - case ex: SSLException ⇒ + case ex: SSLException => if (tracing) log.debug(s"SSLException during doUnwrap: $ex") fail(ex, closeTransport = false) engine.closeInbound() // we don't need to add lastHandshakeStatus check here because @@ -318,7 +318,7 @@ import scala.util.{ Failure, Success, Try } if (userHasData.isReady) userInChoppingBlock.chopInto(userInBuffer) try doWrap() catch { - case ex: SSLException ⇒ + case ex: SSLException => if (tracing) log.debug(s"SSLException during doWrap: $ex") fail(ex, closeTransport = false) completeOrFlush() @@ -353,14 +353,14 @@ import scala.util.{ Failure, Success, Try } if (lastHandshakeStatus == FINISHED) handshakeFinished() runDelegatedTasks() result.getStatus match { - case OK ⇒ + case OK => flushToTransport() userInChoppingBlock.putBack(userInBuffer) - case CLOSED ⇒ + case CLOSED => flushToTransport() if (engine.isInboundDone) nextPhase(completedPhase) else nextPhase(awaitingClose) - case s ⇒ fail(new IllegalStateException(s"unexpected status $s in doWrap()")) + case s => fail(new IllegalStateException(s"unexpected status $s in doWrap()")) } } @@ -372,27 +372,27 @@ import scala.util.{ Failure, Success, Try } if (tracing) log.debug(s"unwrap: status=${result.getStatus} handshake=$lastHandshakeStatus remaining=${transportInBuffer.remaining} out=${userOutBuffer.position()}") runDelegatedTasks() result.getStatus match { - case OK ⇒ + case OK => result.getHandshakeStatus match { - case NEED_WRAP ⇒ flushToUser() - case FINISHED ⇒ + case NEED_WRAP => flushToUser() + case FINISHED => flushToUser() handshakeFinished() transportInChoppingBlock.putBack(transportInBuffer) - case _ ⇒ + case _ => if (transportInBuffer.hasRemaining) doUnwrap() else flushToUser() } - case CLOSED ⇒ + case CLOSED => flushToUser() if (engine.isOutboundDone) nextPhase(completedPhase) else nextPhase(flushingOutbound) - case BUFFER_UNDERFLOW ⇒ + case BUFFER_UNDERFLOW => flushToUser() - case BUFFER_OVERFLOW ⇒ + case BUFFER_OVERFLOW => flushToUser() transportInChoppingBlock.putBack(transportInBuffer) - case s ⇒ fail(new IllegalStateException(s"unexpected status $s in doUnwrap()")) + case s => fail(new IllegalStateException(s"unexpected status $s in doUnwrap()")) } } @@ -415,10 +415,10 @@ import scala.util.{ Failure, Success, Try } val session = engine.getSession verifySession(context.system, session) match { - case Success(()) ⇒ + case Success(()) => currentSession = session corkUser = false - case Failure(ex) ⇒ + case Failure(ex) => fail(ex, closeTransport = true) } } @@ -459,13 +459,13 @@ import scala.util.{ Failure, Success, Try } */ @InternalApi private[akka] object TlsUtils { def applySessionParameters(engine: SSLEngine, sessionParameters: NegotiateNewSession): Unit = { - sessionParameters.enabledCipherSuites foreach (cs ⇒ engine.setEnabledCipherSuites(cs.toArray)) - sessionParameters.enabledProtocols foreach (p ⇒ engine.setEnabledProtocols(p.toArray)) + sessionParameters.enabledCipherSuites foreach (cs => engine.setEnabledCipherSuites(cs.toArray)) + sessionParameters.enabledProtocols foreach (p => engine.setEnabledProtocols(p.toArray)) sessionParameters.clientAuth match { - case Some(TLSClientAuth.None) ⇒ engine.setNeedClientAuth(false) - case Some(TLSClientAuth.Want) ⇒ engine.setWantClientAuth(true) - case Some(TLSClientAuth.Need) ⇒ engine.setNeedClientAuth(true) - case _ ⇒ // do nothing + case Some(TLSClientAuth.None) => engine.setNeedClientAuth(false) + case Some(TLSClientAuth.Want) => engine.setWantClientAuth(true) + case Some(TLSClientAuth.Need) => engine.setNeedClientAuth(true) + case _ => // do nothing } sessionParameters.sslParameters.foreach(engine.setSSLParameters) diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/TcpStages.scala b/akka-stream/src/main/scala/akka/stream/impl/io/TcpStages.scala index 1a8dcb7e00..5486e49307 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/TcpStages.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/TcpStages.scala @@ -19,7 +19,7 @@ import akka.stream._ import akka.stream.impl.ReactiveStreamsCompliance import akka.stream.impl.fusing.GraphStages.detacher import akka.stream.scaladsl.Tcp.{ OutgoingConnection, ServerBinding } -import akka.stream.scaladsl.{ BidiFlow, Flow, TcpIdleTimeoutException, Tcp ⇒ StreamTcp } +import akka.stream.scaladsl.{ BidiFlow, Flow, TcpIdleTimeoutException, Tcp => StreamTcp } import akka.stream.stage._ import akka.util.ByteString @@ -67,18 +67,18 @@ import scala.concurrent.{ Future, Promise } val sender = evt._1 val msg = evt._2 msg match { - case Bound(localAddress) ⇒ + case Bound(localAddress) => listener = sender stageActor.watch(listener) if (isAvailable(out)) listener ! ResumeAccepting(1) val thisStage = self - bindingPromise.success(ServerBinding(localAddress)(() ⇒ { + bindingPromise.success(ServerBinding(localAddress)(() => { // Beware, sender must be explicit since stageActor.ref will be invalid to access after the stage // stopped. thisStage.tell(Unbind, thisStage) unbindPromise.future - }, unbindPromise.future.map(_ ⇒ Done)(ExecutionContexts.sameThreadExecutionContext))) - case f: CommandFailed ⇒ + }, unbindPromise.future.map(_ => Done)(ExecutionContexts.sameThreadExecutionContext))) + case f: CommandFailed => val ex = new BindFailedException { // cannot modify the actual exception class for compatibility reasons override def getMessage: String = s"Bind failed${f.causedByString}" @@ -87,13 +87,13 @@ import scala.concurrent.{ Future, Promise } bindingPromise.failure(ex) unbindPromise.tryFailure(ex) failStage(ex) - case c: Connected ⇒ + case c: Connected => push(out, connectionFor(c, sender)) - case Unbind ⇒ + case Unbind => if (!isClosed(out) && (listener ne null)) tryUnbind() - case Unbound ⇒ + case Unbound => unbindCompleted() - case Terminated(ref) if ref == listener ⇒ + case Terminated(ref) if ref == listener => if (unbindStarted) { unbindCompleted() } else { @@ -119,13 +119,13 @@ import scala.concurrent.{ Future, Promise } val tcpFlow = Flow.fromGraph(new IncomingConnectionStage(connection, connected.remoteAddress, halfClose, ioSettings, - () ⇒ connectionFlowsAwaitingInitialization.decrementAndGet())) + () => connectionFlowsAwaitingInitialization.decrementAndGet())) .via(detacher[ByteString]) // must read ahead for proper completions // FIXME: Previous code was wrong, must add new tests val handler = idleTimeout match { - case d: FiniteDuration ⇒ tcpFlow.join(TcpIdleTimeout(d, Some(connected.remoteAddress))) - case _ ⇒ tcpFlow + case d: FiniteDuration => tcpFlow.join(TcpIdleTimeout(d, Some(connected.remoteAddress))) + case _ => tcpFlow } StreamTcp.IncomingConnection( @@ -150,7 +150,7 @@ import scala.concurrent.{ Future, Promise } } override def onTimer(timerKey: Any): Unit = timerKey match { - case BindShutdownTimer ⇒ + case BindShutdownTimer => completeStage() // TODO need to manually shut down instead right? } @@ -189,7 +189,7 @@ private[stream] object ConnectionSourceStage { halfClose: Boolean, ioSettings: IOSettings) extends TcpRole - case class Inbound(connection: ActorRef, halfClose: Boolean, ioSettings: IOSettings, registerCallback: () ⇒ Unit) extends TcpRole + case class Inbound(connection: ActorRef, halfClose: Boolean, ioSettings: IOSettings, registerCallback: () => Unit) extends TcpRole /* * This is a *non-detached* design, i.e. this does not prefetch itself any of the inputs. It relies on downstream @@ -218,14 +218,14 @@ private[stream] object ConnectionSourceStage { override def preStart(): Unit = { setKeepGoing(true) role match { - case Inbound(conn, _, _, registerCallback) ⇒ + case Inbound(conn, _, _, registerCallback) => setHandler(bytesOut, readHandler) connection = conn getStageActor(connected).watch(connection) connection ! Register(self, keepOpenOnPeerClosed = true, useResumeWriting = false) registerCallback() pull(bytesIn) - case ob @ Outbound(manager, cmd, _, _, _) ⇒ + case ob @ Outbound(manager, cmd, _, _, _) => getStageActor(connecting(ob)).watch(manager) manager ! cmd } @@ -235,9 +235,9 @@ private[stream] object ConnectionSourceStage { val sender = evt._1 val msg = evt._2 msg match { - case Terminated(_) ⇒ fail(new StreamTcpException("The IO manager actor (TCP) has terminated. Stopping now.")) - case f @ CommandFailed(cmd) ⇒ fail(new StreamTcpException(s"Tcp command [$cmd] failed${f.causedByString}").initCause(f.cause.orNull)) - case c: Connected ⇒ + case Terminated(_) => fail(new StreamTcpException("The IO manager actor (TCP) has terminated. Stopping now.")) + case f @ CommandFailed(cmd) => fail(new StreamTcpException(s"Tcp command [$cmd] failed${f.causedByString}").initCause(f.cause.orNull)) + case c: Connected => role.asInstanceOf[Outbound].localAddressPromise.success(c.localAddress) connection = sender setHandler(bytesOut, readHandler) @@ -253,12 +253,12 @@ private[stream] object ConnectionSourceStage { private def connected(evt: (ActorRef, Any)): Unit = { val msg = evt._2 msg match { - case Received(data) ⇒ + case Received(data) => // Keep on reading even when closed. There is no "close-read-side" in TCP if (isClosed(bytesOut)) connection ! ResumeReading else push(bytesOut, data) - case WriteAck ⇒ + case WriteAck => if (writeBuffer.isEmpty) writeInProgress = false else { @@ -275,13 +275,13 @@ private[stream] object ConnectionSourceStage { if (!isClosed(bytesIn) && !hasBeenPulled(bytesIn)) pull(bytesIn) - case Terminated(_) ⇒ fail(new StreamTcpException("The connection actor has terminated. Stopping now.")) - case f @ CommandFailed(cmd) ⇒ fail(new StreamTcpException(s"Tcp command [$cmd] failed${f.causedByString}").initCause(f.cause.orNull)) - case ErrorClosed(cause) ⇒ fail(new StreamTcpException(s"The connection closed with error: $cause")) - case Aborted ⇒ fail(new StreamTcpException("The connection has been aborted")) - case Closed ⇒ completeStage() - case ConfirmedClosed ⇒ completeStage() - case PeerClosed ⇒ complete(bytesOut) + case Terminated(_) => fail(new StreamTcpException("The connection actor has terminated. Stopping now.")) + case f @ CommandFailed(cmd) => fail(new StreamTcpException(s"Tcp command [$cmd] failed${f.causedByString}").initCause(f.cause.orNull)) + case ErrorClosed(cause) => fail(new StreamTcpException(s"The connection closed with error: $cause")) + case Aborted => fail(new StreamTcpException("The connection has been aborted")) + case Closed => completeStage() + case ConfirmedClosed => completeStage() + case PeerClosed => complete(bytesOut) } } @@ -357,10 +357,10 @@ private[stream] object ConnectionSourceStage { } private def reportExceptionToPromise(ex: Throwable): Unit = role match { - case Outbound(_, _, localAddressPromise, _, _) ⇒ + case Outbound(_, _, localAddressPromise, _, _) => // Fail if has not been completed with an address earlier localAddressPromise.tryFailure(ex) - case _ ⇒ // do nothing... + case _ => // do nothing... } override def postStop(): Unit = reportExceptionToPromise(new StreamTcpException("Connection failed.")) @@ -373,7 +373,7 @@ private[stream] object ConnectionSourceStage { * INTERNAL API */ @InternalApi private[akka] class IncomingConnectionStage( - connection: ActorRef, remoteAddress: InetSocketAddress, halfClose: Boolean, ioSettings: IOSettings, registerCallback: () ⇒ Unit) + connection: ActorRef, remoteAddress: InetSocketAddress, halfClose: Boolean, ioSettings: IOSettings, registerCallback: () => Unit) extends GraphStage[FlowShape[ByteString, ByteString]] { import TcpConnectionStage._ @@ -417,8 +417,8 @@ private[stream] object ConnectionSourceStage { override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, Future[StreamTcp.OutgoingConnection]) = { // FIXME: A method like this would make soo much sense on Duration (i.e. toOption) val connTimeout = connectTimeout match { - case x: FiniteDuration ⇒ Some(x) - case _ ⇒ None + case x: FiniteDuration => Some(x) + case _ => None } val localAddressPromise = Promise[InetSocketAddress] @@ -440,14 +440,14 @@ private[stream] object ConnectionSourceStage { @InternalApi private[akka] object TcpIdleTimeout { def apply(idleTimeout: FiniteDuration, remoteAddress: Option[InetSocketAddress]): BidiFlow[ByteString, ByteString, ByteString, ByteString, NotUsed] = { val connectionToString = remoteAddress match { - case Some(address) ⇒ s" on connection to [$address]" - case _ ⇒ "" + case Some(address) => s" on connection to [$address]" + case _ => "" } val toNetTimeout: BidiFlow[ByteString, ByteString, ByteString, ByteString, NotUsed] = BidiFlow.fromFlows( Flow[ByteString].mapError { - case t: TimeoutException ⇒ + case t: TimeoutException => new TcpIdleTimeoutException(s"TCP idle-timeout encountered$connectionToString, no bytes passed in the last $idleTimeout", idleTimeout) }, Flow[ByteString] diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/TlsModule.scala b/akka-stream/src/main/scala/akka/stream/impl/io/TlsModule.scala index 345ad0b268..0ab0ada0e4 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/TlsModule.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/TlsModule.scala @@ -24,8 +24,8 @@ import scala.util.Try cipherIn: Inlet[ByteString], cipherOut: Outlet[ByteString], shape: BidiShape[SslTlsOutbound, ByteString, ByteString, SslTlsInbound], attributes: Attributes, - createSSLEngine: ActorSystem ⇒ SSLEngine, // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 - verifySession: (ActorSystem, SSLSession) ⇒ Try[Unit], // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 + createSSLEngine: ActorSystem => SSLEngine, // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 + verifySession: (ActorSystem, SSLSession) => Try[Unit], // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 closing: TLSClosing) extends AtomicModule[BidiShape[SslTlsOutbound, ByteString, ByteString, SslTlsInbound], NotUsed] { @@ -42,8 +42,8 @@ import scala.util.Try @InternalApi private[stream] object TlsModule { def apply( attributes: Attributes, - createSSLEngine: ActorSystem ⇒ SSLEngine, // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 - verifySession: (ActorSystem, SSLSession) ⇒ Try[Unit], // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 + createSSLEngine: ActorSystem => SSLEngine, // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 + verifySession: (ActorSystem, SSLSession) => Try[Unit], // ActorSystem is only needed to support the AkkaSSLConfig legacy, see #21753 closing: TLSClosing): TlsModule = { val name = attributes.nameOrDefault(s"StreamTls()") val cipherIn = Inlet[ByteString](s"$name.cipherIn") diff --git a/akka-stream/src/main/scala/akka/stream/impl/io/compression/CompressionUtils.scala b/akka-stream/src/main/scala/akka/stream/impl/io/compression/CompressionUtils.scala index 6bc15d9fc7..ae6a7b64db 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/io/compression/CompressionUtils.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/io/compression/CompressionUtils.scala @@ -17,7 +17,7 @@ import akka.util.ByteString /** * Creates a flow from a compressor constructor. */ - def compressorFlow(newCompressor: () ⇒ Compressor): Flow[ByteString, ByteString, NotUsed] = + def compressorFlow(newCompressor: () => Compressor): Flow[ByteString, ByteString, NotUsed] = Flow.fromGraph { new SimpleLinearGraphStage[ByteString] { override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { diff --git a/akka-stream/src/main/scala/akka/stream/impl/streamref/SinkRefImpl.scala b/akka-stream/src/main/scala/akka/stream/impl/streamref/SinkRefImpl.scala index 49b55f5ce1..e23e8a909a 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/streamref/SinkRefImpl.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/streamref/SinkRefImpl.scala @@ -21,7 +21,7 @@ import scala.util.{ Failure, Success, Try } @InternalApi private[stream] final case class SinkRefImpl[In](initialPartnerRef: ActorRef) extends SinkRef[In] { override def sink(): Sink[In, NotUsed] = - Sink.fromGraph(new SinkRefStageImpl[In](OptionVal.Some(initialPartnerRef))).mapMaterializedValue(_ ⇒ NotUsed) + Sink.fromGraph(new SinkRefStageImpl[In](OptionVal.Some(initialPartnerRef))).mapMaterializedValue(_ => NotUsed) } /** @@ -40,8 +40,8 @@ private[stream] final class SinkRefStageImpl[In] private[akka] ( private def initialRefName: String = initialPartnerRef match { - case OptionVal.Some(ref) ⇒ ref.toString - case OptionVal.None ⇒ "" + case OptionVal.Some(ref) => ref.toString + case OptionVal.None => "" } override def createLogicAndMaterializedValue(inheritedAttributes: Attributes) = { @@ -66,8 +66,8 @@ private[stream] final class SinkRefStageImpl[In] private[akka] ( private var partnerRef: OptionVal[ActorRef] = OptionVal.None private def getPartnerRef: ActorRef = partnerRef match { - case OptionVal.Some(ref) ⇒ ref - case OptionVal.None ⇒ throw TargetRefNotInitializedYetException() + case OptionVal.Some(ref) => ref + case OptionVal.None => throw TargetRefNotInitializedYetException() } val SubscriptionTimeoutTimerKey = "SubscriptionTimeoutKey" @@ -88,12 +88,12 @@ private[stream] final class SinkRefStageImpl[In] private[akka] ( self = getStageActor(initialReceive) initialPartnerRef match { - case OptionVal.Some(ref) ⇒ + case OptionVal.Some(ref) => // this will set the `partnerRef` observeAndValidateSender(ref, "Illegal initialPartnerRef! This may be a bug, please report your " + "usage and complete stack trace on the issue tracker: https://github.com/akka/akka") tryPull() - case OptionVal.None ⇒ + case OptionVal.None => // only schedule timeout timer if partnerRef has not been resolved yet (i.e. if this instance of the Actor // has not been provided with a valid initialPartnerRef) scheduleOnce(SubscriptionTimeoutTimerKey, subscriptionTimeout.timeout) @@ -104,20 +104,20 @@ private[stream] final class SinkRefStageImpl[In] private[akka] ( promise.success(SourceRefImpl(self.ref)) } - lazy val initialReceive: ((ActorRef, Any)) ⇒ Unit = { - case (_, Terminated(ref)) ⇒ + lazy val initialReceive: ((ActorRef, Any)) => Unit = { + case (_, Terminated(ref)) => if (ref == getPartnerRef) finishedWithAwaitingPartnerTermination match { - case OptionVal.Some(Failure(ex)) ⇒ + case OptionVal.Some(Failure(ex)) => failStage(ex) - case OptionVal.Some(_ /* known to be Success*/ ) ⇒ + case OptionVal.Some(_ /* known to be Success*/ ) => completeStage() // other side has terminated (in response to a completion message) so we can safely terminate - case OptionVal.None ⇒ + case OptionVal.None => failStage(RemoteStreamRefActorTerminatedException(s"Remote target receiver of data $partnerRef terminated. " + s"Local stream terminating, message loss (on remote side) may have happened.")) } - case (sender, StreamRefsProtocol.CumulativeDemand(d)) ⇒ + case (sender, StreamRefsProtocol.CumulativeDemand(d)) => // the other side may attempt to "double subscribe", which we want to fail eagerly since we're 1:1 pairings observeAndValidateSender(sender, "Illegal sender for CumulativeDemand") @@ -142,7 +142,7 @@ private[stream] final class SinkRefStageImpl[In] private[akka] ( } override protected def onTimer(timerKey: Any): Unit = timerKey match { - case SubscriptionTimeoutTimerKey ⇒ + case SubscriptionTimeoutTimerKey => val ex = StreamRefSubscriptionTimeoutException( // we know the future has been competed by now, since it is in preStart s"[$stageActorName] Remote side did not subscribe (materialize) handed out Source reference [${promise.future.value}], " + @@ -159,12 +159,12 @@ private[stream] final class SinkRefStageImpl[In] private[akka] ( override def onUpstreamFailure(ex: Throwable): Unit = { partnerRef match { - case OptionVal.Some(ref) ⇒ + case OptionVal.Some(ref) => ref ! StreamRefsProtocol.RemoteStreamFailure(ex.getMessage) finishedWithAwaitingPartnerTermination = OptionVal(Failure(ex)) setKeepGoing(true) // we will terminate once partner ref has Terminated (to avoid racing Terminated with completion message) - case _ ⇒ + case _ => completedBeforeRemoteConnected = OptionVal(scala.util.Failure(ex)) // not terminating on purpose, since other side may subscribe still and then we want to fail it // the stage will be terminated either by timeout, or by the handling in `observeAndValidateSender` @@ -174,11 +174,11 @@ private[stream] final class SinkRefStageImpl[In] private[akka] ( override def onUpstreamFinish(): Unit = partnerRef match { - case OptionVal.Some(ref) ⇒ + case OptionVal.Some(ref) => ref ! StreamRefsProtocol.RemoteStreamCompleted(remoteCumulativeDemandConsumed) finishedWithAwaitingPartnerTermination = OptionVal(Success(Done)) setKeepGoing(true) // we will terminate once partner ref has Terminated (to avoid racing Terminated with completion message) - case _ ⇒ + case _ => completedBeforeRemoteConnected = OptionVal(scala.util.Success(Done)) // not terminating on purpose, since other side may subscribe still and then we want to complete it setKeepGoing(true) @@ -193,19 +193,19 @@ private[stream] final class SinkRefStageImpl[In] private[akka] ( self.watch(partner) completedBeforeRemoteConnected match { - case OptionVal.Some(scala.util.Failure(ex)) ⇒ + case OptionVal.Some(scala.util.Failure(ex)) => log.warning("Stream already terminated with exception before remote side materialized, sending failure: {}", ex) partner ! StreamRefsProtocol.RemoteStreamFailure(ex.getMessage) finishedWithAwaitingPartnerTermination = OptionVal(Failure(ex)) setKeepGoing(true) // we will terminate once partner ref has Terminated (to avoid racing Terminated with completion message) - case OptionVal.Some(scala.util.Success(Done)) ⇒ + case OptionVal.Some(scala.util.Success(Done)) => log.warning("Stream already completed before remote side materialized, failing now.") partner ! StreamRefsProtocol.RemoteStreamCompleted(remoteCumulativeDemandConsumed) finishedWithAwaitingPartnerTermination = OptionVal(Success(Done)) setKeepGoing(true) // we will terminate once partner ref has Terminated (to avoid racing Terminated with completion message) - case OptionVal.None ⇒ + case OptionVal.None => if (partner != getPartnerRef) { val ex = InvalidPartnerActorException(partner, getPartnerRef, failureMsg) partner ! StreamRefsProtocol.RemoteStreamFailure(ex.getMessage) diff --git a/akka-stream/src/main/scala/akka/stream/impl/streamref/SourceRefImpl.scala b/akka-stream/src/main/scala/akka/stream/impl/streamref/SourceRefImpl.scala index cf9dafc091..601521a946 100644 --- a/akka-stream/src/main/scala/akka/stream/impl/streamref/SourceRefImpl.scala +++ b/akka-stream/src/main/scala/akka/stream/impl/streamref/SourceRefImpl.scala @@ -21,7 +21,7 @@ import scala.concurrent.{ Future, Promise } @InternalApi private[stream] final case class SourceRefImpl[T](initialPartnerRef: ActorRef) extends SourceRef[T] { def source: Source[T, NotUsed] = - Source.fromGraph(new SourceRefStageImpl(OptionVal.Some(initialPartnerRef))).mapMaterializedValue(_ ⇒ NotUsed) + Source.fromGraph(new SourceRefStageImpl(OptionVal.Some(initialPartnerRef))).mapMaterializedValue(_ => NotUsed) } /** @@ -33,15 +33,15 @@ private[stream] final case class SourceRefImpl[T](initialPartnerRef: ActorRef) e @InternalApi private[stream] final class SourceRefStageImpl[Out]( val initialPartnerRef: OptionVal[ActorRef] -) extends GraphStageWithMaterializedValue[SourceShape[Out], Future[SinkRef[Out]]] { stage ⇒ +) extends GraphStageWithMaterializedValue[SourceShape[Out], Future[SinkRef[Out]]] { stage => val out: Outlet[Out] = Outlet[Out](s"${Logging.simpleName(getClass)}.out") override def shape = SourceShape.of(out) private def initialRefName = initialPartnerRef match { - case OptionVal.Some(ref) ⇒ ref.toString - case _ ⇒ "" + case OptionVal.Some(ref) => ref.toString + case _ => "" } override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, Future[SinkRef[Out]]) = { @@ -127,7 +127,7 @@ private[stream] final class SourceRefStageImpl[Out]( scheduleOnce(DemandRedeliveryTimerKey, settings.demandRedeliveryInterval) override protected def onTimer(timerKey: Any): Unit = timerKey match { - case SubscriptionTimeoutTimerKey ⇒ + case SubscriptionTimeoutTimerKey => val ex = StreamRefSubscriptionTimeoutException( // we know the future has been competed by now, since it is in preStart s"[$stageActorName] Remote side did not subscribe (materialize) handed out Sink reference [${promise.future.value}]," + @@ -135,25 +135,25 @@ private[stream] final class SourceRefStageImpl[Out]( throw ex // this will also log the exception, unlike failStage; this should fail rarely, but would be good to have it "loud" - case DemandRedeliveryTimerKey ⇒ + case DemandRedeliveryTimerKey => log.debug("[{}] Scheduled re-delivery of demand until [{}]", stageActorName, localCumulativeDemand) getPartnerRef ! StreamRefsProtocol.CumulativeDemand(localCumulativeDemand) scheduleDemandRedelivery() - case TerminationDeadlineTimerKey ⇒ + case TerminationDeadlineTimerKey => failStage(RemoteStreamRefActorTerminatedException(s"Remote partner [$partnerRef] has terminated unexpectedly and no clean completion/failure message was received " + "(possible reasons: network partition or subscription timeout triggered termination of partner). Tearing down.")) } - lazy val initialReceive: ((ActorRef, Any)) ⇒ Unit = { - case (sender, msg @ StreamRefsProtocol.OnSubscribeHandshake(remoteRef)) ⇒ + lazy val initialReceive: ((ActorRef, Any)) => Unit = { + case (sender, msg @ StreamRefsProtocol.OnSubscribeHandshake(remoteRef)) => cancelTimer(SubscriptionTimeoutTimerKey) observeAndValidateSender(remoteRef, "Illegal sender in SequencedOnNext") log.debug("[{}] Received handshake {} from {}", stageActorName, msg, sender) triggerCumulativeDemand() - case (sender, msg @ StreamRefsProtocol.SequencedOnNext(seqNr, payload: Out @unchecked)) ⇒ + case (sender, msg @ StreamRefsProtocol.SequencedOnNext(seqNr, payload: Out @unchecked)) => observeAndValidateSender(sender, "Illegal sender in SequencedOnNext") observeAndValidateSequenceNr(seqNr, "Illegal sequence nr in SequencedOnNext") log.debug("[{}] Received seq {} from {}", stageActorName, msg, sender) @@ -161,7 +161,7 @@ private[stream] final class SourceRefStageImpl[Out]( onReceiveElement(payload) triggerCumulativeDemand() - case (sender, StreamRefsProtocol.RemoteStreamCompleted(seqNr)) ⇒ + case (sender, StreamRefsProtocol.RemoteStreamCompleted(seqNr)) => observeAndValidateSender(sender, "Illegal sender in RemoteSinkCompleted") observeAndValidateSequenceNr(seqNr, "Illegal sequence nr in RemoteSinkCompleted") log.debug("[{}] The remote stream has completed, completing as well...", stageActorName) @@ -170,22 +170,22 @@ private[stream] final class SourceRefStageImpl[Out]( completed = true tryPush() - case (sender, StreamRefsProtocol.RemoteStreamFailure(reason)) ⇒ + case (sender, StreamRefsProtocol.RemoteStreamFailure(reason)) => observeAndValidateSender(sender, "Illegal sender in RemoteSinkFailure") log.warning("[{}] The remote stream has failed, failing (reason: {})", stageActorName, reason) self.unwatch(sender) failStage(RemoteStreamRefActorTerminatedException(s"Remote stream (${sender.path}) failed, reason: $reason")) - case (_, Terminated(ref)) ⇒ + case (_, Terminated(ref)) => partnerRef match { - case OptionVal.Some(`ref`) ⇒ + case OptionVal.Some(`ref`) => // we need to start a delayed shutdown in case we were network partitioned and the final signal complete/fail // will never reach us; so after the given timeout we need to forcefully terminate this side of the stream ref // the other (sending) side terminates by default once it gets a Terminated signal so no special handling is needed there. scheduleOnce(TerminationDeadlineTimerKey, settings.finalTerminationSignalDeadline) - case _ ⇒ + case _ => // this should not have happened! It should be impossible that we watched some other actor failStage(RemoteStreamRefActorTerminatedException(s"Received UNEXPECTED Terminated($ref) message! " + s"This actor was NOT our trusted remote partner, which was: $getPartnerRef. Tearing down.")) @@ -214,12 +214,12 @@ private[stream] final class SourceRefStageImpl[Out]( /** @throws InvalidPartnerActorException when partner ref is invalid */ def observeAndValidateSender(partner: ActorRef, msg: String): Unit = partnerRef match { - case OptionVal.None ⇒ + case OptionVal.None => log.debug("Received first message from {}, assuming it to be the remote partner for this stage", partner) partnerRef = OptionVal(partner) self.watch(partner) - case OptionVal.Some(ref) ⇒ + case OptionVal.Some(ref) => if (partner != ref) { val ex = InvalidPartnerActorException(partner, getPartnerRef, msg) partner ! StreamRefsProtocol.RemoteStreamFailure(ex.getMessage) diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/BidiFlow.scala b/akka-stream/src/main/scala/akka/stream/javadsl/BidiFlow.scala index 87fad69bc8..6ea03a4185 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/BidiFlow.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/BidiFlow.scala @@ -23,8 +23,8 @@ object BidiFlow { */ def fromGraph[I1, O1, I2, O2, M](g: Graph[BidiShape[I1, O1, I2, O2], M]): BidiFlow[I1, O1, I2, O2, M] = g match { - case bidi: BidiFlow[I1, O1, I2, O2, M] ⇒ bidi - case other ⇒ new BidiFlow(scaladsl.BidiFlow.fromGraph(other)) + case bidi: BidiFlow[I1, O1, I2, O2, M] => bidi + case other => new BidiFlow(scaladsl.BidiFlow.fromGraph(other)) } /** diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/Flow.scala b/akka-stream/src/main/scala/akka/stream/javadsl/Flow.scala index 37253d2c37..dfc7d1620d 100755 --- a/akka-stream/src/main/scala/akka/stream/javadsl/Flow.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/Flow.scala @@ -32,10 +32,10 @@ object Flow { def create[T](): javadsl.Flow[T, T, NotUsed] = fromGraph(scaladsl.Flow[T]) def fromProcessor[I, O](processorFactory: function.Creator[Processor[I, O]]): javadsl.Flow[I, O, NotUsed] = - new Flow(scaladsl.Flow.fromProcessor(() ⇒ processorFactory.create())) + new Flow(scaladsl.Flow.fromProcessor(() => processorFactory.create())) def fromProcessorMat[I, O, Mat](processorFactory: function.Creator[Pair[Processor[I, O], Mat]]): javadsl.Flow[I, O, Mat] = - new Flow(scaladsl.Flow.fromProcessorMat { () ⇒ + new Flow(scaladsl.Flow.fromProcessorMat { () => val javaPair = processorFactory.create() (javaPair.first, javaPair.second) }) @@ -55,8 +55,8 @@ object Flow { */ def fromGraph[I, O, M](g: Graph[FlowShape[I, O], M]): Flow[I, O, M] = g match { - case f: Flow[I, O, M] ⇒ f - case other ⇒ new Flow(scaladsl.Flow.fromGraph(other)) + case f: Flow[I, O, M] => f + case other => new Flow(scaladsl.Flow.fromGraph(other)) } /** @@ -227,8 +227,8 @@ object Flow { def lazyInit[I, O, M](flowFactory: function.Function[I, CompletionStage[Flow[I, O, M]]], fallback: function.Creator[M]): Flow[I, O, M] = { import scala.compat.java8.FutureConverters._ val sflow = scaladsl.Flow - .fromGraph(new LazyFlow[I, O, M](t ⇒ flowFactory.apply(t).toScala.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext))) - .mapMaterializedValue(_ ⇒ fallback.create()) + .fromGraph(new LazyFlow[I, O, M](t => flowFactory.apply(t).toScala.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext))) + .mapMaterializedValue(_ => fallback.create()) new Flow(sflow) } @@ -251,8 +251,8 @@ object Flow { def lazyInitAsync[I, O, M](flowFactory: function.Creator[CompletionStage[Flow[I, O, M]]]): Flow[I, O, CompletionStage[Optional[M]]] = { import scala.compat.java8.FutureConverters._ - val sflow = scaladsl.Flow.lazyInitAsync(() ⇒ flowFactory.create().toScala.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext)) - .mapMaterializedValue(fut ⇒ fut.map(_.fold[Optional[M]](Optional.empty())(m ⇒ Optional.ofNullable(m)))(ExecutionContexts.sameThreadExecutionContext).toJava) + val sflow = scaladsl.Flow.lazyInitAsync(() => flowFactory.create().toScala.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext)) + .mapMaterializedValue(fut => fut.map(_.fold[Optional[M]](Optional.empty())(m => Optional.ofNullable(m)))(ExecutionContexts.sameThreadExecutionContext).toJava) new Flow(sflow) } /** @@ -532,7 +532,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * '''Cancels when''' downstream cancels */ def mapConcat[T](f: function.Function[Out, java.lang.Iterable[T]]): javadsl.Flow[In, T, Mat] = - new Flow(delegate.mapConcat { elem ⇒ Util.immutableSeq(f(elem)) }) + new Flow(delegate.mapConcat { elem => Util.immutableSeq(f(elem)) }) /** * Transform each input element into an `Iterable` of output elements that is @@ -561,9 +561,9 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * '''Cancels when''' downstream cancels */ def statefulMapConcat[T](f: function.Creator[function.Function[Out, java.lang.Iterable[T]]]): javadsl.Flow[In, T, Mat] = - new Flow(delegate.statefulMapConcat { () ⇒ + new Flow(delegate.statefulMapConcat { () => val fun = f.create() - elem ⇒ Util.immutableSeq(fun(elem)) + elem => Util.immutableSeq(fun(elem)) }) /** @@ -596,7 +596,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * @see [[#mapAsyncUnordered]] */ def mapAsync[T](parallelism: Int, f: function.Function[Out, CompletionStage[T]]): javadsl.Flow[In, T, Mat] = - new Flow(delegate.mapAsync(parallelism)(x ⇒ f(x).toScala)) + new Flow(delegate.mapAsync(parallelism)(x => f(x).toScala)) /** * Transform this stream by applying the given function to each of the elements @@ -630,7 +630,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * @see [[#mapAsync]] */ def mapAsyncUnordered[T](parallelism: Int, f: function.Function[Out, CompletionStage[T]]): javadsl.Flow[In, T, Mat] = - new Flow(delegate.mapAsyncUnordered(parallelism)(x ⇒ f(x).toScala)) + new Flow(delegate.mapAsyncUnordered(parallelism)(x => f(x).toScala)) /** * Use the `ask` pattern to send a request-reply message to the target `ref` actor. @@ -923,7 +923,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * See also [[FlowOps.scan]] */ def scanAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): javadsl.Flow[In, T, Mat] = - new Flow(delegate.scanAsync(zero) { (out, in) ⇒ f(out, in).toScala }) + new Flow(delegate.scanAsync(zero) { (out, in) => f(out, in).toScala }) /** * Similar to `scan` but only emits its result when the upstream completes, @@ -970,7 +970,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * * '''Cancels when''' downstream cancels */ - def foldAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): javadsl.Flow[In, T, Mat] = new Flow(delegate.foldAsync(zero) { (out, in) ⇒ f(out, in).toScala }) + def foldAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): javadsl.Flow[In, T, Mat] = new Flow(delegate.foldAsync(zero) { (out, in) => f(out, in).toScala }) /** * Similar to `fold` but uses first element as zero element. @@ -1344,7 +1344,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr @deprecated("Use recoverWithRetries instead.", "2.4.4") def recover(clazz: Class[_ <: Throwable], supplier: Supplier[Out]): javadsl.Flow[In, Out, Mat] = recover { - case elem if clazz.isInstance(elem) ⇒ supplier.get() + case elem if clazz.isInstance(elem) => supplier.get() } /** @@ -1414,7 +1414,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr */ def recoverWith(clazz: Class[_ <: Throwable], supplier: Supplier[Graph[SourceShape[Out], NotUsed]]): javadsl.Flow[In, Out, Mat] = recoverWith { - case elem if clazz.isInstance(elem) ⇒ supplier.get() + case elem if clazz.isInstance(elem) => supplier.get() } /** @@ -1473,7 +1473,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr */ def recoverWithRetries(attempts: Int, clazz: Class[_ <: Throwable], supplier: Supplier[Graph[SourceShape[Out], NotUsed]]): javadsl.Flow[In, Out, Mat] = recoverWithRetries(attempts, { - case elem if clazz.isInstance(elem) ⇒ supplier.get() + case elem if clazz.isInstance(elem) => supplier.get() }) /** @@ -1688,7 +1688,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * @see [[#extrapolate]] */ def expand[U](expander: function.Function[Out, java.util.Iterator[U]]): javadsl.Flow[In, U, Mat] = - new Flow(delegate.expand(in ⇒ expander(in).asScala)) + new Flow(delegate.expand(in => expander(in).asScala)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -1715,7 +1715,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * @see [[#expand]] */ def extrapolate(extrapolator: function.Function[Out @uncheckedVariance, java.util.Iterator[Out @uncheckedVariance]]): javadsl.Flow[In, Out, Mat] = - new Flow(delegate.extrapolate(in ⇒ extrapolator(in).asScala)) + new Flow(delegate.extrapolate(in => extrapolator(in).asScala)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -1743,7 +1743,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * @see [[#expand]] */ def extrapolate(extrapolator: function.Function[Out @uncheckedVariance, java.util.Iterator[Out @uncheckedVariance]], initial: Out @uncheckedVariance): javadsl.Flow[In, Out, Mat] = - new Flow(delegate.extrapolate(in ⇒ extrapolator(in).asScala, Some(initial))) + new Flow(delegate.extrapolate(in => extrapolator(in).asScala, Some(initial))) /** * Adds a fixed size buffer in the flow that allows to store elements from a faster upstream until it becomes full. @@ -1791,7 +1791,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * '''Cancels when''' downstream cancels or substream cancels */ def prefixAndTail(n: Int): javadsl.Flow[In, akka.japi.Pair[java.util.List[Out], javadsl.Source[Out, NotUsed]], Mat] = - new Flow(delegate.prefixAndTail(n).map { case (taken, tail) ⇒ akka.japi.Pair(taken.asJava, tail.asJava) }) + new Flow(delegate.prefixAndTail(n).map { case (taken, tail) => akka.japi.Pair(taken.asJava, tail.asJava) }) /** * This operation demultiplexes the incoming stream into separate output @@ -2004,7 +2004,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * '''Cancels when''' downstream cancels */ def flatMapConcat[T, M](f: function.Function[Out, _ <: Graph[SourceShape[T], M]]): Flow[In, T, Mat] = - new Flow(delegate.flatMapConcat[T, M](x ⇒ f(x))) + new Flow(delegate.flatMapConcat[T, M](x => f(x))) /** * Transform each input element into a `Source` of output elements that is @@ -2020,7 +2020,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * '''Cancels when''' downstream cancels */ def flatMapMerge[T, M](breadth: Int, f: function.Function[Out, _ <: Graph[SourceShape[T], M]]): Flow[In, T, Mat] = - new Flow(delegate.flatMapMerge(breadth, o ⇒ f(o))) + new Flow(delegate.flatMapMerge(breadth, o => f(o))) /** * Concatenate the given [[Source]] to this [[Flow]], meaning that once this @@ -2576,7 +2576,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * '''Cancels when''' downstream cancels */ def zipWithIndex: Flow[In, Pair[Out, java.lang.Long], Mat] = - new Flow(delegate.zipWithIndex.map { case (elem, index) ⇒ Pair[Out, java.lang.Long](elem, index) }) + new Flow(delegate.zipWithIndex.map { case (elem, index) => Pair[Out, java.lang.Long](elem, index) }) /** * If the first element has not passed through this operator before the provided timeout, the stream is failed @@ -2730,7 +2730,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr @Deprecated @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def keepAlive(maxIdle: FiniteDuration, injectedElem: function.Creator[Out]): javadsl.Flow[In, Out, Mat] = - new Flow(delegate.keepAlive(maxIdle, () ⇒ injectedElem.create())) + new Flow(delegate.keepAlive(maxIdle, () => injectedElem.create())) /** * Injects additional elements if upstream does not emit for a configured amount of time. In other words, this @@ -3074,7 +3074,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * downstream. */ def watchTermination[M]()(matF: function.Function2[Mat, CompletionStage[Done], M]): javadsl.Flow[In, Out, M] = - new Flow(delegate.watchTermination()((left, right) ⇒ matF(left, right.toJava))) + new Flow(delegate.watchTermination()((left, right) => matF(left, right.toJava))) /** * Materializes to `FlowMonitor[Out]` that allows monitoring of the current flow. All events are propagated @@ -3212,7 +3212,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * '''Cancels when''' downstream cancels */ def log(name: String, extract: function.Function[Out, Any], log: LoggingAdapter): javadsl.Flow[In, Out, Mat] = - new Flow(delegate.log(name, e ⇒ extract.apply(e))(log)) + new Flow(delegate.log(name, e => extract.apply(e))(log)) /** * Logs elements flowing through the stream as well as completion and erroring. @@ -3295,7 +3295,7 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr */ @ApiMayChange def asFlowWithContext[U, CtxU, CtxOut](collapseContext: function.Function2[U, CtxU, In], extractContext: function.Function[Out, CtxOut]): FlowWithContext[U, CtxU, Out, CtxOut, Mat] = - this.asScala.asFlowWithContext((x: U, c: CtxU) ⇒ collapseContext.apply(x, c))(x ⇒ extractContext.apply(x)).asJava + this.asScala.asFlowWithContext((x: U, c: CtxU) => collapseContext.apply(x, c))(x => extractContext.apply(x)).asJava } @@ -3306,8 +3306,8 @@ object RunnableGraph { */ def fromGraph[Mat](graph: Graph[ClosedShape, Mat]): RunnableGraph[Mat] = graph match { - case r: RunnableGraph[Mat] ⇒ r - case other ⇒ new RunnableGraphAdapter[Mat](scaladsl.RunnableGraph.fromGraph(graph)) + case r: RunnableGraph[Mat] => r + case other => new RunnableGraphAdapter[Mat](scaladsl.RunnableGraph.fromGraph(graph)) } /** INTERNAL API */ diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/FlowWithContext.scala b/akka-stream/src/main/scala/akka/stream/javadsl/FlowWithContext.scala index 116098923f..fa33a4abf2 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/FlowWithContext.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/FlowWithContext.scala @@ -30,7 +30,7 @@ object FlowWithContext { * Creates a FlowWithContext from a regular flow that operates on `Pair` elements. */ def fromPairs[In, CtxIn, Out, CtxOut, Mat](under: Flow[Pair[In, CtxIn], Pair[Out, CtxOut], Mat]): FlowWithContext[In, CtxIn, Out, CtxOut, Mat] = { - new FlowWithContext(scaladsl.FlowWithContext.fromTuples(scaladsl.Flow[(In, CtxIn)].map { case (i, c) ⇒ Pair(i, c) }.viaMat(under.asScala.map(_.toScala))(scaladsl.Keep.right))) + new FlowWithContext(scaladsl.FlowWithContext.fromTuples(scaladsl.Flow[(In, CtxIn)].map { case (i, c) => Pair(i, c) }.viaMat(under.asScala.map(_.toScala))(scaladsl.Keep.right))) } } @@ -75,7 +75,7 @@ final class FlowWithContext[-In, -CtxIn, +Out, +CtxOut, +Mat](delegate: scaladsl scaladsl.Flow[Pair[In, CtxIn]] .map(_.toScala) .viaMat(delegate.asFlow)(scaladsl.Keep.right) - .map { case (o, c) ⇒ Pair(o, c) } + .map { case (o, c) => Pair(o, c) } .asJava // remaining operations in alphabetic order @@ -129,7 +129,7 @@ final class FlowWithContext[-In, -CtxIn, +Out, +CtxOut, +Mat](delegate: scaladsl viaScala(_.map(f.apply)) def mapAsync[Out2](parallelism: Int, f: function.Function[Out, CompletionStage[Out2]]): FlowWithContext[In, CtxIn, Out2, CtxOut, Mat] = - viaScala(_.mapAsync[Out2](parallelism)(o ⇒ f.apply(o).toScala)) + viaScala(_.mapAsync[Out2](parallelism)(o => f.apply(o).toScala)) /** * Context-preserving variant of [[akka.stream.javadsl.Flow.mapConcat]]. @@ -160,7 +160,7 @@ final class FlowWithContext[-In, -CtxIn, +Out, +CtxOut, +Mat](delegate: scaladsl * @see [[akka.stream.javadsl.Flow.mapConcat]] */ def mapConcat[Out2](f: function.Function[Out, _ <: java.lang.Iterable[Out2]]): FlowWithContext[In, CtxIn, Out2, CtxOut, Mat] = - viaScala(_.mapConcat(elem ⇒ Util.immutableSeq(f.apply(elem)))) + viaScala(_.mapConcat(elem => Util.immutableSeq(f.apply(elem)))) /** * Apply the given function to each context element (leaving the data elements unchanged). @@ -185,7 +185,7 @@ final class FlowWithContext[-In, -CtxIn, +Out, +CtxOut, +Mat](delegate: scaladsl * @see [[akka.stream.javadsl.Flow.log]] */ def log(name: String, extract: function.Function[Out, Any], log: LoggingAdapter): FlowWithContext[In, CtxIn, Out, CtxOut, Mat] = - viaScala(_.log(name, e ⇒ extract.apply(e))(log)) + viaScala(_.log(name, e => extract.apply(e))(log)) /** * Context-preserving variant of [[akka.stream.javadsl.Flow.log]]. @@ -213,6 +213,6 @@ final class FlowWithContext[-In, -CtxIn, +Out, +CtxOut, +Mat](delegate: scaladsl def asScala: scaladsl.FlowWithContext[In, CtxIn, Out, CtxOut, Mat] = delegate - private[this] def viaScala[In2, CtxIn2, Out2, CtxOut2, Mat2](f: scaladsl.FlowWithContext[In, CtxIn, Out, CtxOut, Mat] ⇒ scaladsl.FlowWithContext[In2, CtxIn2, Out2, CtxOut2, Mat2]): FlowWithContext[In2, CtxIn2, Out2, CtxOut2, Mat2] = + private[this] def viaScala[In2, CtxIn2, Out2, CtxOut2, Mat2](f: scaladsl.FlowWithContext[In, CtxIn, Out, CtxOut, Mat] => scaladsl.FlowWithContext[In2, CtxIn2, Out2, CtxOut2, Mat2]): FlowWithContext[In2, CtxIn2, Out2, CtxOut2, Mat2] = new FlowWithContext(f(delegate)) } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/Framing.scala b/akka-stream/src/main/scala/akka/stream/javadsl/Framing.scala index 009ec3ef00..692584e235 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/Framing.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/Framing.scala @@ -124,7 +124,7 @@ object Framing { fieldOffset, maximumFrameLength, byteOrder, - (a: Array[Byte], s: Int) ⇒ computeFrameSize.apply(a, s) + (a: Array[Byte], s: Int) => computeFrameSize.apply(a, s) ).asJava /** diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/Graph.scala b/akka-stream/src/main/scala/akka/stream/javadsl/Graph.scala index c8a05c42a3..4fc9c7c0be 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/Graph.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/Graph.scala @@ -415,7 +415,7 @@ object ZipN { object ZipWithN { def create[A, O](zipper: function.Function[java.util.List[A], O], n: Int): Graph[UniformFanInShape[A, O], NotUsed] = { import scala.collection.JavaConverters._ - scaladsl.ZipWithN[A, O](seq ⇒ zipper.apply(seq.asJava))(n) + scaladsl.ZipWithN[A, O](seq => zipper.apply(seq.asJava))(n) } } @@ -498,14 +498,14 @@ object GraphDSL extends GraphCreate { buildBlock: function.Function2[GraphDSL.Builder[java.util.List[M]], java.util.List[IS], S]): Graph[S, java.util.List[M]] = { require(!graphs.isEmpty, "The input list must have one or more Graph elements") val gbuilder = builder[java.util.List[M]]() - val toList = (m1: M) ⇒ new util.ArrayList(util.Arrays.asList(m1)) - val combine = (s: java.util.List[M], m2: M) ⇒ { + val toList = (m1: M) => new util.ArrayList(util.Arrays.asList(m1)) + val combine = (s: java.util.List[M], m2: M) => { val newList = new util.ArrayList(s) newList.add(m2) newList } val sListH = gbuilder.delegate.add(graphs.get(0), toList) - val sListT = graphs.subList(1, graphs.size()).asScala.map(g ⇒ gbuilder.delegate.add(g, combine)).asJava + val sListT = graphs.subList(1, graphs.size()).asScala.map(g => gbuilder.delegate.add(g, combine)).asJava val s = buildBlock(gbuilder, { val newList = new util.ArrayList[IS] newList.add(sListH) @@ -515,7 +515,7 @@ object GraphDSL extends GraphCreate { new GenericGraph(s, gbuilder.delegate.result(s)) } - final class Builder[+Mat]()(private[stream] implicit val delegate: scaladsl.GraphDSL.Builder[Mat]) { self ⇒ + final class Builder[+Mat]()(private[stream] implicit val delegate: scaladsl.GraphDSL.Builder[Mat]) { self => import akka.stream.scaladsl.GraphDSL.Implicits._ /** diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/Hub.scala b/akka-stream/src/main/scala/akka/stream/javadsl/Hub.scala index ec71ccc6c4..07798e2afa 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/Hub.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/Hub.scala @@ -138,9 +138,9 @@ object PartitionHub { */ @ApiMayChange def ofStateful[T](clazz: Class[T], partitioner: Supplier[ToLongBiFunction[ConsumerInfo, T]], startAfterNrOfConsumers: Int, bufferSize: Int): Sink[T, Source[T, NotUsed]] = { - val p: () ⇒ (akka.stream.scaladsl.PartitionHub.ConsumerInfo, T) ⇒ Long = () ⇒ { + val p: () => (akka.stream.scaladsl.PartitionHub.ConsumerInfo, T) => Long = () => { val f = partitioner.get() - (info, elem) ⇒ f.applyAsLong(info, elem) + (info, elem) => f.applyAsLong(info, elem) } akka.stream.scaladsl.PartitionHub.statefulSink[T](p, startAfterNrOfConsumers, bufferSize) .mapMaterializedValue(_.asJava) @@ -183,7 +183,7 @@ object PartitionHub { @ApiMayChange def of[T](clazz: Class[T], partitioner: BiFunction[Integer, T, Integer], startAfterNrOfConsumers: Int, bufferSize: Int): Sink[T, Source[T, NotUsed]] = akka.stream.scaladsl.PartitionHub.sink[T]( - (size, elem) ⇒ partitioner.apply(size, elem), + (size, elem) => partitioner.apply(size, elem), startAfterNrOfConsumers, bufferSize) .mapMaterializedValue(_.asJava) .asJava diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/Keep.scala b/akka-stream/src/main/scala/akka/stream/javadsl/Keep.scala index 6160bfd35c..cbfc239ff5 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/Keep.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/Keep.scala @@ -9,10 +9,10 @@ import akka.japi.function import akka.japi.Pair object Keep { - private val _left = new function.Function2[Any, Any, Any] with ((Any, Any) ⇒ Any) { def apply(l: Any, r: Any) = l } - private val _right = new function.Function2[Any, Any, Any] with ((Any, Any) ⇒ Any) { def apply(l: Any, r: Any) = r } - private val _both = new function.Function2[Any, Any, Any] with ((Any, Any) ⇒ Any) { def apply(l: Any, r: Any) = new akka.japi.Pair(l, r) } - private val _none = new function.Function2[Any, Any, NotUsed] with ((Any, Any) ⇒ NotUsed) { def apply(l: Any, r: Any) = NotUsed } + private val _left = new function.Function2[Any, Any, Any] with ((Any, Any) => Any) { def apply(l: Any, r: Any) = l } + private val _right = new function.Function2[Any, Any, Any] with ((Any, Any) => Any) { def apply(l: Any, r: Any) = r } + private val _both = new function.Function2[Any, Any, Any] with ((Any, Any) => Any) { def apply(l: Any, r: Any) = new akka.japi.Pair(l, r) } + private val _none = new function.Function2[Any, Any, NotUsed] with ((Any, Any) => NotUsed) { def apply(l: Any, r: Any) = NotUsed } def left[L, R]: function.Function2[L, R, L] = _left.asInstanceOf[function.Function2[L, R, L]] def right[L, R]: function.Function2[L, R, R] = _right.asInstanceOf[function.Function2[L, R, R]] diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/MergeLatest.scala b/akka-stream/src/main/scala/akka/stream/javadsl/MergeLatest.scala index 506ee35706..cc161b229d 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/MergeLatest.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/MergeLatest.scala @@ -30,7 +30,7 @@ object MergeLatest { * @param eagerComplete if true, the merge latest will complete as soon as one of its inputs completes. */ def create[T](inputPorts: Int, eagerComplete: Boolean): GraphStage[UniformFanInShape[T, java.util.List[T]]] = - new scaladsl.MergeLatest[T, java.util.List[T]](inputPorts, eagerComplete)(x ⇒ x.toList.asJava) + new scaladsl.MergeLatest[T, java.util.List[T]](inputPorts, eagerComplete)(x => x.toList.asJava) /** * Create a new `MergeLatest` with the specified number of input ports. diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/RestartFlow.scala b/akka-stream/src/main/scala/akka/stream/javadsl/RestartFlow.scala index 748530aabd..5e64355514 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/RestartFlow.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/RestartFlow.scala @@ -45,7 +45,7 @@ object RestartFlow { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def withBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, flowFactory: Creator[Flow[In, Out, _]]): Flow[In, Out, NotUsed] = { - akka.stream.scaladsl.RestartFlow.withBackoff(minBackoff, maxBackoff, randomFactor) { () ⇒ + akka.stream.scaladsl.RestartFlow.withBackoff(minBackoff, maxBackoff, randomFactor) { () => flowFactory.create().asScala }.asJava } @@ -108,7 +108,7 @@ object RestartFlow { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def withBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int, flowFactory: Creator[Flow[In, Out, _]]): Flow[In, Out, NotUsed] = { - akka.stream.scaladsl.RestartFlow.withBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () ⇒ + akka.stream.scaladsl.RestartFlow.withBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () => flowFactory.create().asScala }.asJava } @@ -173,7 +173,7 @@ object RestartFlow { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def onFailuresWithBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int, flowFactory: Creator[Flow[In, Out, _]]): Flow[In, Out, NotUsed] = { - akka.stream.scaladsl.RestartFlow.onFailuresWithBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () ⇒ + akka.stream.scaladsl.RestartFlow.onFailuresWithBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () => flowFactory.create().asScala }.asJava } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/RestartSink.scala b/akka-stream/src/main/scala/akka/stream/javadsl/RestartSink.scala index 7d01c0d6db..b198e1e1ed 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/RestartSink.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/RestartSink.scala @@ -46,7 +46,7 @@ object RestartSink { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, sinkFactory: Creator[Sink[T, _]]): Sink[T, NotUsed] = { - akka.stream.scaladsl.RestartSink.withBackoff(minBackoff, maxBackoff, randomFactor) { () ⇒ + akka.stream.scaladsl.RestartSink.withBackoff(minBackoff, maxBackoff, randomFactor) { () => sinkFactory.create().asScala }.asJava } @@ -111,7 +111,7 @@ object RestartSink { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int, sinkFactory: Creator[Sink[T, _]]): Sink[T, NotUsed] = { - akka.stream.scaladsl.RestartSink.withBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () ⇒ + akka.stream.scaladsl.RestartSink.withBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () => sinkFactory.create().asScala }.asJava } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/RestartSource.scala b/akka-stream/src/main/scala/akka/stream/javadsl/RestartSource.scala index ea6b153d01..b61d5aa3b5 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/RestartSource.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/RestartSource.scala @@ -42,7 +42,7 @@ object RestartSource { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, sourceFactory: Creator[Source[T, _]]): Source[T, NotUsed] = { - akka.stream.scaladsl.RestartSource.withBackoff(minBackoff, maxBackoff, randomFactor) { () ⇒ + akka.stream.scaladsl.RestartSource.withBackoff(minBackoff, maxBackoff, randomFactor) { () => sourceFactory.create().asScala }.asJava } @@ -100,7 +100,7 @@ object RestartSource { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int, sourceFactory: Creator[Source[T, _]]): Source[T, NotUsed] = { - akka.stream.scaladsl.RestartSource.withBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () ⇒ + akka.stream.scaladsl.RestartSource.withBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () => sourceFactory.create().asScala }.asJava } @@ -158,7 +158,7 @@ object RestartSource { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def onFailuresWithBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, sourceFactory: Creator[Source[T, _]]): Source[T, NotUsed] = { - akka.stream.scaladsl.RestartSource.onFailuresWithBackoff(minBackoff, maxBackoff, randomFactor) { () ⇒ + akka.stream.scaladsl.RestartSource.onFailuresWithBackoff(minBackoff, maxBackoff, randomFactor) { () => sourceFactory.create().asScala }.asJava } @@ -215,7 +215,7 @@ object RestartSource { @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def onFailuresWithBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int, sourceFactory: Creator[Source[T, _]]): Source[T, NotUsed] = { - akka.stream.scaladsl.RestartSource.onFailuresWithBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () ⇒ + akka.stream.scaladsl.RestartSource.onFailuresWithBackoff(minBackoff, maxBackoff, randomFactor, maxRestarts) { () => sourceFactory.create().asScala }.asJava } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/Sink.scala b/akka-stream/src/main/scala/akka/stream/javadsl/Sink.scala index 2b300f9506..d69b597b4e 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/Sink.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/Sink.scala @@ -106,7 +106,7 @@ object Sink { * the stream. */ def foreachAsync[T](parallelism: Int)(f: function.Function[T, CompletionStage[Void]]): Sink[T, CompletionStage[Done]] = - new Sink(scaladsl.Sink.foreachAsync(parallelism)((x: T) ⇒ f(x).toScala.map(_ ⇒ ())(ExecutionContexts.sameThreadExecutionContext)).toCompletionStage()) + new Sink(scaladsl.Sink.foreachAsync(parallelism)((x: T) => f(x).toScala.map(_ => ())(ExecutionContexts.sameThreadExecutionContext)).toCompletionStage()) /** * A `Sink` that will invoke the given procedure for each received element in parallel. The sink is materialized @@ -129,7 +129,7 @@ object Sink { * or [[scala.util.Failure]]. */ def onComplete[In](callback: function.Procedure[Try[Done]]): Sink[In, NotUsed] = - new Sink(scaladsl.Sink.onComplete[In](x ⇒ callback.apply(x))) + new Sink(scaladsl.Sink.onComplete[In](x => callback.apply(x))) /** * A `Sink` that materializes into a `CompletionStage` of the first value received. @@ -182,7 +182,7 @@ object Sink { */ def takeLast[In](n: Int): Sink[In, CompletionStage[java.util.List[In]]] = { import scala.collection.JavaConverters._ - new Sink(scaladsl.Sink.takeLast[In](n).mapMaterializedValue(fut ⇒ fut.map(sq ⇒ sq.asJava)(ExecutionContexts.sameThreadExecutionContext).toJava)) + new Sink(scaladsl.Sink.takeLast[In](n).mapMaterializedValue(fut => fut.map(sq => sq.asJava)(ExecutionContexts.sameThreadExecutionContext).toJava)) } /** @@ -197,7 +197,7 @@ object Sink { */ def seq[In]: Sink[In, CompletionStage[java.util.List[In]]] = { import scala.collection.JavaConverters._ - new Sink(scaladsl.Sink.seq[In].mapMaterializedValue(fut ⇒ fut.map(sq ⇒ sq.asJava)(ExecutionContexts.sameThreadExecutionContext).toJava)) + new Sink(scaladsl.Sink.seq[In].mapMaterializedValue(fut => fut.map(sq => sq.asJava)(ExecutionContexts.sameThreadExecutionContext).toJava)) } /** @@ -253,8 +253,8 @@ object Sink { */ def fromGraph[T, M](g: Graph[SinkShape[T], M]): Sink[T, M] = g match { - case s: Sink[T, M] ⇒ s - case other ⇒ new Sink(scaladsl.Sink.fromGraph(other)) + case s: Sink[T, M] => s + case other => new Sink(scaladsl.Sink.fromGraph(other)) } /** @@ -263,7 +263,7 @@ object Sink { def combine[T, U](output1: Sink[U, _], output2: Sink[U, _], rest: java.util.List[Sink[U, _]], strategy: function.Function[java.lang.Integer, Graph[UniformFanOutShape[T, U], NotUsed]]): Sink[T, NotUsed] = { import scala.collection.JavaConverters._ val seq = if (rest != null) rest.asScala.map(_.asScala).toSeq else immutable.Seq() - new Sink(scaladsl.Sink.combine(output1.asScala, output2.asScala, seq: _*)(num ⇒ strategy.apply(num))) + new Sink(scaladsl.Sink.combine(output1.asScala, output2.asScala, seq: _*)(num => strategy.apply(num))) } /** @@ -299,8 +299,8 @@ object Sink { @deprecated("Use lazyInitAsync instead. (lazyInitAsync no more needs a fallback function and the materialized value more clearly indicates if the internal sink was materialized or not.)", "2.5.11") def lazyInit[T, M](sinkFactory: function.Function[T, CompletionStage[Sink[T, M]]], fallback: function.Creator[M]): Sink[T, CompletionStage[M]] = new Sink(scaladsl.Sink.lazyInit[T, M]( - t ⇒ sinkFactory.apply(t).toScala.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext), - () ⇒ fallback.create()).mapMaterializedValue(_.toJava)) + t => sinkFactory.apply(t).toScala.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext), + () => fallback.create()).mapMaterializedValue(_.toJava)) /** * Creates a real `Sink` upon receiving the first element. Internal `Sink` will not be created if there are no elements, @@ -313,8 +313,8 @@ object Sink { */ def lazyInitAsync[T, M](sinkFactory: function.Creator[CompletionStage[Sink[T, M]]]): Sink[T, CompletionStage[Optional[M]]] = { val sSink = scaladsl.Sink.lazyInitAsync[T, M]( - () ⇒ sinkFactory.create().toScala.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext) - ).mapMaterializedValue(fut ⇒ fut.map(_.fold(Optional.empty[M]())(m ⇒ Optional.ofNullable(m)))(ExecutionContexts.sameThreadExecutionContext).toJava) + () => sinkFactory.create().toScala.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext) + ).mapMaterializedValue(fut => fut.map(_.fold(Optional.empty[M]())(m => Optional.ofNullable(m)))(ExecutionContexts.sameThreadExecutionContext).toJava) new Sink(sSink) } } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/Source.scala b/akka-stream/src/main/scala/akka/stream/javadsl/Source.scala index 44757c4147..8c395c29d7 100755 --- a/akka-stream/src/main/scala/akka/stream/javadsl/Source.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/Source.scala @@ -58,7 +58,7 @@ object Source { * with an empty Optional. */ def maybe[T]: Source[T, CompletableFuture[Optional[T]]] = { - new Source(scaladsl.Source.maybe[T].mapMaterializedValue { scalaOptionPromise: Promise[Option[T]] ⇒ + new Source(scaladsl.Source.maybe[T].mapMaterializedValue { scalaOptionPromise: Promise[Option[T]] => val javaOptionPromise = new CompletableFuture[Optional[T]]() scalaOptionPromise.completeWith( javaOptionPromise.toScala @@ -98,7 +98,7 @@ object Source { * steps. */ def fromIterator[O](f: function.Creator[java.util.Iterator[O]]): javadsl.Source[O, NotUsed] = - new Source(scaladsl.Source.fromIterator(() ⇒ f.create().asScala)) + new Source(scaladsl.Source.fromIterator(() => f.create().asScala)) /** * Helper to create 'cycled' [[Source]] from iterator provider. @@ -112,7 +112,7 @@ object Source { * will continue infinitely by repeating the sequence of elements provided by function parameter. */ def cycle[O](f: function.Creator[java.util.Iterator[O]]): javadsl.Source[O, NotUsed] = - new Source(scaladsl.Source.cycle(() ⇒ f.create().asScala)) + new Source(scaladsl.Source.cycle(() => f.create().asScala)) /** * Helper to create [[Source]] from `Iterable`. @@ -245,7 +245,7 @@ object Source { * a pair of the next state `S` and output elements of type `E`. */ def unfold[S, E](s: S, f: function.Function[S, Optional[Pair[S, E]]]): Source[E, NotUsed] = - new Source(scaladsl.Source.unfold(s)((s: S) ⇒ f.apply(s).asScala.map(_.toScala))) + new Source(scaladsl.Source.unfold(s)((s: S) => f.apply(s).asScala.map(_.toScala))) /** * Same as [[unfold]], but uses an async function to generate the next state-element tuple. @@ -253,7 +253,7 @@ object Source { def unfoldAsync[S, E](s: S, f: function.Function[S, CompletionStage[Optional[Pair[S, E]]]]): Source[E, NotUsed] = new Source( scaladsl.Source.unfoldAsync(s)( - (s: S) ⇒ f.apply(s).toScala.map(_.asScala.map(_.toScala))(akka.dispatch.ExecutionContexts.sameThreadExecutionContext))) + (s: S) => f.apply(s).toScala.map(_.asScala.map(_.toScala))(akka.dispatch.ExecutionContexts.sameThreadExecutionContext))) /** * Create a `Source` that immediately ends the stream with the `cause` failure to every connected `Sink`. @@ -267,7 +267,7 @@ object Source { * `create` factory is never called and the materialized `CompletionStage` is failed. */ def lazily[T, M](create: function.Creator[Source[T, M]]): Source[T, CompletionStage[M]] = - scaladsl.Source.lazily[T, M](() ⇒ create.create().asScala).mapMaterializedValue(_.toJava).asJava + scaladsl.Source.lazily[T, M](() => create.create().asScala).mapMaterializedValue(_.toJava).asJava /** * Creates a `Source` from supplied future factory that is not called until downstream demand. When source gets @@ -277,7 +277,7 @@ object Source { * @see [[Source.lazily]] */ def lazilyAsync[T](create: function.Creator[CompletionStage[T]]): Source[T, Future[NotUsed]] = - scaladsl.Source.lazilyAsync[T](() ⇒ create.create().toScala).asJava + scaladsl.Source.lazilyAsync[T](() => create.create().toScala).asJava /** * Creates a `Source` that is materialized as a [[org.reactivestreams.Subscriber]] @@ -342,9 +342,9 @@ object Source { */ def fromGraph[T, M](g: Graph[SourceShape[T], M]): Source[T, M] = g match { - case s: Source[T, M] ⇒ s - case s if s eq scaladsl.Source.empty ⇒ empty().asInstanceOf[Source[T, M]] - case other ⇒ new Source(scaladsl.Source.fromGraph(other)) + case s: Source[T, M] => s + case s if s eq scaladsl.Source.empty => empty().asInstanceOf[Source[T, M]] + case other => new Source(scaladsl.Source.fromGraph(other)) } /** @@ -353,7 +353,7 @@ object Source { def combine[T, U](first: Source[T, _ <: Any], second: Source[T, _ <: Any], rest: java.util.List[Source[T, _ <: Any]], strategy: function.Function[java.lang.Integer, _ <: Graph[UniformFanInShape[T, U], NotUsed]]): Source[U, NotUsed] = { val seq = if (rest != null) Util.immutableSeq(rest).map(_.asScala) else immutable.Seq() - new Source(scaladsl.Source.combine(first.asScala, second.asScala, seq: _*)(num ⇒ strategy.apply(num))) + new Source(scaladsl.Source.combine(first.asScala, second.asScala, seq: _*)(num => strategy.apply(num))) } /** @@ -362,7 +362,7 @@ object Source { def combineMat[T, U, M1, M2, M](first: Source[T, M1], second: Source[T, M2], strategy: function.Function[java.lang.Integer, _ <: Graph[UniformFanInShape[T, U], NotUsed]], combine: function.Function2[M1, M2, M]): Source[U, M] = { - new Source(scaladsl.Source.combineMat(first.asScala, second.asScala)(num ⇒ strategy.apply(num))(combinerToScala(combine))) + new Source(scaladsl.Source.combineMat(first.asScala, second.asScala)(num => strategy.apply(num))(combinerToScala(combine))) } /** @@ -378,7 +378,7 @@ object Source { */ def zipWithN[T, O](zipper: function.Function[java.util.List[T], O], sources: java.util.List[Source[T, _ <: Any]]): Source[O, NotUsed] = { val seq = if (sources != null) Util.immutableSeq(sources).map(_.asScala) else immutable.Seq() - new Source(scaladsl.Source.zipWithN[T, O](seq ⇒ zipper.apply(seq.asJava))(seq)) + new Source(scaladsl.Source.zipWithN[T, O](seq => zipper.apply(seq.asJava))(seq)) } /** @@ -448,7 +448,7 @@ object Source { close: function.Procedure[S]): javadsl.Source[T, NotUsed] = new Source(scaladsl.Source.unfoldResource[T, S]( create.create _, - (s: S) ⇒ read.apply(s).asScala, close.apply)) + (s: S) => read.apply(s).asScala, close.apply)) /** * Start a new `Source` from some resource which can be opened, read and closed. @@ -475,9 +475,9 @@ object Source { read: function.Function[S, CompletionStage[Optional[T]]], close: function.Function[S, CompletionStage[Done]]): javadsl.Source[T, NotUsed] = new Source(scaladsl.Source.unfoldResourceAsync[T, S]( - () ⇒ create.create().toScala, - (s: S) ⇒ read.apply(s).toScala.map(_.asScala)(akka.dispatch.ExecutionContexts.sameThreadExecutionContext), - (s: S) ⇒ close.apply(s).toScala)) + () => create.create().toScala, + (s: S) => read.apply(s).toScala.map(_.asScala)(akka.dispatch.ExecutionContexts.sameThreadExecutionContext), + (s: S) => close.apply(s).toScala)) /** * Upcast a stream of elements to a stream of supertypes of that element. Useful in combination with @@ -1206,7 +1206,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * '''Cancels when''' downstream cancels */ def zipWithIndex: javadsl.Source[Pair[Out @uncheckedVariance, java.lang.Long], Mat] = - new Source(delegate.zipWithIndex.map { case (elem, index) ⇒ Pair[Out, java.lang.Long](elem, index) }) + new Source(delegate.zipWithIndex.map { case (elem, index) => Pair[Out, java.lang.Long](elem, index) }) /** * Shortcut for running this `Source` with a foreach procedure. The given procedure is invoked @@ -1297,7 +1297,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ @deprecated("Use recoverWithRetries instead.", "2.4.4") def recover(clazz: Class[_ <: Throwable], supplier: Supplier[Out]): javadsl.Source[Out, Mat] = recover { - case elem if clazz.isInstance(elem) ⇒ supplier.get() + case elem if clazz.isInstance(elem) => supplier.get() } /** @@ -1367,7 +1367,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ */ def recoverWith(clazz: Class[_ <: Throwable], supplier: Supplier[Graph[SourceShape[Out], NotUsed]]): Source[Out, Mat] = recoverWith { - case elem if clazz.isInstance(elem) ⇒ supplier.get() + case elem if clazz.isInstance(elem) => supplier.get() } /** @@ -1424,7 +1424,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ */ def recoverWithRetries(attempts: Int, clazz: Class[_ <: Throwable], supplier: Supplier[Graph[SourceShape[Out], NotUsed]]): Source[Out, Mat] = recoverWithRetries(attempts, { - case elem if clazz.isInstance(elem) ⇒ supplier.get() + case elem if clazz.isInstance(elem) => supplier.get() }) /** @@ -1449,7 +1449,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * '''Cancels when''' downstream cancels */ def mapConcat[T](f: function.Function[Out, _ <: java.lang.Iterable[T]]): javadsl.Source[T, Mat] = - new Source(delegate.mapConcat(elem ⇒ Util.immutableSeq(f.apply(elem)))) + new Source(delegate.mapConcat(elem => Util.immutableSeq(f.apply(elem)))) /** * Transform each input element into an `Iterable` of output elements that is @@ -1478,9 +1478,9 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * '''Cancels when''' downstream cancels */ def statefulMapConcat[T](f: function.Creator[function.Function[Out, java.lang.Iterable[T]]]): javadsl.Source[T, Mat] = - new Source(delegate.statefulMapConcat { () ⇒ + new Source(delegate.statefulMapConcat { () => val fun = f.create() - elem ⇒ Util.immutableSeq(fun(elem)) + elem => Util.immutableSeq(fun(elem)) }) /** @@ -1515,7 +1515,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * @see [[#mapAsyncUnordered]] */ def mapAsync[T](parallelism: Int, f: function.Function[Out, CompletionStage[T]]): javadsl.Source[T, Mat] = - new Source(delegate.mapAsync(parallelism)(x ⇒ f(x).toScala)) + new Source(delegate.mapAsync(parallelism)(x => f(x).toScala)) /** * Transform this stream by applying the given function to each of the elements @@ -1549,7 +1549,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * @see [[#mapAsync]] */ def mapAsyncUnordered[T](parallelism: Int, f: function.Function[Out, CompletionStage[T]]): javadsl.Source[T, Mat] = - new Source(delegate.mapAsyncUnordered(parallelism)(x ⇒ f(x).toScala)) + new Source(delegate.mapAsyncUnordered(parallelism)(x => f(x).toScala)) /** * Use the `ask` pattern to send a request-reply message to the target `ref` actor. @@ -1838,7 +1838,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * See also [[FlowOps.scan]] */ def scanAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): javadsl.Source[T, Mat] = - new Source(delegate.scanAsync(zero) { (out, in) ⇒ f(out, in).toScala }) + new Source(delegate.scanAsync(zero) { (out, in) => f(out, in).toScala }) /** * Similar to `scan` but only emits its result when the upstream completes, @@ -1885,7 +1885,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * * '''Cancels when''' downstream cancels */ - def foldAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): javadsl.Source[T, Mat] = new Source(delegate.foldAsync(zero) { (out, in) ⇒ f(out, in).toScala }) + def foldAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): javadsl.Source[T, Mat] = new Source(delegate.foldAsync(zero) { (out, in) => f(out, in).toScala }) /** * Similar to `fold` but uses first element as zero element. @@ -2419,7 +2419,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * @see [[#extrapolate]] */ def expand[U](expander: function.Function[Out, java.util.Iterator[U]]): javadsl.Source[U, Mat] = - new Source(delegate.expand(in ⇒ expander(in).asScala)) + new Source(delegate.expand(in => expander(in).asScala)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -2446,7 +2446,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * @see [[#expand]] */ def extrapolate(extrapolator: function.Function[Out @uncheckedVariance, java.util.Iterator[Out @uncheckedVariance]]): Source[Out, Mat] = - new Source(delegate.extrapolate(in ⇒ extrapolator(in).asScala)) + new Source(delegate.extrapolate(in => extrapolator(in).asScala)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -2474,7 +2474,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * @see [[#expand]] */ def extrapolate(extrapolator: function.Function[Out @uncheckedVariance, java.util.Iterator[Out @uncheckedVariance]], initial: Out @uncheckedVariance): Source[Out, Mat] = - new Source(delegate.extrapolate(in ⇒ extrapolator(in).asScala, Some(initial))) + new Source(delegate.extrapolate(in => extrapolator(in).asScala, Some(initial))) /** * Adds a fixed size buffer in the flow that allows to store elements from a faster upstream until it becomes full. @@ -2522,7 +2522,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * '''Cancels when''' downstream cancels or substream cancels */ def prefixAndTail(n: Int): javadsl.Source[Pair[java.util.List[Out @uncheckedVariance], javadsl.Source[Out @uncheckedVariance, NotUsed]], Mat] = - new Source(delegate.prefixAndTail(n).map { case (taken, tail) ⇒ Pair(taken.asJava, tail.asJava) }) + new Source(delegate.prefixAndTail(n).map { case (taken, tail) => Pair(taken.asJava, tail.asJava) }) /** * This operation demultiplexes the incoming stream into separate output @@ -2759,7 +2759,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * '''Cancels when''' downstream cancels */ def flatMapConcat[T, M](f: function.Function[Out, _ <: Graph[SourceShape[T], M]]): Source[T, Mat] = - new Source(delegate.flatMapConcat[T, M](x ⇒ f(x))) + new Source(delegate.flatMapConcat[T, M](x => f(x))) /** * Transform each input element into a `Source` of output elements that is @@ -2775,7 +2775,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * '''Cancels when''' downstream cancels */ def flatMapMerge[T, M](breadth: Int, f: function.Function[Out, _ <: Graph[SourceShape[T], M]]): Source[T, Mat] = - new Source(delegate.flatMapMerge(breadth, o ⇒ f(o))) + new Source(delegate.flatMapMerge(breadth, o => f(o))) /** * If the first element has not passed through this operator before the provided timeout, the stream is failed @@ -2929,7 +2929,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ @Deprecated @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def keepAlive(maxIdle: FiniteDuration, injectedElem: function.Creator[Out]): javadsl.Source[Out, Mat] = - new Source(delegate.keepAlive(maxIdle, () ⇒ injectedElem.create())) + new Source(delegate.keepAlive(maxIdle, () => injectedElem.create())) /** * Injects additional elements if upstream does not emit for a configured amount of time. In other words, this @@ -3233,7 +3233,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ @Deprecated @deprecated("Use throttle without `maximumBurst` parameter instead.", "2.5.12") def throttleEven(cost: Int, per: FiniteDuration, - costCalculation: (Out) ⇒ Int, mode: ThrottleMode): javadsl.Source[Out, Mat] = + costCalculation: (Out) => Int, mode: ThrottleMode): javadsl.Source[Out, Mat] = new Source(delegate.throttleEven(cost, per, costCalculation.apply _, mode)) /** @@ -3249,7 +3249,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ @Deprecated @deprecated("Use throttle without `maximumBurst` parameter instead.", "2.5.12") def throttleEven(cost: Int, per: java.time.Duration, - costCalculation: (Out) ⇒ Int, mode: ThrottleMode): javadsl.Source[Out, Mat] = + costCalculation: (Out) => Int, mode: ThrottleMode): javadsl.Source[Out, Mat] = throttleEven(cost, per.asScala, costCalculation, mode) /** @@ -3273,7 +3273,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * downstream. */ def watchTermination[M]()(matF: function.Function2[Mat, CompletionStage[Done], M]): javadsl.Source[Out, M] = - new Source(delegate.watchTermination()((left, right) ⇒ matF(left, right.toJava))) + new Source(delegate.watchTermination()((left, right) => matF(left, right.toJava))) /** * Materializes to `FlowMonitor` that allows monitoring of the current flow. All events are propagated @@ -3406,7 +3406,7 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ * '''Cancels when''' downstream cancels */ def log(name: String, extract: function.Function[Out, Any], log: LoggingAdapter): javadsl.Source[Out, Mat] = - new Source(delegate.log(name, e ⇒ extract.apply(e))(log)) + new Source(delegate.log(name, e => extract.apply(e))(log)) /** * Logs elements flowing through the stream as well as completion and erroring. @@ -3473,5 +3473,5 @@ final class Source[Out, Mat](delegate: scaladsl.Source[Out, Mat]) extends Graph[ */ @ApiMayChange def asSourceWithContext[Ctx](extractContext: function.Function[Out, Ctx]): SourceWithContext[Out, Ctx, Mat] = - new scaladsl.SourceWithContext(this.asScala.map(x ⇒ (x, extractContext.apply(x)))).asJava + new scaladsl.SourceWithContext(this.asScala.map(x => (x, extractContext.apply(x)))).asJava } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/SourceWithContext.scala b/akka-stream/src/main/scala/akka/stream/javadsl/SourceWithContext.scala index 69f0278431..81efaf0385 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/SourceWithContext.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/SourceWithContext.scala @@ -52,7 +52,7 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon * @see [[akka.stream.javadsl.Flow.via]] */ def via[Out2, Ctx2, Mat2](viaFlow: Graph[FlowShape[Pair[Out @uncheckedVariance, Ctx @uncheckedVariance], Pair[Out2, Ctx2]], Mat2]): SourceWithContext[Out2, Ctx2, Mat] = - viaScala(_.via(akka.stream.scaladsl.Flow[(Out, Ctx)].map { case (o, c) ⇒ Pair(o, c) }.via(viaFlow).map(_.toScala))) + viaScala(_.via(akka.stream.scaladsl.Flow[(Out, Ctx)].map { case (o, c) => Pair(o, c) }.via(viaFlow).map(_.toScala))) /** * Context-preserving variant of [[akka.stream.javadsl.Source.withAttributes]]. @@ -67,7 +67,7 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon * stream of a pair of (data, context). */ def asSource(): Source[Pair[Out @uncheckedVariance, Ctx @uncheckedVariance], Mat @uncheckedVariance] = - delegate.asSource.map { case (o, c) ⇒ Pair(o, c) }.asJava + delegate.asSource.map { case (o, c) => Pair(o, c) }.asJava // remaining operations in alphabetic order @@ -120,7 +120,7 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon viaScala(_.map(f.apply)) def mapAsync[Out2](parallelism: Int, f: function.Function[Out, CompletionStage[Out2]]): SourceWithContext[Out2, Ctx, Mat] = - viaScala(_.mapAsync[Out2](parallelism)(o ⇒ f.apply(o).toScala)) + viaScala(_.mapAsync[Out2](parallelism)(o => f.apply(o).toScala)) /** * Context-preserving variant of [[akka.stream.javadsl.Source.mapConcat]]. @@ -151,7 +151,7 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon * @see [[akka.stream.javadsl.Source.mapConcat]] */ def mapConcat[Out2](f: function.Function[Out, _ <: java.lang.Iterable[Out2]]): SourceWithContext[Out2, Ctx, Mat] = - viaScala(_.mapConcat(elem ⇒ Util.immutableSeq(f.apply(elem)))) + viaScala(_.mapConcat(elem => Util.immutableSeq(f.apply(elem)))) /** * Apply the given function to each context element (leaving the data elements unchanged). @@ -175,7 +175,7 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon * @see [[akka.stream.javadsl.Source.log]] */ def log(name: String, extract: function.Function[Out, Any], log: LoggingAdapter): SourceWithContext[Out, Ctx, Mat] = - viaScala(_.log(name, e ⇒ extract.apply(e))(log)) + viaScala(_.log(name, e => extract.apply(e))(log)) /** * Context-preserving variant of [[akka.stream.javadsl.Flow.log]]. @@ -206,14 +206,14 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon * concatenating the processing steps of both. */ def to[Mat2](sink: Graph[SinkShape[Pair[Out @uncheckedVariance, Ctx @uncheckedVariance]], Mat2]): javadsl.RunnableGraph[Mat] = - RunnableGraph.fromGraph(asScala.asSource.map { case (o, e) ⇒ Pair(o, e) }.to(sink)) + RunnableGraph.fromGraph(asScala.asSource.map { case (o, e) => Pair(o, e) }.to(sink)) /** * Connect this [[akka.stream.javadsl.SourceWithContext]] to a [[akka.stream.javadsl.Sink]], * concatenating the processing steps of both. */ def toMat[Mat2, Mat3](sink: Graph[SinkShape[Pair[Out @uncheckedVariance, Ctx @uncheckedVariance]], Mat2], combine: function.Function2[Mat, Mat2, Mat3]): javadsl.RunnableGraph[Mat3] = - RunnableGraph.fromGraph(asScala.asSource.map { case (o, e) ⇒ Pair(o, e) }.toMat(sink)(combinerToScala(combine))) + RunnableGraph.fromGraph(asScala.asSource.map { case (o, e) => Pair(o, e) }.toMat(sink)(combinerToScala(combine))) /** * Connect this [[akka.stream.javadsl.SourceWithContext]] to a [[akka.stream.javadsl.Sink]] and run it. @@ -224,6 +224,6 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon def asScala: scaladsl.SourceWithContext[Out, Ctx, Mat] = delegate - private[this] def viaScala[Out2, Ctx2, Mat2](f: scaladsl.SourceWithContext[Out, Ctx, Mat] ⇒ scaladsl.SourceWithContext[Out2, Ctx2, Mat2]): SourceWithContext[Out2, Ctx2, Mat2] = + private[this] def viaScala[Out2, Ctx2, Mat2](f: scaladsl.SourceWithContext[Out, Ctx, Mat] => scaladsl.SourceWithContext[Out2, Ctx2, Mat2]): SourceWithContext[Out2, Ctx2, Mat2] = new SourceWithContext(f(delegate)) } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/StreamConverters.scala b/akka-stream/src/main/scala/akka/stream/javadsl/StreamConverters.scala index 48b41c56f5..8d61089774 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/StreamConverters.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/StreamConverters.scala @@ -52,7 +52,7 @@ object StreamConverters { * @param autoFlush If true the OutputStream will be flushed whenever a byte array is written */ def fromOutputStream(f: function.Creator[OutputStream], autoFlush: Boolean): javadsl.Sink[ByteString, CompletionStage[IOResult]] = - new Sink(scaladsl.StreamConverters.fromOutputStream(() ⇒ f.create(), autoFlush).toCompletionStage()) + new Sink(scaladsl.StreamConverters.fromOutputStream(() => f.create(), autoFlush).toCompletionStage()) /** * Creates a Sink which when materialized will return an [[java.io.InputStream]] which it is possible @@ -124,7 +124,7 @@ object StreamConverters { * The created [[InputStream]] will be closed when the [[Source]] is cancelled. */ def fromInputStream(in: function.Creator[InputStream], chunkSize: Int): javadsl.Source[ByteString, CompletionStage[IOResult]] = - new Source(scaladsl.StreamConverters.fromInputStream(() ⇒ in.create(), chunkSize).toCompletionStage()) + new Source(scaladsl.StreamConverters.fromInputStream(() => in.create(), chunkSize).toCompletionStage()) /** * Creates a Source from an [[java.io.InputStream]] created by the given function. @@ -235,7 +235,7 @@ object StreamConverters { * to handle multiple invocations. */ def javaCollector[T, R](collector: function.Creator[Collector[T, _ <: Any, R]]): Sink[T, CompletionStage[R]] = - new Sink(scaladsl.StreamConverters.javaCollector[T, R](() ⇒ collector.create()).toCompletionStage()) + new Sink(scaladsl.StreamConverters.javaCollector[T, R](() => collector.create()).toCompletionStage()) /** * Creates a sink which materializes into a ``CompletionStage`` which will be completed with a result of the Java 8 ``Collector`` @@ -248,6 +248,6 @@ object StreamConverters { * to handle multiple invocations. */ def javaCollectorParallelUnordered[T, R](parallelism: Int)(collector: function.Creator[Collector[T, _ <: Any, R]]): Sink[T, CompletionStage[R]] = - new Sink(scaladsl.StreamConverters.javaCollectorParallelUnordered[T, R](parallelism)(() ⇒ collector.create()).toCompletionStage()) + new Sink(scaladsl.StreamConverters.javaCollectorParallelUnordered[T, R](parallelism)(() => collector.create()).toCompletionStage()) } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/SubFlow.scala b/akka-stream/src/main/scala/akka/stream/javadsl/SubFlow.scala index 3eb39ed53a..d983a30111 100755 --- a/akka-stream/src/main/scala/akka/stream/javadsl/SubFlow.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/SubFlow.scala @@ -186,7 +186,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * '''Cancels when''' downstream cancels */ def mapConcat[T](f: function.Function[Out, java.lang.Iterable[T]]): SubFlow[In, T, Mat] = - new SubFlow(delegate.mapConcat { elem ⇒ Util.immutableSeq(f(elem)) }) + new SubFlow(delegate.mapConcat { elem => Util.immutableSeq(f(elem)) }) /** * Transform each input element into an `Iterable` of output elements that is @@ -215,9 +215,9 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * '''Cancels when''' downstream cancels */ def statefulMapConcat[T](f: function.Creator[function.Function[Out, java.lang.Iterable[T]]]): SubFlow[In, T, Mat] = - new SubFlow(delegate.statefulMapConcat { () ⇒ + new SubFlow(delegate.statefulMapConcat { () => val fun = f.create() - elem ⇒ Util.immutableSeq(fun(elem)) + elem => Util.immutableSeq(fun(elem)) }) /** @@ -252,7 +252,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * @see [[#mapAsyncUnordered]] */ def mapAsync[T](parallelism: Int, f: function.Function[Out, CompletionStage[T]]): SubFlow[In, T, Mat] = - new SubFlow(delegate.mapAsync(parallelism)(x ⇒ f(x).toScala)) + new SubFlow(delegate.mapAsync(parallelism)(x => f(x).toScala)) /** * Transform this stream by applying the given function to each of the elements @@ -286,7 +286,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * @see [[#mapAsync]] */ def mapAsyncUnordered[T](parallelism: Int, f: function.Function[Out, CompletionStage[T]]): SubFlow[In, T, Mat] = - new SubFlow(delegate.mapAsyncUnordered(parallelism)(x ⇒ f(x).toScala)) + new SubFlow(delegate.mapAsyncUnordered(parallelism)(x => f(x).toScala)) /** * Only pass on those elements that satisfy the given predicate. @@ -500,7 +500,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * See also [[FlowOps.scan]] */ def scanAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): SubFlow[In, T, Mat] = - new SubFlow(delegate.scanAsync(zero) { (out, in) ⇒ f(out, in).toScala }) + new SubFlow(delegate.scanAsync(zero) { (out, in) => f(out, in).toScala }) /** * Similar to `scan` but only emits its result when the upstream completes, @@ -547,7 +547,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * * '''Cancels when''' downstream cancels */ - def foldAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): SubFlow[In, T, Mat] = new SubFlow(delegate.foldAsync(zero) { (out, in) ⇒ f(out, in).toScala }) + def foldAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): SubFlow[In, T, Mat] = new SubFlow(delegate.foldAsync(zero) { (out, in) => f(out, in).toScala }) /** * Similar to `fold` but uses first element as zero element. @@ -1173,7 +1173,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * element. */ def expand[U](expander: function.Function[Out, java.util.Iterator[U]]): SubFlow[In, U, Mat] = - new SubFlow(delegate.expand(in ⇒ expander(in).asScala)) + new SubFlow(delegate.expand(in => expander(in).asScala)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -1200,7 +1200,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * @see [[#expand]] */ def extrapolate(extrapolator: function.Function[Out @uncheckedVariance, java.util.Iterator[Out @uncheckedVariance]]): SubFlow[In, Out, Mat] = - new SubFlow(delegate.extrapolate(in ⇒ extrapolator(in).asScala)) + new SubFlow(delegate.extrapolate(in => extrapolator(in).asScala)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -1228,7 +1228,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * @see [[#expand]] */ def extrapolate(extrapolator: function.Function[Out @uncheckedVariance, java.util.Iterator[Out @uncheckedVariance]], initial: Out @uncheckedVariance): SubFlow[In, Out, Mat] = - new SubFlow(delegate.extrapolate(in ⇒ extrapolator(in).asScala, Some(initial))) + new SubFlow(delegate.extrapolate(in => extrapolator(in).asScala, Some(initial))) /** * Adds a fixed size buffer in the flow that allows to store elements from a faster upstream until it becomes full. @@ -1276,7 +1276,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * '''Cancels when''' downstream cancels or substream cancels */ def prefixAndTail(n: Int): SubFlow[In, akka.japi.Pair[java.util.List[Out @uncheckedVariance], javadsl.Source[Out @uncheckedVariance, NotUsed]], Mat] = - new SubFlow(delegate.prefixAndTail(n).map { case (taken, tail) ⇒ akka.japi.Pair(taken.asJava, tail.asJava) }) + new SubFlow(delegate.prefixAndTail(n).map { case (taken, tail) => akka.japi.Pair(taken.asJava, tail.asJava) }) /** * Transform each input element into a `Source` of output elements that is @@ -1293,7 +1293,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * */ def flatMapConcat[T, M](f: function.Function[Out, _ <: Graph[SourceShape[T], M]]): SubFlow[In, T, Mat] = - new SubFlow(delegate.flatMapConcat(x ⇒ f(x))) + new SubFlow(delegate.flatMapConcat(x => f(x))) /** * Transform each input element into a `Source` of output elements that is @@ -1309,7 +1309,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * '''Cancels when''' downstream cancels */ def flatMapMerge[T, M](breadth: Int, f: function.Function[Out, _ <: Graph[SourceShape[T], M]]): SubFlow[In, T, Mat] = - new SubFlow(delegate.flatMapMerge(breadth, o ⇒ f(o))) + new SubFlow(delegate.flatMapMerge(breadth, o => f(o))) /** * Concatenate the given [[Source]] to this [[Flow]], meaning that once this @@ -1500,7 +1500,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * '''Cancels when''' downstream cancels */ def zip[T](source: Graph[SourceShape[T], _]): SubFlow[In, akka.japi.Pair[Out @uncheckedVariance, T], Mat] = - new SubFlow(delegate.zip(source).map { case (o, t) ⇒ akka.japi.Pair.create(o, t) }) + new SubFlow(delegate.zip(source).map { case (o, t) => akka.japi.Pair.create(o, t) }) /** * Combine the elements of current [[Flow]] and the given [[Source]] into a stream of tuples, picking always the latest element of each. @@ -1515,7 +1515,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * '''Cancels when''' downstream cancels */ def zipLatest[T](source: Graph[SourceShape[T], _]): SubFlow[In, akka.japi.Pair[Out @uncheckedVariance, T], Mat] = - new SubFlow(delegate.zipLatest(source).map { case (o, t) ⇒ akka.japi.Pair.create(o, t) }) + new SubFlow(delegate.zipLatest(source).map { case (o, t) => akka.japi.Pair.create(o, t) }) /** * Put together the elements of current [[Flow]] and the given [[Source]] @@ -1565,7 +1565,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * '''Cancels when''' downstream cancels */ def zipWithIndex: SubFlow[In, akka.japi.Pair[Out @uncheckedVariance, java.lang.Long], Mat] = - new SubFlow(delegate.zipWithIndex.map { case (elem, index) ⇒ akka.japi.Pair[Out, java.lang.Long](elem, index) }) + new SubFlow(delegate.zipWithIndex.map { case (elem, index) => akka.japi.Pair[Out, java.lang.Long](elem, index) }) /** * If the first element has not passed through this operator before the provided timeout, the stream is failed @@ -1719,7 +1719,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I @Deprecated @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def keepAlive(maxIdle: FiniteDuration, injectedElem: function.Creator[Out]): SubFlow[In, Out, Mat] = - new SubFlow(delegate.keepAlive(maxIdle, () ⇒ injectedElem.create())) + new SubFlow(delegate.keepAlive(maxIdle, () => injectedElem.create())) /** * Injects additional elements if upstream does not emit for a configured amount of time. In other words, this @@ -2139,7 +2139,7 @@ class SubFlow[In, Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Flow[I * '''Cancels when''' downstream cancels */ def log(name: String, extract: function.Function[Out, Any], log: LoggingAdapter): SubFlow[In, Out, Mat] = - new SubFlow(delegate.log(name, e ⇒ extract.apply(e))(log)) + new SubFlow(delegate.log(name, e => extract.apply(e))(log)) /** * Logs elements flowing through the stream as well as completion and erroring. diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/SubSource.scala b/akka-stream/src/main/scala/akka/stream/javadsl/SubSource.scala index 651a3ceaaf..2740c73032 100755 --- a/akka-stream/src/main/scala/akka/stream/javadsl/SubSource.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/SubSource.scala @@ -175,7 +175,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * '''Cancels when''' downstream cancels */ def mapConcat[T](f: function.Function[Out, java.lang.Iterable[T]]): SubSource[T, Mat] = - new SubSource(delegate.mapConcat { elem ⇒ Util.immutableSeq(f(elem)) }) + new SubSource(delegate.mapConcat { elem => Util.immutableSeq(f(elem)) }) /** * Transform each input element into an `Iterable` of output elements that is @@ -204,9 +204,9 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * '''Cancels when''' downstream cancels */ def statefulMapConcat[T](f: function.Creator[function.Function[Out, java.lang.Iterable[T]]]): SubSource[T, Mat] = - new SubSource(delegate.statefulMapConcat { () ⇒ + new SubSource(delegate.statefulMapConcat { () => val fun = f.create() - elem ⇒ Util.immutableSeq(fun(elem)) + elem => Util.immutableSeq(fun(elem)) }) /** @@ -241,7 +241,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * @see [[#mapAsyncUnordered]] */ def mapAsync[T](parallelism: Int, f: function.Function[Out, CompletionStage[T]]): SubSource[T, Mat] = - new SubSource(delegate.mapAsync(parallelism)(x ⇒ f(x).toScala)) + new SubSource(delegate.mapAsync(parallelism)(x => f(x).toScala)) /** * Transform this stream by applying the given function to each of the elements @@ -275,7 +275,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * @see [[#mapAsync]] */ def mapAsyncUnordered[T](parallelism: Int, f: function.Function[Out, CompletionStage[T]]): SubSource[T, Mat] = - new SubSource(delegate.mapAsyncUnordered(parallelism)(x ⇒ f(x).toScala)) + new SubSource(delegate.mapAsyncUnordered(parallelism)(x => f(x).toScala)) /** * Only pass on those elements that satisfy the given predicate. @@ -489,7 +489,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * See also [[FlowOps.scan]] */ def scanAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): SubSource[T, Mat] = - new SubSource(delegate.scanAsync(zero) { (out, in) ⇒ f(out, in).toScala }) + new SubSource(delegate.scanAsync(zero) { (out, in) => f(out, in).toScala }) /** * Similar to `scan` but only emits its result when the upstream completes, @@ -534,7 +534,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * * '''Cancels when''' downstream cancels */ - def foldAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): SubSource[T, Mat] = new SubSource(delegate.foldAsync(zero) { (out, in) ⇒ f(out, in).toScala }) + def foldAsync[T](zero: T)(f: function.Function2[T, Out, CompletionStage[T]]): SubSource[T, Mat] = new SubSource(delegate.foldAsync(zero) { (out, in) => f(out, in).toScala }) /** * Similar to `fold` but uses first element as zero element. @@ -1153,7 +1153,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * @see [[#extrapolate]] */ def expand[U](expander: function.Function[Out, java.util.Iterator[U]]): SubSource[U, Mat] = - new SubSource(delegate.expand(in ⇒ expander(in).asScala)) + new SubSource(delegate.expand(in => expander(in).asScala)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -1180,7 +1180,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * @see [[#expand]] */ def extrapolate(extrapolator: function.Function[Out @uncheckedVariance, java.util.Iterator[Out @uncheckedVariance]]): SubSource[Out, Mat] = - new SubSource(delegate.extrapolate(in ⇒ extrapolator(in).asScala)) + new SubSource(delegate.extrapolate(in => extrapolator(in).asScala)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -1208,7 +1208,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * @see [[#expand]] */ def extrapolate(extrapolator: function.Function[Out @uncheckedVariance, java.util.Iterator[Out @uncheckedVariance]], initial: Out @uncheckedVariance): SubSource[Out, Mat] = - new SubSource(delegate.extrapolate(in ⇒ extrapolator(in).asScala, Some(initial))) + new SubSource(delegate.extrapolate(in => extrapolator(in).asScala, Some(initial))) /** * Adds a fixed size buffer in the flow that allows to store elements from a faster upstream until it becomes full. @@ -1256,7 +1256,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * '''Cancels when''' downstream cancels or substream cancels */ def prefixAndTail(n: Int): SubSource[akka.japi.Pair[java.util.List[Out @uncheckedVariance], javadsl.Source[Out @uncheckedVariance, NotUsed]], Mat] = - new SubSource(delegate.prefixAndTail(n).map { case (taken, tail) ⇒ akka.japi.Pair(taken.asJava, tail.asJava) }) + new SubSource(delegate.prefixAndTail(n).map { case (taken, tail) => akka.japi.Pair(taken.asJava, tail.asJava) }) /** * Transform each input element into a `Source` of output elements that is @@ -1273,7 +1273,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * */ def flatMapConcat[T, M](f: function.Function[Out, _ <: Graph[SourceShape[T], M]]): SubSource[T, Mat] = - new SubSource(delegate.flatMapConcat(x ⇒ f(x))) + new SubSource(delegate.flatMapConcat(x => f(x))) /** * Transform each input element into a `Source` of output elements that is @@ -1289,7 +1289,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * '''Cancels when''' downstream cancels */ def flatMapMerge[T, M](breadth: Int, f: function.Function[Out, _ <: Graph[SourceShape[T], M]]): SubSource[T, Mat] = - new SubSource(delegate.flatMapMerge(breadth, o ⇒ f(o))) + new SubSource(delegate.flatMapMerge(breadth, o => f(o))) /** * Concatenate the given [[Source]] to this [[Flow]], meaning that once this @@ -1481,7 +1481,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * '''Cancels when''' downstream cancels */ def zip[T](source: Graph[SourceShape[T], _]): SubSource[akka.japi.Pair[Out @uncheckedVariance, T], Mat] = - new SubSource(delegate.zip(source).map { case (o, t) ⇒ akka.japi.Pair.create(o, t) }) + new SubSource(delegate.zip(source).map { case (o, t) => akka.japi.Pair.create(o, t) }) /** * Combine the elements of current [[Flow]] and the given [[Source]] into a stream of tuples, picking always the latest element of each. @@ -1496,7 +1496,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * '''Cancels when''' downstream cancels */ def zipLatest[T](source: Graph[SourceShape[T], _]): SubSource[akka.japi.Pair[Out @uncheckedVariance, T], Mat] = - new SubSource(delegate.zipLatest(source).map { case (o, t) ⇒ akka.japi.Pair.create(o, t) }) + new SubSource(delegate.zipLatest(source).map { case (o, t) => akka.japi.Pair.create(o, t) }) /** * Put together the elements of current [[Flow]] and the given [[Source]] @@ -1546,7 +1546,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * '''Cancels when''' downstream cancels */ def zipWithIndex: javadsl.SubSource[akka.japi.Pair[Out @uncheckedVariance, Long], Mat] = - new SubSource(delegate.zipWithIndex.map { case (elem, index) ⇒ akka.japi.Pair(elem, index) }) + new SubSource(delegate.zipWithIndex.map { case (elem, index) => akka.japi.Pair(elem, index) }) /** * If the first element has not passed through this operator before the provided timeout, the stream is failed @@ -1700,7 +1700,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O @Deprecated @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "2.5.12") def keepAlive(maxIdle: FiniteDuration, injectedElem: function.Creator[Out]): SubSource[Out, Mat] = - new SubSource(delegate.keepAlive(maxIdle, () ⇒ injectedElem.create())) + new SubSource(delegate.keepAlive(maxIdle, () => injectedElem.create())) /** * Injects additional elements if upstream does not emit for a configured amount of time. In other words, this @@ -2004,7 +2004,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O @Deprecated @deprecated("Use throttle without `maximumBurst` parameter instead.", "2.5.12") def throttleEven(cost: Int, per: FiniteDuration, - costCalculation: (Out) ⇒ Int, mode: ThrottleMode): javadsl.SubSource[Out, Mat] = + costCalculation: (Out) => Int, mode: ThrottleMode): javadsl.SubSource[Out, Mat] = new SubSource(delegate.throttleEven(cost, per, costCalculation.apply _, mode)) /** @@ -2020,7 +2020,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O @Deprecated @deprecated("Use throttle without `maximumBurst` parameter instead.", "2.5.12") def throttleEven(cost: Int, per: java.time.Duration, - costCalculation: (Out) ⇒ Int, mode: ThrottleMode): javadsl.SubSource[Out, Mat] = + costCalculation: (Out) => Int, mode: ThrottleMode): javadsl.SubSource[Out, Mat] = throttleEven(cost, per.asScala, costCalculation, mode) /** @@ -2120,7 +2120,7 @@ class SubSource[Out, Mat](delegate: scaladsl.SubFlow[Out, Mat, scaladsl.Source[O * '''Cancels when''' downstream cancels */ def log(name: String, extract: function.Function[Out, Any], log: LoggingAdapter): SubSource[Out, Mat] = - new SubSource(delegate.log(name, e ⇒ extract.apply(e))(log)) + new SubSource(delegate.log(name, e => extract.apply(e))(log)) /** * Logs elements flowing through the stream as well as completion and erroring. diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/TLS.scala b/akka-stream/src/main/scala/akka/stream/javadsl/TLS.scala index 87bbd33632..08ed7af63e 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/TLS.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/TLS.scala @@ -100,7 +100,7 @@ object TLS { * configured using [[javax.net.ssl.SSLParameters.setEndpointIdentificationAlgorithm]]. */ def create(sslContext: SSLContext, sslConfig: Optional[AkkaSSLConfig], firstSession: NegotiateNewSession, role: TLSRole, hostInfo: Optional[japi.Pair[String, java.lang.Integer]], closing: TLSClosing): BidiFlow[SslTlsOutbound, ByteString, ByteString, SslTlsInbound, NotUsed] = - new javadsl.BidiFlow(scaladsl.TLS.apply(sslContext, OptionConverters.toScala(sslConfig), firstSession, role, closing, OptionConverters.toScala(hostInfo).map(e ⇒ (e.first, e.second)))) + new javadsl.BidiFlow(scaladsl.TLS.apply(sslContext, OptionConverters.toScala(sslConfig), firstSession, role, closing, OptionConverters.toScala(hostInfo).map(e => (e.first, e.second)))) /** * Create a StreamTls [[akka.stream.javadsl.BidiFlow]] in client mode. The @@ -119,7 +119,7 @@ object TLS { * configured using [[javax.net.ssl.SSLParameters.setEndpointIdentificationAlgorithm]]. */ def create(sslContext: SSLContext, firstSession: NegotiateNewSession, role: TLSRole, hostInfo: Optional[japi.Pair[String, java.lang.Integer]], closing: TLSClosing): BidiFlow[SslTlsOutbound, ByteString, ByteString, SslTlsInbound, NotUsed] = - new javadsl.BidiFlow(scaladsl.TLS.apply(sslContext, None, firstSession, role, closing, OptionConverters.toScala(hostInfo).map(e ⇒ (e.first, e.second)))) + new javadsl.BidiFlow(scaladsl.TLS.apply(sslContext, None, firstSession, role, closing, OptionConverters.toScala(hostInfo).map(e => (e.first, e.second)))) /** * Create a StreamTls [[akka.stream.javadsl.BidiFlow]]. This is a low-level interface. @@ -134,8 +134,8 @@ object TLS { */ def create(sslEngineCreator: Supplier[SSLEngine], sessionVerifier: Consumer[SSLSession], closing: TLSClosing): BidiFlow[SslTlsOutbound, ByteString, ByteString, SslTlsInbound, NotUsed] = new javadsl.BidiFlow(scaladsl.TLS.apply( - () ⇒ sslEngineCreator.get(), - session ⇒ Try(sessionVerifier.accept(session)), + () => sslEngineCreator.get(), + session => Try(sessionVerifier.accept(session)), closing)) /** @@ -148,7 +148,7 @@ object TLS { */ def create(sslEngineCreator: Supplier[SSLEngine], closing: TLSClosing): BidiFlow[SslTlsOutbound, ByteString, ByteString, SslTlsInbound, NotUsed] = new javadsl.BidiFlow(scaladsl.TLS.apply( - () ⇒ sslEngineCreator.get(), + () => sslEngineCreator.get(), closing)) } diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/Tcp.scala b/akka-stream/src/main/scala/akka/stream/javadsl/Tcp.scala index 015405e2e7..b088732105 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/Tcp.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/Tcp.scala @@ -4,7 +4,7 @@ package akka.stream.javadsl -import java.lang.{ Iterable ⇒ JIterable } +import java.lang.{ Iterable => JIterable } import java.util.Optional import akka.{ Done, NotUsed } @@ -111,7 +111,7 @@ object Tcp extends ExtensionId[Tcp] with ExtensionIdProvider { class Tcp(system: ExtendedActorSystem) extends akka.actor.Extension { import Tcp._ - import akka.dispatch.ExecutionContexts.{ sameThreadExecutionContext ⇒ ec } + import akka.dispatch.ExecutionContexts.{ sameThreadExecutionContext => ec } private lazy val delegate: scaladsl.Tcp = scaladsl.Tcp(system) diff --git a/akka-stream/src/main/scala/akka/stream/javadsl/package.scala b/akka-stream/src/main/scala/akka/stream/javadsl/package.scala index 696396a11d..975b5b21fd 100644 --- a/akka-stream/src/main/scala/akka/stream/javadsl/package.scala +++ b/akka-stream/src/main/scala/akka/stream/javadsl/package.scala @@ -5,11 +5,11 @@ package akka.stream package object javadsl { - def combinerToScala[M1, M2, M](f: akka.japi.function.Function2[M1, M2, M]): (M1, M2) ⇒ M = + def combinerToScala[M1, M2, M](f: akka.japi.function.Function2[M1, M2, M]): (M1, M2) => M = f match { - case x if x eq Keep.left ⇒ scaladsl.Keep.left.asInstanceOf[(M1, M2) ⇒ M] - case x if x eq Keep.right ⇒ scaladsl.Keep.right.asInstanceOf[(M1, M2) ⇒ M] - case s: Function2[_, _, _] ⇒ s.asInstanceOf[(M1, M2) ⇒ M] - case other ⇒ other.apply _ + case x if x eq Keep.left => scaladsl.Keep.left.asInstanceOf[(M1, M2) => M] + case x if x eq Keep.right => scaladsl.Keep.right.asInstanceOf[(M1, M2) => M] + case s: Function2[_, _, _] => s.asInstanceOf[(M1, M2) => M] + case other => other.apply _ } } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/BidiFlow.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/BidiFlow.scala index ea13dcc3aa..e819c969a5 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/BidiFlow.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/BidiFlow.scala @@ -57,7 +57,7 @@ final class BidiFlow[-I1, +O1, -I2, +O2, +Mat]( * The `combine` function is used to compose the materialized values of this flow and that * flow into the materialized value of the resulting BidiFlow. */ - def atopMat[OO1, II2, Mat2, M](bidi: Graph[BidiShape[O1, OO1, II2, I2], Mat2])(combine: (Mat, Mat2) ⇒ M): BidiFlow[I1, OO1, II2, O2, M] = { + def atopMat[OO1, II2, Mat2, M](bidi: Graph[BidiShape[O1, OO1, II2, I2], Mat2])(combine: (Mat, Mat2) => M): BidiFlow[I1, OO1, II2, O2, M] = { val newBidi1Shape = shape.deepCopy() val newBidi2Shape = bidi.shape.deepCopy() @@ -115,7 +115,7 @@ final class BidiFlow[-I1, +O1, -I2, +O2, +Mat]( * The `combine` function is used to compose the materialized values of this flow and that * flow into the materialized value of the resulting [[Flow]]. */ - def joinMat[Mat2, M](flow: Graph[FlowShape[O1, I2], Mat2])(combine: (Mat, Mat2) ⇒ M): Flow[I1, O2, M] = { + def joinMat[Mat2, M](flow: Graph[FlowShape[O1, I2], Mat2])(combine: (Mat, Mat2) => M): Flow[I1, O2, M] = { val newBidiShape = shape.deepCopy() val newFlowShape = flow.shape.deepCopy() @@ -147,9 +147,9 @@ final class BidiFlow[-I1, +O1, -I2, +O2, +Mat]( /** * Transform only the materialized value of this BidiFlow, leaving all other properties as they were. */ - def mapMaterializedValue[Mat2](f: Mat ⇒ Mat2): BidiFlow[I1, O1, I2, O2, Mat2] = + def mapMaterializedValue[Mat2](f: Mat => Mat2): BidiFlow[I1, O1, I2, O2, Mat2] = new BidiFlow( - traversalBuilder.transformMat(f.asInstanceOf[Any ⇒ Any]), + traversalBuilder.transformMat(f.asInstanceOf[Any => Any]), shape ) @@ -218,9 +218,9 @@ object BidiFlow { */ def fromGraph[I1, O1, I2, O2, Mat](graph: Graph[BidiShape[I1, O1, I2, O2], Mat]): BidiFlow[I1, O1, I2, O2, Mat] = graph match { - case bidi: BidiFlow[I1, O1, I2, O2, Mat] ⇒ bidi - case bidi: javadsl.BidiFlow[I1, O1, I2, O2, Mat] ⇒ bidi.asScala - case other ⇒ + case bidi: BidiFlow[I1, O1, I2, O2, Mat] => bidi + case bidi: javadsl.BidiFlow[I1, O1, I2, O2, Mat] => bidi.asScala + case other => new BidiFlow( other.traversalBuilder, other.shape @@ -248,7 +248,7 @@ object BidiFlow { */ def fromFlowsMat[I1, O1, I2, O2, M1, M2, M]( flow1: Graph[FlowShape[I1, O1], M1], - flow2: Graph[FlowShape[I2, O2], M2])(combine: (M1, M2) ⇒ M): BidiFlow[I1, O1, I2, O2, M] = { + flow2: Graph[FlowShape[I2, O2], M2])(combine: (M1, M2) => M): BidiFlow[I1, O1, I2, O2, M] = { val newFlow1Shape = flow1.shape.deepCopy() val newFlow2Shape = flow2.shape.deepCopy() @@ -287,7 +287,7 @@ object BidiFlow { * Create a BidiFlow where the top and bottom flows are just one simple mapping * operator each, expressed by the two functions. */ - def fromFunctions[I1, O1, I2, O2](outbound: I1 ⇒ O1, inbound: I2 ⇒ O2): BidiFlow[I1, O1, I2, O2, NotUsed] = + def fromFunctions[I1, O1, I2, O2](outbound: I1 => O1, inbound: I2 => O2): BidiFlow[I1, O1, I2, O2, NotUsed] = fromFlows(Flow[I1].map(outbound), Flow[I2].map(inbound)) /** diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Compression.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Compression.scala index ca237b8a29..b3b02d6463 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Compression.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Compression.scala @@ -29,7 +29,7 @@ object Compression { * @param level Compression level (0-9) */ def gzip(level: Int): Flow[ByteString, ByteString, NotUsed] = - CompressionUtils.compressorFlow(() ⇒ new GzipCompressor(level)) + CompressionUtils.compressorFlow(() => new GzipCompressor(level)) /** * Creates a Flow that decompresses a gzip-compressed stream of data. @@ -58,7 +58,7 @@ object Compression { * */ def deflate(level: Int, nowrap: Boolean): Flow[ByteString, ByteString, NotUsed] = - CompressionUtils.compressorFlow(() ⇒ new DeflateCompressor(level, nowrap)) + CompressionUtils.compressorFlow(() => new DeflateCompressor(level, nowrap)) /** * Creates a Flow that decompresses a deflate-compressed stream of data. diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/FileIO.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/FileIO.scala index fb90881130..46a7e65d86 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/FileIO.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/FileIO.scala @@ -20,7 +20,7 @@ import scala.concurrent.Future */ object FileIO { - import Sink.{ shape ⇒ sinkShape } + import Sink.{ shape => sinkShape } /** * Creates a Source from a files contents. diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Flow.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Flow.scala index a16cae235f..c0db5cdd27 100755 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Flow.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Flow.scala @@ -47,7 +47,7 @@ final class Flow[-In, +Out, +Mat]( override def via[T, Mat2](flow: Graph[FlowShape[Out, T], Mat2]): Repr[T] = viaMat(flow)(Keep.left) - override def viaMat[T, Mat2, Mat3](flow: Graph[FlowShape[Out, T], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): Flow[In, T, Mat3] = { + override def viaMat[T, Mat2, Mat3](flow: Graph[FlowShape[Out, T], Mat2])(combine: (Mat, Mat2) => Mat3): Flow[In, T, Mat3] = { if (this.isIdentity) { // optimization by returning flow if possible since we know Mat2 == Mat3 from flow if (combine == Keep.right) Flow.fromGraph(flow).asInstanceOf[Flow[In, T, Mat3]] @@ -119,7 +119,7 @@ final class Flow[-In, +Out, +Mat]( * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): Sink[In, Mat3] = { + def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) => Mat3): Sink[In, Mat3] = { if (isIdentity) { new Sink( LinearTraversalBuilder.fromBuilder(sink.traversalBuilder, sink.shape, combine), @@ -134,7 +134,7 @@ final class Flow[-In, +Out, +Mat]( /** * Transform the materialized value of this Flow, leaving all other properties as they were. */ - override def mapMaterializedValue[Mat2](f: Mat ⇒ Mat2): ReprMat[Out, Mat2] = + override def mapMaterializedValue[Mat2](f: Mat => Mat2): ReprMat[Out, Mat2] = new Flow( traversalBuilder.transformMat(f), shape) @@ -169,7 +169,7 @@ final class Flow[-In, +Out, +Mat]( * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def joinMat[Mat2, Mat3](flow: Graph[FlowShape[Out, In], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): RunnableGraph[Mat3] = { + def joinMat[Mat2, Mat3](flow: Graph[FlowShape[Out, In], Mat2])(combine: (Mat, Mat2) => Mat3): RunnableGraph[Mat3] = { val resultBuilder = traversalBuilder .append(flow.traversalBuilder, flow.shape, combine) .wire(flow.shape.out, shape.in) @@ -215,7 +215,7 @@ final class Flow[-In, +Out, +Mat]( * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def joinMat[I2, O2, Mat2, M](bidi: Graph[BidiShape[Out, O2, I2, In], Mat2])(combine: (Mat, Mat2) ⇒ M): Flow[I2, O2, M] = { + def joinMat[I2, O2, Mat2, M](bidi: Graph[BidiShape[Out, O2, I2, In], Mat2])(combine: (Mat, Mat2) => M): Flow[I2, O2, M] = { val newBidiShape = bidi.shape.deepCopy() val newFlowShape = shape.deepCopy() @@ -299,7 +299,7 @@ final class Flow[-In, +Out, +Mat]( def toProcessor: RunnableGraph[Processor[In @uncheckedVariance, Out @uncheckedVariance]] = Source.asSubscriber[In].via(this).toMat(Sink.asPublisher[Out](false))(Keep.both[Subscriber[In], Publisher[Out]]) .mapMaterializedValue { - case (sub, pub) ⇒ new Processor[In, Out] { + case (sub, pub) => new Processor[In, Out] { override def onError(t: Throwable): Unit = sub.onError(t) override def onSubscribe(s: Subscription): Unit = sub.onSubscribe(s) override def onComplete(): Unit = sub.onComplete() @@ -317,11 +317,11 @@ final class Flow[-In, +Out, +Mat]( * API MAY CHANGE */ @ApiMayChange - def asFlowWithContext[U, CtxU, CtxOut](collapseContext: (U, CtxU) ⇒ In)(extractContext: Out ⇒ CtxOut): FlowWithContext[U, CtxU, Out, CtxOut, Mat] = + def asFlowWithContext[U, CtxU, CtxOut](collapseContext: (U, CtxU) => In)(extractContext: Out => CtxOut): FlowWithContext[U, CtxU, Out, CtxOut, Mat] = new FlowWithContext(Flow[(U, CtxU)].map { - case (e, ctx) ⇒ + case (e, ctx) => collapseContext(e, ctx) - }.viaMat(this)(Keep.right).map(e ⇒ (e, extractContext(e)))) + }.viaMat(this)(Keep.right).map(e => (e, extractContext(e)))) /** Converts this Scala DSL element to it's Java DSL counterpart. */ def asJava[JIn <: In]: javadsl.Flow[JIn, Out @uncheckedVariance, Mat @uncheckedVariance] = @@ -339,14 +339,14 @@ object Flow { /** * Creates a Flow from a Reactive Streams [[org.reactivestreams.Processor]] */ - def fromProcessor[I, O](processorFactory: () ⇒ Processor[I, O]): Flow[I, O, NotUsed] = { - fromProcessorMat(() ⇒ (processorFactory(), NotUsed)) + def fromProcessor[I, O](processorFactory: () => Processor[I, O]): Flow[I, O, NotUsed] = { + fromProcessorMat(() => (processorFactory(), NotUsed)) } /** * Creates a Flow from a Reactive Streams [[org.reactivestreams.Processor]] and returns a materialized value. */ - def fromProcessorMat[I, O, M](processorFactory: () ⇒ (Processor[I, O], M)): Flow[I, O, M] = + def fromProcessorMat[I, O, M](processorFactory: () => (Processor[I, O], M)): Flow[I, O, M] = fromGraph(ProcessorModule(processorFactory)) /** @@ -358,7 +358,7 @@ object Flow { * Creates a [Flow] which will use the given function to transform its inputs to outputs. It is equivalent * to `Flow[T].map(f)` */ - def fromFunction[A, B](f: A ⇒ B): Flow[A, B, NotUsed] = apply[A].map(f) + def fromFunction[A, B](f: A => B): Flow[A, B, NotUsed] = apply[A].map(f) /** * A graph with the shape of a flow logically is a flow, this method makes @@ -366,9 +366,9 @@ object Flow { */ def fromGraph[I, O, M](g: Graph[FlowShape[I, O], M]): Flow[I, O, M] = g match { - case f: Flow[I, O, M] ⇒ f - case f: javadsl.Flow[I, O, M] ⇒ f.asScala - case g: GraphStageWithMaterializedValue[FlowShape[I, O], M] ⇒ + case f: Flow[I, O, M] => f + case f: javadsl.Flow[I, O, M] => f.asScala + case g: GraphStageWithMaterializedValue[FlowShape[I, O], M] => // move these from the operator itself to make the returned source // behave as it is the operator with regards to attributes val attrs = g.traversalBuilder.attributes @@ -378,7 +378,7 @@ object Flow { noAttrStage.shape ).withAttributes(attrs) - case other ⇒ new Flow( + case other => new Flow( LinearTraversalBuilder.fromBuilder(g.traversalBuilder, g.shape, Keep.right), g.shape) } @@ -435,8 +435,8 @@ object Flow { * The `combine` function is used to compose the materialized values of the `sink` and `source` * into the materialized value of the resulting [[Flow]]. */ - def fromSinkAndSourceMat[I, O, M1, M2, M](sink: Graph[SinkShape[I], M1], source: Graph[SourceShape[O], M2])(combine: (M1, M2) ⇒ M): Flow[I, O, M] = - fromGraph(GraphDSL.create(sink, source)(combine) { implicit b ⇒ (in, out) ⇒ FlowShape(in.in, out.out) }) + def fromSinkAndSourceMat[I, O, M1, M2, M](sink: Graph[SinkShape[I], M1], source: Graph[SourceShape[O], M2])(combine: (M1, M2) => M): Flow[I, O, M] = + fromGraph(GraphDSL.create(sink, source)(combine) { implicit b => (in, out) => FlowShape(in.in, out.out) }) /** * Allows coupling termination (cancellation, completion, erroring) of Sinks and Sources while creating a Flow from them. @@ -525,7 +525,7 @@ object Flow { * The `combine` function is used to compose the materialized values of the `sink` and `source` * into the materialized value of the resulting [[Flow]]. */ - def fromSinkAndSourceCoupledMat[I, O, M1, M2, M](sink: Graph[SinkShape[I], M1], source: Graph[SourceShape[O], M2])(combine: (M1, M2) ⇒ M): Flow[I, O, M] = + def fromSinkAndSourceCoupledMat[I, O, M1, M2, M](sink: Graph[SinkShape[I], M1], source: Graph[SourceShape[O], M2])(combine: (M1, M2) => M): Flow[I, O, M] = // format: OFF Flow.fromGraph(GraphDSL.create(sink, source)(combine) { implicit b => (i, o) => import GraphDSL.Implicits._ @@ -551,8 +551,8 @@ object Flow { */ @Deprecated @deprecated("Use lazyInitAsync instead. (lazyInitAsync returns a flow with a more useful materialized value.)", "2.5.12") - def lazyInit[I, O, M](flowFactory: I ⇒ Future[Flow[I, O, M]], fallback: () ⇒ M): Flow[I, O, M] = - Flow.fromGraph(new LazyFlow[I, O, M](flowFactory)).mapMaterializedValue(_ ⇒ fallback()) + def lazyInit[I, O, M](flowFactory: I => Future[Flow[I, O, M]], fallback: () => M): Flow[I, O, M] = + Flow.fromGraph(new LazyFlow[I, O, M](flowFactory)).mapMaterializedValue(_ => fallback()) /** * Creates a real `Flow` upon receiving the first element. Internal `Flow` will not be created @@ -570,8 +570,8 @@ object Flow { * * '''Cancels when''' downstream cancels */ - def lazyInitAsync[I, O, M](flowFactory: () ⇒ Future[Flow[I, O, M]]): Flow[I, O, Future[Option[M]]] = - Flow.fromGraph(new LazyFlow[I, O, M](_ ⇒ flowFactory())) + def lazyInitAsync[I, O, M](flowFactory: () => Future[Flow[I, O, M]]): Flow[I, O, Future[Option[M]]] = + Flow.fromGraph(new LazyFlow[I, O, M](_ => flowFactory())) } object RunnableGraph { @@ -581,8 +581,8 @@ object RunnableGraph { */ def fromGraph[Mat](g: Graph[ClosedShape, Mat]): RunnableGraph[Mat] = g match { - case r: RunnableGraph[Mat] ⇒ r - case other ⇒ RunnableGraph(other.traversalBuilder) + case r: RunnableGraph[Mat] => r + case other => RunnableGraph(other.traversalBuilder) } } /** @@ -594,8 +594,8 @@ final case class RunnableGraph[+Mat](override val traversalBuilder: TraversalBui /** * Transform only the materialized value of this RunnableGraph, leaving all other properties as they were. */ - def mapMaterializedValue[Mat2](f: Mat ⇒ Mat2): RunnableGraph[Mat2] = - copy(traversalBuilder.transformMat(f.asInstanceOf[Any ⇒ Any])) + def mapMaterializedValue[Mat2](f: Mat => Mat2): RunnableGraph[Mat2] = + copy(traversalBuilder.transformMat(f.asInstanceOf[Any => Any])) /** * Run this flow and return the materialized instance from the flow. @@ -782,7 +782,7 @@ trait FlowOps[+Out, +Mat] { * '''Cancels when''' downstream cancels * */ - def map[T](f: Out ⇒ T): Repr[T] = via(Map(f)) + def map[T](f: Out => T): Repr[T] = via(Map(f)) /** * This is a simplified version of `wireTap(Sink)` that takes only a simple function. @@ -807,7 +807,7 @@ trait FlowOps[+Out, +Mat] { * '''Cancels when''' downstream cancels * */ - def wireTap(f: Out ⇒ Unit): Repr[Out] = + def wireTap(f: Out => Unit): Repr[Out] = wireTap(Sink.foreach(f)).named("wireTap") /** @@ -828,7 +828,7 @@ trait FlowOps[+Out, +Mat] { * '''Cancels when''' downstream cancels * */ - def mapConcat[T](f: Out ⇒ immutable.Iterable[T]): Repr[T] = statefulMapConcat(() ⇒ f) + def mapConcat[T](f: Out => immutable.Iterable[T]): Repr[T] = statefulMapConcat(() => f) /** * Transform each input element into an `Iterable` of output elements that is @@ -854,7 +854,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.mapConcat]] */ - def statefulMapConcat[T](f: () ⇒ Out ⇒ immutable.Iterable[T]): Repr[T] = + def statefulMapConcat[T](f: () => Out => immutable.Iterable[T]): Repr[T] = via(new StatefulMapConcat(f)) /** @@ -888,7 +888,7 @@ trait FlowOps[+Out, +Mat] { * * @see [[#mapAsyncUnordered]] */ - def mapAsync[T](parallelism: Int)(f: Out ⇒ Future[T]): Repr[T] = + def mapAsync[T](parallelism: Int)(f: Out => Future[T]): Repr[T] = if (parallelism == 1) mapAsyncUnordered[T](parallelism = 1)(f) // optimization for parallelism 1 else via(MapAsync(parallelism, f)) @@ -923,7 +923,7 @@ trait FlowOps[+Out, +Mat] { * * @see [[#mapAsync]] */ - def mapAsyncUnordered[T](parallelism: Int)(f: Out ⇒ Future[T]): Repr[T] = via(MapAsyncUnordered(parallelism, f)) + def mapAsyncUnordered[T](parallelism: Int)(f: Out => Future[T]): Repr[T] = via(MapAsyncUnordered(parallelism, f)) /** * Use the `ask` pattern to send a request-reply message to the target `ref` actor. @@ -997,13 +997,13 @@ trait FlowOps[+Out, +Mat] { def ask[S](parallelism: Int)(ref: ActorRef)(implicit timeout: Timeout, tag: ClassTag[S]): Repr[S] = { val askFlow = Flow[Out] .watch(ref) - .mapAsync(parallelism) { el ⇒ + .mapAsync(parallelism) { el => akka.pattern.ask(ref).?(el)(timeout).mapTo[S](tag) } .mapError { // the purpose of this recovery is to change the name of the stage in that exception // we do so in order to help users find which stage caused the failure -- "the ask stage" - case ex: WatchedActorTerminatedException ⇒ + case ex: WatchedActorTerminatedException => throw new WatchedActorTerminatedException("ask()", ex.ref) } .named("ask") @@ -1040,7 +1040,7 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def filter(p: Out ⇒ Boolean): Repr[Out] = via(Filter(p)) + def filter(p: Out => Boolean): Repr[Out] = via(Filter(p)) /** * Only pass on those elements that NOT satisfy the given predicate. @@ -1055,7 +1055,7 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def filterNot(p: Out ⇒ Boolean): Repr[Out] = + def filterNot(p: Out => Boolean): Repr[Out] = via(Flow[Out].filter(!p(_)).withAttributes(DefaultAttributes.filterNot)) /** @@ -1077,7 +1077,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.limit]], [[FlowOps.limitWeighted]] */ - def takeWhile(p: Out ⇒ Boolean): Repr[Out] = takeWhile(p, false) + def takeWhile(p: Out => Boolean): Repr[Out] = takeWhile(p, false) /** * Terminate processing (and cancel the upstream publisher) after predicate @@ -1100,7 +1100,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.limit]], [[FlowOps.limitWeighted]] */ - def takeWhile(p: Out ⇒ Boolean, inclusive: Boolean): Repr[Out] = via(TakeWhile(p, inclusive)) + def takeWhile(p: Out => Boolean, inclusive: Boolean): Repr[Out] = via(TakeWhile(p, inclusive)) /** * Discard elements at the beginning of the stream while predicate is true. @@ -1116,7 +1116,7 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def dropWhile(p: Out ⇒ Boolean): Repr[Out] = via(DropWhile(p)) + def dropWhile(p: Out => Boolean): Repr[Out] = via(DropWhile(p)) /** * Transform this stream by applying the given partial function to each of the elements @@ -1152,7 +1152,7 @@ trait FlowOps[+Out, +Mat] { * '''Cancels when''' downstream cancels */ def collectType[T](implicit tag: ClassTag[T]): Repr[T] = - collect { case c if tag.runtimeClass.isInstance(c) ⇒ c.asInstanceOf[T] } + collect { case c if tag.runtimeClass.isInstance(c) => c.asInstanceOf[T] } /** * Chunk up this stream into groups of the given size, with the last group @@ -1191,7 +1191,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.take]], [[FlowOps.takeWithin]], [[FlowOps.takeWhile]] */ - def limit(max: Long): Repr[Out] = limitWeighted(max)(_ ⇒ 1) + def limit(max: Long): Repr[Out] = limitWeighted(max)(_ => 1) /** * Ensure stream boundedness by evaluating the cost of incoming elements @@ -1217,7 +1217,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.take]], [[FlowOps.takeWithin]], [[FlowOps.takeWhile]] */ - def limitWeighted[T](max: Long)(costFn: Out ⇒ Long): Repr[Out] = via(LimitWeighted(max, costFn)) + def limitWeighted[T](max: Long)(costFn: Out => Long): Repr[Out] = via(LimitWeighted(max, costFn)) /** * Apply a sliding window over the stream and return the windows as groups of elements, with the last group @@ -1260,7 +1260,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.scanAsync]] */ - def scan[T](zero: T)(f: (T, Out) ⇒ T): Repr[T] = via(Scan(zero, f)) + def scan[T](zero: T)(f: (T, Out) => T): Repr[T] = via(Scan(zero, f)) /** * Similar to `scan` but with a asynchronous function, @@ -1290,7 +1290,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.scan]] */ - def scanAsync[T](zero: T)(f: (T, Out) ⇒ Future[T]): Repr[T] = via(ScanAsync(zero, f)) + def scanAsync[T](zero: T)(f: (T, Out) => Future[T]): Repr[T] = via(ScanAsync(zero, f)) /** * Similar to `scan` but only emits its result when the upstream completes, @@ -1315,7 +1315,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.scan]] */ - def fold[T](zero: T)(f: (T, Out) ⇒ T): Repr[T] = via(Fold(zero, f)) + def fold[T](zero: T)(f: (T, Out) => T): Repr[T] = via(Fold(zero, f)) /** * Similar to `fold` but with an asynchronous function. @@ -1340,7 +1340,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.fold]] */ - def foldAsync[T](zero: T)(f: (T, Out) ⇒ Future[T]): Repr[T] = via(new FoldAsync(zero, f)) + def foldAsync[T](zero: T)(f: (T, Out) => Future[T]): Repr[T] = via(new FoldAsync(zero, f)) /** * Similar to `fold` but uses first element as zero element. @@ -1364,7 +1364,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.fold]] */ - def reduce[T >: Out](f: (T, T) ⇒ T): Repr[T] = via(new Reduce[T](f)) + def reduce[T >: Out](f: (T, T) => T): Repr[T] = via(new Reduce[T](f)) /** * Intersperses stream with provided element, similar to how [[scala.collection.immutable.List.mkString]] @@ -1464,7 +1464,7 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream completes */ - def groupedWeightedWithin(maxWeight: Long, d: FiniteDuration)(costFn: Out ⇒ Long): Repr[immutable.Seq[Out]] = + def groupedWeightedWithin(maxWeight: Long, d: FiniteDuration)(costFn: Out => Long): Repr[immutable.Seq[Out]] = via(new GroupedWeightedWithin[Out](maxWeight, costFn, d)) /** @@ -1591,7 +1591,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.conflate]], [[FlowOps.limit]], [[FlowOps.limitWeighted]] [[FlowOps.batch]] [[FlowOps.batchWeighted]] */ - def conflateWithSeed[S](seed: Out ⇒ S)(aggregate: (S, Out) ⇒ S): Repr[S] = + def conflateWithSeed[S](seed: Out => S)(aggregate: (S, Out) => S): Repr[S] = via(Batch(1L, ConstantFun.zeroLong, seed, aggregate).withAttributes(DefaultAttributes.conflate)) /** @@ -1619,7 +1619,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.conflate]], [[FlowOps.limit]], [[FlowOps.limitWeighted]] [[FlowOps.batch]] [[FlowOps.batchWeighted]] */ - def conflate[O2 >: Out](aggregate: (O2, O2) ⇒ O2): Repr[O2] = conflateWithSeed[O2](ConstantFun.scalaIdentityFunction)(aggregate) + def conflate[O2 >: Out](aggregate: (O2, O2) => O2): Repr[O2] = conflateWithSeed[O2](ConstantFun.scalaIdentityFunction)(aggregate) /** * Allows a faster upstream to progress independently of a slower subscriber by aggregating elements into batches @@ -1645,7 +1645,7 @@ trait FlowOps[+Out, +Mat] { * @param seed Provides the first state for a batched value using the first unconsumed element as a start * @param aggregate Takes the currently batched value and the current pending element to produce a new aggregate */ - def batch[S](max: Long, seed: Out ⇒ S)(aggregate: (S, Out) ⇒ S): Repr[S] = + def batch[S](max: Long, seed: Out => S)(aggregate: (S, Out) => S): Repr[S] = via(Batch(max, ConstantFun.oneLong, seed, aggregate).withAttributes(DefaultAttributes.batch)) /** @@ -1676,7 +1676,7 @@ trait FlowOps[+Out, +Mat] { * @param seed Provides the first state for a batched value using the first unconsumed element as a start * @param aggregate Takes the currently batched value and the current pending element to produce a new batch */ - def batchWeighted[S](max: Long, costFn: Out ⇒ Long, seed: Out ⇒ S)(aggregate: (S, Out) ⇒ S): Repr[S] = + def batchWeighted[S](max: Long, costFn: Out => Long, seed: Out => S)(aggregate: (S, Out) => S): Repr[S] = via(Batch(max, costFn, seed, aggregate).withAttributes(DefaultAttributes.batchWeighted)) /** @@ -1704,7 +1704,7 @@ trait FlowOps[+Out, +Mat] { * @see [[#extrapolate]] for a version that always preserves the original element and allows for an initial "startup" * element. */ - def expand[U](expander: Out ⇒ Iterator[U]): Repr[U] = via(new Expand(expander)) + def expand[U](expander: Out => Iterator[U]): Repr[U] = via(new Expand(expander)) /** * Allows a faster downstream to progress independent of a slower upstream. @@ -1729,12 +1729,12 @@ trait FlowOps[+Out, +Mat] { * @param initial the initial element to be emitted, in case upstream is able to stall the entire stream. * @see [[#expand]] for a version that can overwrite the original element. */ - def extrapolate[U >: Out](extrapolator: U ⇒ Iterator[U], initial: Option[U] = None): Repr[U] = { - val expandArg = (u: U) ⇒ Iterator.single(u) ++ extrapolator(u) + def extrapolate[U >: Out](extrapolator: U => Iterator[U], initial: Option[U] = None): Repr[U] = { + val expandArg = (u: U) => Iterator.single(u) ++ extrapolator(u) val expandStep = new Expand[U, U](expandArg) - initial.map(e ⇒ prepend(Source.single(e)).via(expandStep)).getOrElse(via(expandStep)) + initial.map(e => prepend(Source.single(e)).via(expandStep)).getOrElse(via(expandStep)) } /** @@ -1839,14 +1839,14 @@ trait FlowOps[+Out, +Mat] { * @param allowClosedSubstreamRecreation enables recreation of already closed substreams if elements with their * corresponding keys arrive after completion */ - def groupBy[K](maxSubstreams: Int, f: Out ⇒ K, allowClosedSubstreamRecreation: Boolean): SubFlow[Out, Mat, Repr, Closed] = { + def groupBy[K](maxSubstreams: Int, f: Out => K, allowClosedSubstreamRecreation: Boolean): SubFlow[Out, Mat, Repr, Closed] = { val merge = new SubFlowImpl.MergeBack[Out, Repr] { override def apply[T](flow: Flow[Out, T, NotUsed], breadth: Int): Repr[T] = via(new GroupBy(maxSubstreams, f, allowClosedSubstreamRecreation)) .map(_.via(flow)) .via(new FlattenMerge(breadth)) } - val finish: (Sink[Out, NotUsed]) ⇒ Closed = s ⇒ + val finish: (Sink[Out, NotUsed]) => Closed = s => via(new GroupBy(maxSubstreams, f, allowClosedSubstreamRecreation)) .to(Sink.foreach(_.runWith(s)(GraphInterpreter.currentInterpreter.materializer))) new SubFlowImpl(Flow[Out], merge, finish) @@ -1865,7 +1865,7 @@ trait FlowOps[+Out, +Mat] { * * @see [[#groupBy]] */ - def groupBy[K](maxSubstreams: Int, f: Out ⇒ K): SubFlow[Out, Mat, Repr, Closed] = groupBy(maxSubstreams, f, false) + def groupBy[K](maxSubstreams: Int, f: Out => K): SubFlow[Out, Mat, Repr, Closed] = groupBy(maxSubstreams, f, false) /** * This operation applies the given predicate to all incoming elements and @@ -1921,7 +1921,7 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.splitAfter]]. */ - def splitWhen(substreamCancelStrategy: SubstreamCancelStrategy)(p: Out ⇒ Boolean): SubFlow[Out, Mat, Repr, Closed] = { + def splitWhen(substreamCancelStrategy: SubstreamCancelStrategy)(p: Out => Boolean): SubFlow[Out, Mat, Repr, Closed] = { val merge = new SubFlowImpl.MergeBack[Out, Repr] { override def apply[T](flow: Flow[Out, T, NotUsed], breadth: Int): Repr[T] = via(Split.when(p, substreamCancelStrategy)) @@ -1929,7 +1929,7 @@ trait FlowOps[+Out, +Mat] { .via(new FlattenMerge(breadth)) } - val finish: (Sink[Out, NotUsed]) ⇒ Closed = s ⇒ + val finish: (Sink[Out, NotUsed]) => Closed = s => via(Split.when(p, substreamCancelStrategy)) .to(Sink.foreach(_.runWith(s)(GraphInterpreter.currentInterpreter.materializer))) @@ -1943,7 +1943,7 @@ trait FlowOps[+Out, +Mat] { * * @see [[#splitWhen]] */ - def splitWhen(p: Out ⇒ Boolean): SubFlow[Out, Mat, Repr, Closed] = + def splitWhen(p: Out => Boolean): SubFlow[Out, Mat, Repr, Closed] = splitWhen(SubstreamCancelStrategy.drain)(p) /** @@ -1991,14 +1991,14 @@ trait FlowOps[+Out, +Mat] { * * See also [[FlowOps.splitWhen]]. */ - def splitAfter(substreamCancelStrategy: SubstreamCancelStrategy)(p: Out ⇒ Boolean): SubFlow[Out, Mat, Repr, Closed] = { + def splitAfter(substreamCancelStrategy: SubstreamCancelStrategy)(p: Out => Boolean): SubFlow[Out, Mat, Repr, Closed] = { val merge = new SubFlowImpl.MergeBack[Out, Repr] { override def apply[T](flow: Flow[Out, T, NotUsed], breadth: Int): Repr[T] = via(Split.after(p, substreamCancelStrategy)) .map(_.via(flow)) .via(new FlattenMerge(breadth)) } - val finish: (Sink[Out, NotUsed]) ⇒ Closed = s ⇒ + val finish: (Sink[Out, NotUsed]) => Closed = s => via(Split.after(p, substreamCancelStrategy)) .to(Sink.foreach(_.runWith(s)(GraphInterpreter.currentInterpreter.materializer))) new SubFlowImpl(Flow[Out], merge, finish) @@ -2011,7 +2011,7 @@ trait FlowOps[+Out, +Mat] { * * @see [[#splitAfter]] */ - def splitAfter(p: Out ⇒ Boolean): SubFlow[Out, Mat, Repr, Closed] = + def splitAfter(p: Out => Boolean): SubFlow[Out, Mat, Repr, Closed] = splitAfter(SubstreamCancelStrategy.drain)(p) /** @@ -2027,7 +2027,7 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def flatMapConcat[T, M](f: Out ⇒ Graph[SourceShape[T], M]): Repr[T] = map(f).via(new FlattenMerge[T, M](1)) + def flatMapConcat[T, M](f: Out => Graph[SourceShape[T], M]): Repr[T] = map(f).via(new FlattenMerge[T, M](1)) /** * Transform each input element into a `Source` of output elements that is @@ -2042,7 +2042,7 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def flatMapMerge[T, M](breadth: Int, f: Out ⇒ Graph[SourceShape[T], M]): Repr[T] = map(f).via(new FlattenMerge[T, M](breadth)) + def flatMapMerge[T, M](breadth: Int, f: Out => Graph[SourceShape[T], M]): Repr[T] = map(f).via(new FlattenMerge[T, M](breadth)) /** * If the first element has not passed through this operator before the provided timeout, the stream is failed @@ -2119,7 +2119,7 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def keepAlive[U >: Out](maxIdle: FiniteDuration, injectedElem: () ⇒ U): Repr[U] = + def keepAlive[U >: Out](maxIdle: FiniteDuration, injectedElem: () => U): Repr[U] = via(new Timers.IdleInject[Out, U](maxIdle, injectedElem)) /** @@ -2226,7 +2226,7 @@ trait FlowOps[+Out, +Mat] { * '''Cancels when''' downstream cancels * */ - def throttle(cost: Int, per: FiniteDuration, costCalculation: (Out) ⇒ Int): Repr[Out] = + def throttle(cost: Int, per: FiniteDuration, costCalculation: (Out) => Int): Repr[Out] = via(new Throttle(cost, per, Throttle.AutomaticMaximumBurst, costCalculation, ThrottleMode.Shaping)) /** @@ -2269,7 +2269,7 @@ trait FlowOps[+Out, +Mat] { * */ def throttle(cost: Int, per: FiniteDuration, maximumBurst: Int, - costCalculation: (Out) ⇒ Int, mode: ThrottleMode): Repr[Out] = + costCalculation: (Out) => Int, mode: ThrottleMode): Repr[Out] = via(new Throttle(cost, per, maximumBurst, costCalculation, mode)) /** @@ -2301,7 +2301,7 @@ trait FlowOps[+Out, +Mat] { @Deprecated @deprecated("Use throttle without `maximumBurst` parameter instead.", "2.5.12") def throttleEven(cost: Int, per: FiniteDuration, - costCalculation: (Out) ⇒ Int, mode: ThrottleMode): Repr[Out] = + costCalculation: (Out) => Int, mode: ThrottleMode): Repr[Out] = throttle(cost, per, Throttle.AutomaticMaximumBurst, costCalculation, mode) /** @@ -2350,8 +2350,8 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def log(name: String, extract: Out ⇒ Any = ConstantFun.scalaIdentityFunction)(implicit log: LoggingAdapter = null): Repr[Out] = - via(Log(name, extract.asInstanceOf[Any ⇒ Any], Option(log))) + def log(name: String, extract: Out => Any = ConstantFun.scalaIdentityFunction)(implicit log: LoggingAdapter = null): Repr[Out] = + via(Log(name, extract.asInstanceOf[Any => Any], Option(log))) /** * Combine the elements of current flow and the given [[Source]] into a stream of tuples. @@ -2367,7 +2367,7 @@ trait FlowOps[+Out, +Mat] { def zip[U](that: Graph[SourceShape[U], _]): Repr[(Out, U)] = via(zipGraph(that)) protected def zipGraph[U, M](that: Graph[SourceShape[U], M]): Graph[FlowShape[Out @uncheckedVariance, (Out, U)], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => val zip = b.add(Zip[Out, U]()) r ~> zip.in1 FlowShape(zip.in0, zip.out) @@ -2392,7 +2392,7 @@ trait FlowOps[+Out, +Mat] { def zipLatest[U](that: Graph[SourceShape[U], _]): Repr[(Out, U)] = via(zipLatestGraph(that)) protected def zipLatestGraph[U, M](that: Graph[SourceShape[U], M]): Graph[FlowShape[Out @uncheckedVariance, (Out, U)], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => val zip = b.add(ZipLatest[Out, U]()) r ~> zip.in1 FlowShape(zip.in0, zip.out) @@ -2410,11 +2410,11 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def zipWith[Out2, Out3](that: Graph[SourceShape[Out2], _])(combine: (Out, Out2) ⇒ Out3): Repr[Out3] = + def zipWith[Out2, Out3](that: Graph[SourceShape[Out2], _])(combine: (Out, Out2) => Out3): Repr[Out3] = via(zipWithGraph(that)(combine)) - protected def zipWithGraph[Out2, Out3, M](that: Graph[SourceShape[Out2], M])(combine: (Out, Out2) ⇒ Out3): Graph[FlowShape[Out @uncheckedVariance, Out3], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + protected def zipWithGraph[Out2, Out3, M](that: Graph[SourceShape[Out2], M])(combine: (Out, Out2) => Out3): Graph[FlowShape[Out @uncheckedVariance, Out3], M] = + GraphDSL.create(that) { implicit b => r => val zip = b.add(ZipWith[Out, Out2, Out3](combine)) r ~> zip.in1 FlowShape(zip.in0, zip.out) @@ -2437,11 +2437,11 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def zipLatestWith[Out2, Out3](that: Graph[SourceShape[Out2], _])(combine: (Out, Out2) ⇒ Out3): Repr[Out3] = + def zipLatestWith[Out2, Out3](that: Graph[SourceShape[Out2], _])(combine: (Out, Out2) => Out3): Repr[Out3] = via(zipLatestWithGraph(that)(combine)) - protected def zipLatestWithGraph[Out2, Out3, M](that: Graph[SourceShape[Out2], M])(combine: (Out, Out2) ⇒ Out3): Graph[FlowShape[Out @uncheckedVariance, Out3], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + protected def zipLatestWithGraph[Out2, Out3, M](that: Graph[SourceShape[Out2], M])(combine: (Out, Out2) => Out3): Graph[FlowShape[Out @uncheckedVariance, Out3], M] = + GraphDSL.create(that) { implicit b => r => val zip = b.add(ZipLatestWith[Out, Out2, Out3](combine)) r ~> zip.in1 FlowShape(zip.in0, zip.out) @@ -2460,9 +2460,9 @@ trait FlowOps[+Out, +Mat] { * '''Cancels when''' downstream cancels */ def zipWithIndex: Repr[(Out, Long)] = { - statefulMapConcat[(Out, Long)] { () ⇒ + statefulMapConcat[(Out, Long)] { () => var index: Long = 0L - elem ⇒ { + elem => { val zipped = (elem, index) index += 1 immutable.Iterable[(Out, Long)](zipped) @@ -2523,7 +2523,7 @@ trait FlowOps[+Out, +Mat] { that: Graph[SourceShape[U], M], segmentSize: Int, eagerClose: Boolean = false): Graph[FlowShape[Out @uncheckedVariance, U], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => val interleave = b.add(Interleave[U](2, segmentSize, eagerClose)) r ~> interleave.in(1) FlowShape(interleave.in(0), interleave.out) @@ -2545,7 +2545,7 @@ trait FlowOps[+Out, +Mat] { via(mergeGraph(that, eagerComplete)) protected def mergeGraph[U >: Out, M](that: Graph[SourceShape[U], M], eagerComplete: Boolean): Graph[FlowShape[Out @uncheckedVariance, U], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => val merge = b.add(Merge[U](2, eagerComplete)) r ~> merge.in(1) FlowShape(merge.in(0), merge.out) @@ -2570,7 +2570,7 @@ trait FlowOps[+Out, +Mat] { via(mergeSortedGraph(that)) protected def mergeSortedGraph[U >: Out, M](that: Graph[SourceShape[U], M])(implicit ord: Ordering[U]): Graph[FlowShape[Out @uncheckedVariance, U], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => val merge = b.add(new MergeSorted[U]) r ~> merge.in1 FlowShape(merge.in0, merge.out) @@ -2598,7 +2598,7 @@ trait FlowOps[+Out, +Mat] { via(concatGraph(that)) protected def concatGraph[U >: Out, Mat2](that: Graph[SourceShape[U], Mat2]): Graph[FlowShape[Out @uncheckedVariance, U], Mat2] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => val merge = b.add(Concat[U]()) r ~> merge.in(1) FlowShape(merge.in(0), merge.out) @@ -2626,7 +2626,7 @@ trait FlowOps[+Out, +Mat] { via(prependGraph(that)) protected def prependGraph[U >: Out, Mat2](that: Graph[SourceShape[U], Mat2]): Graph[FlowShape[Out @uncheckedVariance, U], Mat2] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => val merge = b.add(Concat[U]()) r ~> merge.in(0) FlowShape(merge.in(1), merge.out) @@ -2658,7 +2658,7 @@ trait FlowOps[+Out, +Mat] { via(orElseGraph(secondary)) protected def orElseGraph[U >: Out, Mat2](secondary: Graph[SourceShape[U], Mat2]): Graph[FlowShape[Out @uncheckedVariance, U], Mat2] = - GraphDSL.create(secondary) { implicit b ⇒ secondary ⇒ + GraphDSL.create(secondary) { implicit b => secondary => val orElse = b.add(OrElse[U]()) secondary ~> orElse.in(1) @@ -2714,7 +2714,7 @@ trait FlowOps[+Out, +Mat] { def alsoTo(that: Graph[SinkShape[Out], _]): Repr[Out] = via(alsoToGraph(that)) protected def alsoToGraph[M](that: Graph[SinkShape[Out], M]): Graph[FlowShape[Out @uncheckedVariance, Out], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => import GraphDSL.Implicits._ val bcast = b.add(Broadcast[Out](2, eagerCancel = true)) bcast.out(1) ~> r @@ -2733,12 +2733,12 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' any of the downstreams cancel */ - def divertTo(that: Graph[SinkShape[Out], _], when: Out ⇒ Boolean): Repr[Out] = via(divertToGraph(that, when)) + def divertTo(that: Graph[SinkShape[Out], _], when: Out => Boolean): Repr[Out] = via(divertToGraph(that, when)) - protected def divertToGraph[M](that: Graph[SinkShape[Out], M], when: Out ⇒ Boolean): Graph[FlowShape[Out @uncheckedVariance, Out], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + protected def divertToGraph[M](that: Graph[SinkShape[Out], M], when: Out => Boolean): Graph[FlowShape[Out @uncheckedVariance, Out], M] = + GraphDSL.create(that) { implicit b => r => import GraphDSL.Implicits._ - val partition = b.add(new Partition[Out](2, out ⇒ if (when(out)) 1 else 0, true)) + val partition = b.add(new Partition[Out](2, out => if (when(out)) 1 else 0, true)) partition.out(1) ~> r FlowShape(partition.in, partition.out(0)) } @@ -2762,7 +2762,7 @@ trait FlowOps[+Out, +Mat] { def wireTap(that: Graph[SinkShape[Out], _]): Repr[Out] = via(wireTapGraph(that)) protected def wireTapGraph[M](that: Graph[SinkShape[Out], M]): Graph[FlowShape[Out @uncheckedVariance, Out], M] = - GraphDSL.create(that) { implicit b ⇒ r ⇒ + GraphDSL.create(that) { implicit b => r => import GraphDSL.Implicits._ val bcast = b.add(WireTap[Out]()) bcast.out1 ~> r @@ -2827,7 +2827,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def viaMat[T, Mat2, Mat3](flow: Graph[FlowShape[Out, T], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): ReprMat[T, Mat3] + def viaMat[T, Mat2, Mat3](flow: Graph[FlowShape[Out, T], Mat2])(combine: (Mat, Mat2) => Mat3): ReprMat[T, Mat3] /** * Connect this [[Flow]] to a [[Sink]], concatenating the processing steps of both. @@ -2848,7 +2848,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): ClosedMat[Mat3] + def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) => Mat3): ClosedMat[Mat3] /** * Combine the elements of current flow and the given [[Source]] into a stream of tuples. @@ -2858,7 +2858,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def zipMat[U, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[(Out, U), Mat3] = + def zipMat[U, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) => Mat3): ReprMat[(Out, U), Mat3] = viaMat(zipGraph(that))(matF) /** @@ -2870,7 +2870,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def zipWithMat[Out2, Out3, Mat2, Mat3](that: Graph[SourceShape[Out2], Mat2])(combine: (Out, Out2) ⇒ Out3)(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[Out3, Mat3] = + def zipWithMat[Out2, Out3, Mat2, Mat3](that: Graph[SourceShape[Out2], Mat2])(combine: (Out, Out2) => Out3)(matF: (Mat, Mat2) => Mat3): ReprMat[Out3, Mat3] = viaMat(zipWithGraph(that)(combine))(matF) /** @@ -2882,7 +2882,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def zipLatestMat[U, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[(Out, U), Mat3] = + def zipLatestMat[U, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) => Mat3): ReprMat[(Out, U), Mat3] = viaMat(zipLatestGraph(that))(matF) /** @@ -2894,7 +2894,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def zipLatestWithMat[Out2, Out3, Mat2, Mat3](that: Graph[SourceShape[Out2], Mat2])(combine: (Out, Out2) ⇒ Out3)(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[Out3, Mat3] = + def zipLatestWithMat[Out2, Out3, Mat2, Mat3](that: Graph[SourceShape[Out2], Mat2])(combine: (Out, Out2) => Out3)(matF: (Mat, Mat2) => Mat3): ReprMat[Out3, Mat3] = viaMat(zipLatestWithGraph(that)(combine))(matF) /** @@ -2906,7 +2906,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def mergeMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2], eagerComplete: Boolean = false)(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[U, Mat3] = + def mergeMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2], eagerComplete: Boolean = false)(matF: (Mat, Mat2) => Mat3): ReprMat[U, Mat3] = viaMat(mergeGraph(that, eagerComplete))(matF) /** @@ -2923,7 +2923,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def interleaveMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2], request: Int)(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[U, Mat3] = + def interleaveMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2], request: Int)(matF: (Mat, Mat2) => Mat3): ReprMat[U, Mat3] = interleaveMat(that, request, eagerClose = false)(matF) /** @@ -2942,7 +2942,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def interleaveMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2], request: Int, eagerClose: Boolean)(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[U, Mat3] = + def interleaveMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2], request: Int, eagerClose: Boolean)(matF: (Mat, Mat2) => Mat3): ReprMat[U, Mat3] = viaMat(interleaveGraph(that, request, eagerClose))(matF) /** @@ -2957,7 +2957,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def mergeSortedMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) ⇒ Mat3)(implicit ord: Ordering[U]): ReprMat[U, Mat3] = + def mergeSortedMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) => Mat3)(implicit ord: Ordering[U]): ReprMat[U, Mat3] = viaMat(mergeSortedGraph(that))(matF) /** @@ -2975,7 +2975,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def concatMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[U, Mat3] = + def concatMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) => Mat3): ReprMat[U, Mat3] = viaMat(concatGraph(that))(matF) /** @@ -2993,7 +2993,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def prependMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[U, Mat3] = + def prependMat[U >: Out, Mat2, Mat3](that: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) => Mat3): ReprMat[U, Mat3] = viaMat(prependGraph(that))(matF) /** @@ -3018,7 +3018,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * '''Cancels when''' downstream cancels and additionally the alternative is cancelled as soon as an element passes * by from this stream. */ - def orElseMat[U >: Out, Mat2, Mat3](secondary: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[U, Mat3] = + def orElseMat[U >: Out, Mat2, Mat3](secondary: Graph[SourceShape[U], Mat2])(matF: (Mat, Mat2) => Mat3): ReprMat[U, Mat3] = viaMat(orElseGraph(secondary))(matF) /** @@ -3030,7 +3030,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def alsoToMat[Mat2, Mat3](that: Graph[SinkShape[Out], Mat2])(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[Out, Mat3] = + def alsoToMat[Mat2, Mat3](that: Graph[SinkShape[Out], Mat2])(matF: (Mat, Mat2) => Mat3): ReprMat[Out, Mat3] = viaMat(alsoToGraph(that))(matF) /** @@ -3042,7 +3042,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def divertToMat[Mat2, Mat3](that: Graph[SinkShape[Out], Mat2], when: Out ⇒ Boolean)(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[Out, Mat3] = + def divertToMat[Mat2, Mat3](that: Graph[SinkShape[Out], Mat2], when: Out => Boolean)(matF: (Mat, Mat2) => Mat3): ReprMat[Out, Mat3] = viaMat(divertToGraph(that, when))(matF) /** @@ -3057,7 +3057,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def wireTapMat[Mat2, Mat3](that: Graph[SinkShape[Out], Mat2])(matF: (Mat, Mat2) ⇒ Mat3): ReprMat[Out, Mat3] = + def wireTapMat[Mat2, Mat3](that: Graph[SinkShape[Out], Mat2])(matF: (Mat, Mat2) => Mat3): ReprMat[Out, Mat3] = viaMat(wireTapGraph(that))(matF) /** @@ -3069,13 +3069,13 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def watchTermination[Mat2]()(matF: (Mat, Future[Done]) ⇒ Mat2): ReprMat[Out, Mat2] = + def watchTermination[Mat2]()(matF: (Mat, Future[Done]) => Mat2): ReprMat[Out, Mat2] = viaMat(GraphStages.terminationWatcher)(matF) /** * Transform the materialized value of this graph, leaving all other properties as they were. */ - def mapMaterializedValue[Mat2](f: Mat ⇒ Mat2): ReprMat[Out, Mat2] + def mapMaterializedValue[Mat2](f: Mat => Mat2): ReprMat[Out, Mat2] /** * Materializes to `FlowMonitor[Out]` that allows monitoring of the current flow. All events are propagated @@ -3086,7 +3086,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { */ @Deprecated @deprecated("Use monitor() or monitorMat(combine) instead", "2.5.17") - def monitor[Mat2]()(combine: (Mat, FlowMonitor[Out]) ⇒ Mat2): ReprMat[Out, Mat2] = + def monitor[Mat2]()(combine: (Mat, FlowMonitor[Out]) => Mat2): ReprMat[Out, Mat2] = viaMat(GraphStages.monitor)(combine) /** @@ -3096,7 +3096,7 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * * The `combine` function is used to combine the `FlowMonitor` with this flow's materialized value. */ - def monitorMat[Mat2](combine: (Mat, FlowMonitor[Out]) ⇒ Mat2): ReprMat[Out, Mat2] = + def monitorMat[Mat2](combine: (Mat, FlowMonitor[Out]) => Mat2): ReprMat[Out, Mat2] = viaMat(GraphStages.monitor)(combine) /** diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/FlowWithContext.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/FlowWithContext.scala index d8bb4adb5d..c34a6b4fab 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/FlowWithContext.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/FlowWithContext.scala @@ -48,7 +48,7 @@ final class FlowWithContext[-In, -CtxIn, +Out, +CtxOut, +Mat]( override def via[Out2, Ctx2, Mat2](viaFlow: Graph[FlowShape[(Out, CtxOut), (Out2, Ctx2)], Mat2]): Repr[Out2, Ctx2] = new FlowWithContext(delegate.via(viaFlow)) - override def viaMat[Out2, Ctx2, Mat2, Mat3](flow: Graph[FlowShape[(Out, CtxOut), (Out2, Ctx2)], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): FlowWithContext[In, CtxIn, Out2, Ctx2, Mat3] = + override def viaMat[Out2, Ctx2, Mat2, Mat3](flow: Graph[FlowShape[(Out, CtxOut), (Out2, Ctx2)], Mat2])(combine: (Mat, Mat2) => Mat3): FlowWithContext[In, CtxIn, Out2, Ctx2, Mat3] = new FlowWithContext(delegate.viaMat(flow)(combine)) /** diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/FlowWithContextOps.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/FlowWithContextOps.scala index 820163033f..dd08135158 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/FlowWithContextOps.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/FlowWithContextOps.scala @@ -51,23 +51,23 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { * * @see [[akka.stream.scaladsl.FlowOps.viaMat]] */ - def viaMat[Out2, Ctx2, Mat2, Mat3](flow: Graph[FlowShape[(Out, Ctx), (Out2, Ctx2)], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): ReprMat[Out2, Ctx2, Mat3] + def viaMat[Out2, Ctx2, Mat2, Mat3](flow: Graph[FlowShape[(Out, Ctx), (Out2, Ctx2)], Mat2])(combine: (Mat, Mat2) => Mat3): ReprMat[Out2, Ctx2, Mat3] /** * Context-preserving variant of [[akka.stream.scaladsl.FlowOps.map]]. * * @see [[akka.stream.scaladsl.FlowOps.map]] */ - def map[Out2](f: Out ⇒ Out2): Repr[Out2, Ctx] = - via(flow.map { case (e, ctx) ⇒ (f(e), ctx) }) + def map[Out2](f: Out => Out2): Repr[Out2, Ctx] = + via(flow.map { case (e, ctx) => (f(e), ctx) }) /** * Context-preserving variant of [[akka.stream.scaladsl.FlowOps.mapAsync]]. * * @see [[akka.stream.scaladsl.FlowOps.mapAsync]] */ - def mapAsync[Out2](parallelism: Int)(f: Out ⇒ Future[Out2]): Repr[Out2, Ctx] = - via(flow.mapAsync(parallelism) { case (e, ctx) ⇒ f(e).map(o ⇒ (o, ctx))(ExecutionContexts.sameThreadExecutionContext) }) + def mapAsync[Out2](parallelism: Int)(f: Out => Future[Out2]): Repr[Out2, Ctx] = + via(flow.mapAsync(parallelism) { case (e, ctx) => f(e).map(o => (o, ctx))(ExecutionContexts.sameThreadExecutionContext) }) /** * Context-preserving variant of [[akka.stream.scaladsl.FlowOps.collect]]. @@ -78,7 +78,7 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { */ def collect[Out2](f: PartialFunction[Out, Out2]): Repr[Out2, Ctx] = via(flow.collect { - case (e, ctx) if f.isDefinedAt(e) ⇒ (f(e), ctx) + case (e, ctx) if f.isDefinedAt(e) => (f(e), ctx) }) /** @@ -88,8 +88,8 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { * * @see [[akka.stream.scaladsl.FlowOps.filter]] */ - def filter(pred: Out ⇒ Boolean): Repr[Out, Ctx] = - collect { case e if pred(e) ⇒ e } + def filter(pred: Out => Boolean): Repr[Out, Ctx] = + collect { case e if pred(e) => e } /** * Context-preserving variant of [[akka.stream.scaladsl.FlowOps.filterNot]]. @@ -98,8 +98,8 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { * * @see [[akka.stream.scaladsl.FlowOps.filterNot]] */ - def filterNot(pred: Out ⇒ Boolean): Repr[Out, Ctx] = - collect { case e if !pred(e) ⇒ e } + def filterNot(pred: Out => Boolean): Repr[Out, Ctx] = + collect { case e if !pred(e) => e } /** * Context-preserving variant of [[akka.stream.scaladsl.FlowOps.grouped]]. @@ -109,7 +109,7 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { * @see [[akka.stream.scaladsl.FlowOps.grouped]] */ def grouped(n: Int): Repr[immutable.Seq[Out], immutable.Seq[Ctx]] = - via(flow.grouped(n).map { elsWithContext ⇒ + via(flow.grouped(n).map { elsWithContext => val (els, ctxs) = elsWithContext.unzip (els, ctxs) }) @@ -122,7 +122,7 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { * @see [[akka.stream.scaladsl.FlowOps.sliding]] */ def sliding(n: Int, step: Int = 1): Repr[immutable.Seq[Out], immutable.Seq[Ctx]] = - via(flow.sliding(n, step).map { elsWithContext ⇒ + via(flow.sliding(n, step).map { elsWithContext => val (els, ctxs) = elsWithContext.unzip (els, ctxs) }) @@ -155,24 +155,24 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { * * @see [[akka.stream.scaladsl.FlowOps.mapConcat]] */ - def mapConcat[Out2](f: Out ⇒ immutable.Iterable[Out2]): Repr[Out2, Ctx] = + def mapConcat[Out2](f: Out => immutable.Iterable[Out2]): Repr[Out2, Ctx] = via(flow.mapConcat { - case (e, ctx) ⇒ f(e).map(_ -> ctx) + case (e, ctx) => f(e).map(_ -> ctx) }) /** * Apply the given function to each context element (leaving the data elements unchanged). */ - def mapContext[Ctx2](f: Ctx ⇒ Ctx2): Repr[Out, Ctx2] = - via(flow.map { case (e, ctx) ⇒ (e, f(ctx)) }) + def mapContext[Ctx2](f: Ctx => Ctx2): Repr[Out, Ctx2] = + via(flow.map { case (e, ctx) => (e, f(ctx)) }) /** * Context-preserving variant of [[akka.stream.scaladsl.FlowOps.log]]. * * @see [[akka.stream.scaladsl.FlowOps.log]] */ - def log(name: String, extract: Out ⇒ Any = ConstantFun.scalaIdentityFunction)(implicit log: LoggingAdapter = null): Repr[Out, Ctx] = { - val extractWithContext: ((Out, Ctx)) ⇒ Any = { case (e, _) ⇒ extract(e) } + def log(name: String, extract: Out => Any = ConstantFun.scalaIdentityFunction)(implicit log: LoggingAdapter = null): Repr[Out, Ctx] = { + val extractWithContext: ((Out, Ctx)) => Any = { case (e, _) => extract(e) } via(flow.log(name, extractWithContext)(log)) } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Framing.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Framing.scala index 05bddd4e33..de5e9a2434 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Framing.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Framing.scala @@ -85,7 +85,7 @@ object Framing { fieldOffset: Int, maximumFrameLength: Int, byteOrder: ByteOrder, - computeFrameSize: (Array[Byte], Int) ⇒ Int): Flow[ByteString, ByteString, NotUsed] = { + computeFrameSize: (Array[Byte], Int) => Int): Flow[ByteString, ByteString, NotUsed] = { require(fieldLength >= 1 && fieldLength <= 4, "Length field length must be 1, 2, 3 or 4.") Flow[ByteString].via(new LengthFieldFramingStage(fieldLength, fieldOffset, maximumFrameLength, byteOrder, Some(computeFrameSize))) .named("lengthFieldFraming") @@ -139,7 +139,7 @@ object Framing { class FramingException(msg: String) extends RuntimeException(msg) - private final val bigEndianDecoder: (ByteIterator, Int) ⇒ Int = (bs, length) ⇒ { + private final val bigEndianDecoder: (ByteIterator, Int) => Int = (bs, length) => { var count = length var decoded = 0 while (count > 0) { @@ -150,7 +150,7 @@ object Framing { decoded } - private final val littleEndianDecoder: (ByteIterator, Int) ⇒ Int = (bs, length) ⇒ { + private final val littleEndianDecoder: (ByteIterator, Int) => Int = (bs, length) => { val highestOctet = (length - 1) << 3 val Mask = ((1L << (length << 3)) - 1).toInt var count = length @@ -238,8 +238,8 @@ object Framing { // Retrive previous position val previous = indices.lastOption match { - case OptionVal.Some((_, i)) ⇒ i + separatorBytes.size - case OptionVal.None ⇒ 0 + case OptionVal.Some((_, i)) => i + separatorBytes.size + case OptionVal.None => 0 } if (possibleMatchPos - previous > maximumLineBytes) { @@ -286,7 +286,7 @@ object Framing { if (isClosed(in) && buffer.isEmpty) completeStage() } else { // Emit results and compact buffer - emitMultiple(out, new FrameIterator(), () ⇒ { + emitMultiple(out, new FrameIterator(), () => { reset() if (isClosed(in) && buffer.isEmpty) completeStage() }) @@ -294,8 +294,8 @@ object Framing { private def reset(): Unit = { val previous = indices.lastOption match { - case OptionVal.Some((_, i)) ⇒ i + separatorBytes.size - case OptionVal.None ⇒ 0 + case OptionVal.Some((_, i)) => i + separatorBytes.size + case OptionVal.None => 0 } buffer = buffer.drop(previous).compact @@ -347,7 +347,7 @@ object Framing { val lengthFieldOffset: Int, val maximumFrameLength: Int, val byteOrder: ByteOrder, - computeFrameSize: Option[(Array[Byte], Int) ⇒ Int]) extends GraphStage[FlowShape[ByteString, ByteString]] { + computeFrameSize: Option[(Array[Byte], Int) => Int]) extends GraphStage[FlowShape[ByteString, ByteString]] { //for the sake of binary compatibility def this( @@ -360,8 +360,8 @@ object Framing { private val minimumChunkSize = lengthFieldOffset + lengthFieldLength private val intDecoder = byteOrder match { - case ByteOrder.BIG_ENDIAN ⇒ bigEndianDecoder - case ByteOrder.LITTLE_ENDIAN ⇒ littleEndianDecoder + case ByteOrder.BIG_ENDIAN => bigEndianDecoder + case ByteOrder.LITTLE_ENDIAN => littleEndianDecoder } val in = Inlet[ByteString]("LengthFieldFramingStage.in") @@ -397,8 +397,8 @@ object Framing { } else if (buffSize >= minimumChunkSize) { val parsedLength = intDecoder(buffer.iterator.drop(lengthFieldOffset), lengthFieldLength) frameSize = computeFrameSize match { - case Some(f) ⇒ f(buffer.take(lengthFieldOffset).toArray, parsedLength) - case None ⇒ parsedLength + minimumChunkSize + case Some(f) => f(buffer.take(lengthFieldOffset).toArray, parsedLength) + case None => parsedLength + minimumChunkSize } if (frameSize > maximumFrameLength) { failStage(new FramingException(s"Maximum allowed frame size is $maximumFrameLength but decoded frame header reported size $frameSize")) diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Graph.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Graph.scala index 106347777c..416569356c 100755 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Graph.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Graph.scala @@ -28,7 +28,7 @@ import scala.util.control.{ NoStackTrace, NonFatal } * The implementation of a graph with an arbitrary shape. */ private[stream] final class GenericGraph[S <: Shape, Mat](override val shape: S, override val traversalBuilder: TraversalBuilder) - extends Graph[S, Mat] { outer ⇒ + extends Graph[S, Mat] { outer => override def toString: String = s"GenericGraph($shape)" @@ -43,7 +43,7 @@ private[stream] final class GenericGraph[S <: Shape, Mat](override val shape: S, * prevents building up a chain of changes. */ private[stream] final class GenericGraphWithChangedAttributes[S <: Shape, Mat](override val shape: S, originalTraversalBuilder: TraversalBuilder, newAttributes: Attributes) - extends Graph[S, Mat] { outer ⇒ + extends Graph[S, Mat] { outer => private[stream] def traversalBuilder: TraversalBuilder = originalTraversalBuilder.setAttributes(newAttributes) @@ -80,7 +80,7 @@ final class Merge[T](val inputPorts: Int, val eagerComplete: Boolean) extends Gr // one input might seem counter intuitive but saves us from special handling in other places require(inputPorts >= 1, "A Merge must have one or more input ports") - val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i ⇒ Inlet[T]("Merge.in" + i)) + val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i => Inlet[T]("Merge.in" + i)) val out: Outlet[T] = Outlet[T]("Merge.out") override def initialAttributes = DefaultAttributes.merge override val shape: UniformFanInShape[T, T] = UniformFanInShape(out, in: _*) @@ -219,9 +219,9 @@ final class MergePreferred[T](val secondaryPorts: Int, val eagerComplete: Boolea setHandler(out, eagerTerminateOutput) - val pullMe = Array.tabulate(secondaryPorts)(i ⇒ { + val pullMe = Array.tabulate(secondaryPorts)(i => { val port = in(i) - () ⇒ tryPull(port) + () => tryPull(port) }) /* @@ -245,7 +245,7 @@ final class MergePreferred[T](val secondaryPorts: Int, val eagerComplete: Boolea tryPull(preferred) } - val emitted = () ⇒ { + val emitted = () => { preferredEmitting -= 1 if (isAvailable(preferred)) emitPreferred() else if (preferredEmitting == 0) emitSecondary() @@ -310,20 +310,20 @@ final class MergePrioritized[T] private (val priorities: Seq[Int], val eagerComp require(inputPorts > 0, "A Merge must have one or more input ports") require(priorities.forall(_ > 0), "Priorities should be positive integers") - val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i ⇒ Inlet[T]("MergePrioritized.in" + i)) + val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i => Inlet[T]("MergePrioritized.in" + i)) val out: Outlet[T] = Outlet[T]("MergePrioritized.out") override def initialAttributes: Attributes = DefaultAttributes.mergePrioritized override val shape: UniformFanInShape[T, T] = UniformFanInShape(out, in: _*) override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler { - private val allBuffers = Vector.tabulate(priorities.size)(i ⇒ FixedSizeBuffer[Inlet[T]](priorities(i))) + private val allBuffers = Vector.tabulate(priorities.size)(i => FixedSizeBuffer[Inlet[T]](priorities(i))) private var runningUpstreams = inputPorts private val randomGen = new SplittableRandom override def preStart(): Unit = in.foreach(tryPull) (in zip allBuffers).foreach { - case (inlet, buffer) ⇒ + case (inlet, buffer) => setHandler(inlet, new InHandler { override def onPush(): Unit = { if (isAvailable(out) && !hasPending) { @@ -423,7 +423,7 @@ final class Interleave[T](val inputPorts: Int, val segmentSize: Int, val eagerCl require(inputPorts > 1, "input ports must be > 1") require(segmentSize > 0, "segmentSize must be > 0") - val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i ⇒ Inlet[T]("Interleave.in" + i)) + val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i => Inlet[T]("Interleave.in" + i)) val out: Outlet[T] = Outlet[T]("Interleave.out") override val shape: UniformFanInShape[T, T] = UniformFanInShape(out, in: _*) @@ -438,8 +438,8 @@ final class Interleave[T](val inputPorts: Int, val segmentSize: Int, val eagerCl @tailrec def nextInletIndex(index: Int): Int = { val successor = index + 1 match { - case `inputPorts` ⇒ 0 - case x ⇒ x + case `inputPorts` => 0 + case x => x } if (!isClosed(in(successor))) successor else { @@ -454,7 +454,7 @@ final class Interleave[T](val inputPorts: Int, val segmentSize: Int, val eagerCl currentUpstreamIndex = nextInletIndex(currentUpstreamIndex) } - in.foreach { i ⇒ + in.foreach { i => setHandler(i, new InHandler { override def onPush(): Unit = { push(out, grab(i)) @@ -518,18 +518,18 @@ final class MergeSorted[T: Ordering] extends GraphStage[FanInShape2[T, T, T]] { val dispatchR = dispatch(other, _: T) val dispatchL = dispatch(_: T, other) - val passR = () ⇒ emit(out, other, () ⇒ { nullOut(); passAlong(right, out, doPull = true) }) - val passL = () ⇒ emit(out, other, () ⇒ { nullOut(); passAlong(left, out, doPull = true) }) - val readR = () ⇒ read(right)(dispatchR, passL) - val readL = () ⇒ read(left)(dispatchL, passR) + val passR = () => emit(out, other, () => { nullOut(); passAlong(right, out, doPull = true) }) + val passL = () => emit(out, other, () => { nullOut(); passAlong(left, out, doPull = true) }) + val readR = () => read(right)(dispatchR, passL) + val readL = () => read(left)(dispatchL, passR) override def preStart(): Unit = { // all fan-in stages need to eagerly pull all inputs to get cycles started pull(right) - read(left)(l ⇒ { + read(left)(l => { other = l readR() - }, () ⇒ passAlong(right, out)) + }, () => passAlong(right, out)) } } } @@ -563,7 +563,7 @@ final class Broadcast[T](val outputPorts: Int, val eagerCancel: Boolean) extends // one output might seem counter intuitive but saves us from special handling in other places require(outputPorts >= 1, "A Broadcast must have one or more output ports") val in: Inlet[T] = Inlet[T]("Broadcast.in") - val out: immutable.IndexedSeq[Outlet[T]] = Vector.tabulate(outputPorts)(i ⇒ Outlet[T]("Broadcast.out" + i)) + val out: immutable.IndexedSeq[Outlet[T]] = Vector.tabulate(outputPorts)(i => Outlet[T]("Broadcast.out" + i)) override def initialAttributes = DefaultAttributes.broadcast override val shape: UniformFanOutShape[T, T] = UniformFanOutShape(in, out: _*) @@ -690,10 +690,10 @@ private[stream] final class WireTap[T] extends GraphStage[FanOutShape2[T, T, T]] setHandler(outTap, new OutHandler { override def onPull() = { pendingTap match { - case Some(elem) ⇒ + case Some(elem) => push(outTap, elem) pendingTap = None - case None ⇒ // no pending element to emit + case None => // no pending element to emit } } @@ -724,7 +724,7 @@ object Partition { * @param outputPorts number of output ports * @param partitioner function deciding which output each element will be targeted */ // FIXME BC add `eagerCancel: Boolean = false` parameter - def apply[T](outputPorts: Int, partitioner: T ⇒ Int): Partition[T] = new Partition(outputPorts, partitioner, false) + def apply[T](outputPorts: Int, partitioner: T => Int): Partition[T] = new Partition(outputPorts, partitioner, false) } /** @@ -740,16 +740,16 @@ object Partition { * '''Cancels when''' all downstreams have cancelled (eagerCancel=false) or one downstream cancels (eagerCancel=true) */ -final class Partition[T](val outputPorts: Int, val partitioner: T ⇒ Int, val eagerCancel: Boolean) extends GraphStage[UniformFanOutShape[T, T]] { +final class Partition[T](val outputPorts: Int, val partitioner: T => Int, val eagerCancel: Boolean) extends GraphStage[UniformFanOutShape[T, T]] { /** * Sets `eagerCancel` to `false`. */ @deprecated("Use the constructor which also specifies the `eagerCancel` parameter") - def this(outputPorts: Int, partitioner: T ⇒ Int) = this(outputPorts, partitioner, false) + def this(outputPorts: Int, partitioner: T => Int) = this(outputPorts, partitioner, false) val in: Inlet[T] = Inlet[T]("Partition.in") - val out: Seq[Outlet[T]] = Seq.tabulate(outputPorts)(i ⇒ Outlet[T]("Partition.out" + i)) // FIXME BC make this immutable.IndexedSeq as type + Vector as concrete impl + val out: Seq[Outlet[T]] = Seq.tabulate(outputPorts)(i => Outlet[T]("Partition.out" + i)) // FIXME BC make this immutable.IndexedSeq as type + Vector as concrete impl override val shape: UniformFanOutShape[T, T] = UniformFanOutShape[T, T](in, out: _*) override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler { @@ -783,7 +783,7 @@ final class Partition[T](val outputPorts: Int, val partitioner: T ⇒ Int, val e setHandler(in, this) out.iterator.zipWithIndex.foreach { - case (o, idx) ⇒ + case (o, idx) => setHandler(o, new OutHandler { override def onPull() = { if (outPendingElem != null) { @@ -863,7 +863,7 @@ final class Balance[T](val outputPorts: Int, val waitForAllDownstreams: Boolean, def this(outputPorts: Int, waitForAllDownstreams: Boolean) = this(outputPorts, waitForAllDownstreams, false) val in: Inlet[T] = Inlet[T]("Balance.in") - val out: immutable.IndexedSeq[Outlet[T]] = Vector.tabulate(outputPorts)(i ⇒ Outlet[T]("Balance.out" + i)) + val out: immutable.IndexedSeq[Outlet[T]] = Vector.tabulate(outputPorts)(i => Outlet[T]("Balance.out" + i)) override def initialAttributes = DefaultAttributes.balance override val shape: UniformFanOutShape[T, T] = UniformFanOutShape[T, T](in, out: _*) @@ -893,7 +893,7 @@ final class Balance[T](val outputPorts: Int, val waitForAllDownstreams: Boolean, def onPush(): Unit = dequeueAndDispatch() setHandler(in, this) - out.foreach { o ⇒ + out.foreach { o => setHandler(o, new OutHandler { private var hasPulled = false @@ -1095,7 +1095,7 @@ object ZipWithN { /** * Create a new `ZipWithN`. */ - def apply[A, O](zipper: immutable.Seq[A] ⇒ O)(n: Int) = new ZipWithN[A, O](zipper)(n) + def apply[A, O](zipper: immutable.Seq[A] => O)(n: Int) = new ZipWithN[A, O](zipper)(n) } /** @@ -1111,7 +1111,7 @@ object ZipWithN { * * '''Cancels when''' downstream cancels */ -class ZipWithN[A, O](zipper: immutable.Seq[A] ⇒ O)(n: Int) extends GraphStage[UniformFanInShape[A, O]] { +class ZipWithN[A, O](zipper: immutable.Seq[A] => O)(n: Int) extends GraphStage[UniformFanInShape[A, O]] { override def initialAttributes = DefaultAttributes.zipWithN override val shape = new UniformFanInShape[A, O](n) def out: Outlet[O] = shape.out @@ -1137,7 +1137,7 @@ class ZipWithN[A, O](zipper: immutable.Seq[A] ⇒ O)(n: Int) extends GraphStage[ shape.inlets.foreach(pullInlet) } - shape.inlets.foreach(in ⇒ { + shape.inlets.foreach(in => { setHandler(in, new InHandler { override def onPush(): Unit = { pending -= 1 @@ -1188,7 +1188,7 @@ object Concat { */ final class Concat[T](val inputPorts: Int) extends GraphStage[UniformFanInShape[T, T]] { require(inputPorts > 1, "A Concat must have more than 1 input ports") - val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i ⇒ Inlet[T]("Concat.in" + i)) + val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i => Inlet[T]("Concat.in" + i)) val out: Outlet[T] = Outlet[T]("Concat.out") override def initialAttributes = DefaultAttributes.concat override val shape: UniformFanInShape[T, T] = UniformFanInShape(out, in: _*) @@ -1318,13 +1318,13 @@ object GraphDSL extends GraphApply { * Creates a new [[Graph]] by importing the given graph list `graphs` and passing their [[Shape]]s * along with the [[GraphDSL.Builder]] to the given create function. */ - def create[S <: Shape, IS <: Shape, Mat](graphs: immutable.Seq[Graph[IS, Mat]])(buildBlock: GraphDSL.Builder[immutable.Seq[Mat]] ⇒ immutable.Seq[IS] ⇒ S): Graph[S, immutable.Seq[Mat]] = { + def create[S <: Shape, IS <: Shape, Mat](graphs: immutable.Seq[Graph[IS, Mat]])(buildBlock: GraphDSL.Builder[immutable.Seq[Mat]] => immutable.Seq[IS] => S): Graph[S, immutable.Seq[Mat]] = { require(graphs.nonEmpty, "The input list must have one or more Graph elements") val builder = new GraphDSL.Builder - val toList = (m1: Mat) ⇒ Seq(m1) - val combine = (s: Seq[Mat], m2: Mat) ⇒ s :+ m2 + val toList = (m1: Mat) => Seq(m1) + val combine = (s: Seq[Mat], m2: Mat) => s :+ m2 val sListH = builder.add(graphs.head, toList) - val sListT = graphs.tail.map(g ⇒ builder.add(g, combine)) + val sListT = graphs.tail.map(g => builder.add(g, combine)) val s = buildBlock(builder)(immutable.Seq(sListH) ++ sListT) new GenericGraph(s, builder.result(s)) @@ -1345,7 +1345,7 @@ object GraphDSL extends GraphApply { unwiredIns -= to unwiredOuts -= from } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => if (!traversalBuilderInProgress.isUnwired(from)) throw new IllegalArgumentException(s"[${from.s}] is already connected") else if (!traversalBuilderInProgress.isUnwired(to)) @@ -1374,7 +1374,7 @@ object GraphDSL extends GraphApply { * This is only used by the materialization-importing apply methods of Source, * Flow, Sink and Graph. */ - private[stream] def add[S <: Shape, A](graph: Graph[S, _], transform: (A) ⇒ Any): S = { + private[stream] def add[S <: Shape, A](graph: Graph[S, _], transform: (A) => Any): S = { val newShape = graph.shape.deepCopy() traversalBuilderInProgress = traversalBuilderInProgress.add( graph.traversalBuilder.transformMat(transform), @@ -1393,7 +1393,7 @@ object GraphDSL extends GraphApply { * This is only used by the materialization-importing apply methods of Source, * Flow, Sink and Graph. */ - private[stream] def add[S <: Shape, A, B](graph: Graph[S, _], combine: (A, B) ⇒ Any): S = { + private[stream] def add[S <: Shape, A, B](graph: Graph[S, _], combine: (A, B) => Any): S = { val newShape = graph.shape.deepCopy() traversalBuilderInProgress = traversalBuilderInProgress.add(graph.traversalBuilder, newShape, combine) @@ -1418,12 +1418,12 @@ object GraphDSL extends GraphApply { * @return The outlet that will emit the materialized value. */ def materializedValue: Outlet[M @uncheckedVariance] = - add(Source.maybe[M], { (prev: M, prom: Promise[Option[M]]) ⇒ prom.success(Some(prev)); prev }).out + add(Source.maybe[M], { (prev: M, prom: Promise[Option[M]]) => prom.success(Some(prev)); prev }).out private[GraphDSL] def traversalBuilder: TraversalBuilder = traversalBuilderInProgress private[stream] def result(resultShape: Shape): TraversalBuilder = { - def errorString[T](expectedSet: Set[T], actualSet: Set[T], tag: String)(format: T ⇒ String): String = + def errorString[T](expectedSet: Set[T], actualSet: Set[T], tag: String)(format: T => String): String = if (expectedSet != actualSet) { val diff1 = expectedSet.diff(actualSet) val diff2 = actualSet.diff(expectedSet) @@ -1497,7 +1497,7 @@ object GraphDSL extends GraphApply { b.addEdge(importAndGetPort(b), junction.in) try findOut(b, junction, 0) catch { - case e: IllegalArgumentException ⇒ new DisabledPortOps(e.getMessage) + case e: IllegalArgumentException => new DisabledPortOps(e.getMessage) } } @@ -1540,7 +1540,7 @@ object GraphDSL extends GraphApply { b.addEdge(junction.out, importAndGetPortReverse(b)) try findIn(b, junction, 0) catch { - case e: IllegalArgumentException ⇒ new DisabledReversePortOps(e.getMessage) + case e: IllegalArgumentException => new DisabledReversePortOps(e.getMessage) } } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Hub.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Hub.scala index 6ed897b97d..4b99d5b33e 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Hub.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Hub.scala @@ -116,7 +116,7 @@ private[akka] class MergeHub[T](perProducerBufferSize: Int) extends GraphStageWi @volatile private[this] var shuttingDown = false private[this] val demands = scala.collection.mutable.LongMap.empty[InputState] - private[this] val wakeupCallback = getAsyncCallback[NotUsed]((_) ⇒ + private[this] val wakeupCallback = getAsyncCallback[NotUsed]((_) => // We are only allowed to dequeue if we are not backpressured. See comment in tryProcessNext() for details. if (isAvailable(out)) tryProcessNext(firstAttempt = true)) @@ -124,14 +124,14 @@ private[akka] class MergeHub[T](perProducerBufferSize: Int) extends GraphStageWi // Returns true when we have not consumed demand, false otherwise private def onEvent(ev: Event): Boolean = ev match { - case Element(id, elem) ⇒ + case Element(id, elem) => demands(id).onElement() push(out, elem) false - case Register(id, callback) ⇒ + case Register(id, callback) => demands.put(id, new InputState(callback)) true - case Deregister(id) ⇒ + case Deregister(id) => demands.remove(id) true } @@ -205,8 +205,8 @@ private[akka] class MergeHub[T](perProducerBufferSize: Int) extends GraphStageWi var event = queue.poll() while (event ne null) { event match { - case Register(_, demandCallback) ⇒ demandCallback.invoke(MergeHub.Cancel) - case _ ⇒ + case Register(_, demandCallback) => demandCallback.invoke(MergeHub.Cancel) + case _ => } event = queue.poll() } @@ -286,8 +286,8 @@ private[akka] class MergeHub[T](perProducerBufferSize: Int) extends GraphStageWi // propagate LogLevels attribute so that MergeHub can be used with onFailure = LogLevels.Off val sinkWithAttributes = inheritedAttributes.get[LogLevels] match { - case Some(a) ⇒ Sink.fromGraph(sink).addAttributes(Attributes(a)) - case None ⇒ Sink.fromGraph(sink) + case Some(a) => Sink.fromGraph(sink).addAttributes(Attributes(a)) + case None => Sink.fromGraph(sink) } (logic, sinkWithAttributes) @@ -424,23 +424,23 @@ private[akka] class BroadcastHub[T](bufferSize: Int) extends GraphStageWithMater private def onEvent(ev: HubEvent): Unit = { ev match { - case RegistrationPending ⇒ - state.getAndSet(noRegistrationsState).asInstanceOf[Open].registrations foreach { consumer ⇒ + case RegistrationPending => + state.getAndSet(noRegistrationsState).asInstanceOf[Open].registrations foreach { consumer => val startFrom = head activeConsumers += 1 addConsumer(consumer, startFrom) // in case the consumer is already stopped we need to undo registration implicit val ec = materializer.executionContext consumer.callback.invokeWithFeedback(Initialize(startFrom)).failed.foreach { - case _: StreamDetachedException ⇒ - callbackPromise.future.foreach(callback ⇒ + case _: StreamDetachedException => + callbackPromise.future.foreach(callback => callback.invoke(UnRegister(consumer.id, startFrom, startFrom)) ) - case _ ⇒ () + case _ => () } } - case UnRegister(id, previousOffset, finalOffset) ⇒ + case UnRegister(id, previousOffset, finalOffset) => if (findAndRemoveConsumer(id, previousOffset) != null) activeConsumers -= 1 if (activeConsumers == 0) { @@ -457,13 +457,13 @@ private[akka] class BroadcastHub[T](bufferSize: Int) extends GraphStageWithMater } } else checkUnblock(previousOffset) - case Advance(id, previousOffset) ⇒ + case Advance(id, previousOffset) => val newOffset = previousOffset + DemandThreshold // Move the consumer from its last known offset to its new one. Check if we are unblocked. val consumer = findAndRemoveConsumer(id, previousOffset) addConsumer(consumer, newOffset) checkUnblock(previousOffset) - case NeedWakeup(id, previousOffset, currentOffset) ⇒ + case NeedWakeup(id, previousOffset, currentOffset) => // Move the consumer from its last known offset to its new one. Check if we are unblocked. val consumer = findAndRemoveConsumer(id, previousOffset) addConsumer(consumer, currentOffset) @@ -483,12 +483,12 @@ private[akka] class BroadcastHub[T](bufferSize: Int) extends GraphStageWithMater val failMessage = HubCompleted(Some(ex)) // Notify pending consumers and set tombstone - state.getAndSet(Closed(Some(ex))).asInstanceOf[Open].registrations foreach { consumer ⇒ + state.getAndSet(Closed(Some(ex))).asInstanceOf[Open].registrations foreach { consumer => consumer.callback.invoke(failMessage) } // Notify registered consumers - consumerWheel.iterator.flatMap(_.iterator) foreach { consumer ⇒ + consumerWheel.iterator.flatMap(_.iterator) foreach { consumer => consumer.callback.invoke(failMessage) } failStage(ex) @@ -573,11 +573,11 @@ private[akka] class BroadcastHub[T](bufferSize: Int) extends GraphStageWithMater // Notify pending consumers and set tombstone @tailrec def tryClose(): Unit = state.get() match { - case Closed(_) ⇒ // Already closed, ignore - case open: Open ⇒ + case Closed(_) => // Already closed, ignore + case open: Open => if (state.compareAndSet(open, Closed(None))) { val completedMessage = HubCompleted(None) - open.registrations foreach { consumer ⇒ + open.registrations foreach { consumer => consumer.callback.invoke(completedMessage) } } else tryClose() @@ -637,20 +637,20 @@ private[akka] class BroadcastHub[T](bufferSize: Int) extends GraphStageWithMater override def preStart(): Unit = { val callback = getAsyncCallback(onCommand) - val onHubReady: Try[AsyncCallback[HubEvent]] ⇒ Unit = { - case Success(callback) ⇒ + val onHubReady: Try[AsyncCallback[HubEvent]] => Unit = { + case Success(callback) => hubCallback = callback if (isAvailable(out) && offsetInitialized) onPull() callback.invoke(RegistrationPending) - case Failure(ex) ⇒ + case Failure(ex) => failStage(ex) } @tailrec def register(): Unit = { logic.state.get() match { - case Closed(Some(ex)) ⇒ failStage(ex) - case Closed(None) ⇒ completeStage() - case previousState @ Open(callbackFuture, registrations) ⇒ + case Closed(Some(ex)) => failStage(ex) + case Closed(None) => completeStage() + case previousState @ Open(callbackFuture, registrations) => val newRegistrations = Consumer(id, callback) :: registrations if (logic.state.compareAndSet(previousState, Open(callbackFuture, newRegistrations))) { callbackFuture.onComplete(getAsyncCallback(onHubReady).invoke)(materializer.executionContext) @@ -674,13 +674,13 @@ private[akka] class BroadcastHub[T](bufferSize: Int) extends GraphStageWithMater val elem = logic.poll(offset) elem match { - case null ⇒ + case null => hubCallback.invoke(NeedWakeup(id, previousPublishedOffset, offset)) previousPublishedOffset = offset untilNextAdvanceSignal = DemandThreshold - case Completed ⇒ + case Completed => completeStage() - case _ ⇒ + case _ => push(out, elem.asInstanceOf[T]) offset += 1 untilNextAdvanceSignal -= 1 @@ -700,11 +700,11 @@ private[akka] class BroadcastHub[T](bufferSize: Int) extends GraphStageWithMater } private def onCommand(cmd: ConsumerEvent): Unit = cmd match { - case HubCompleted(Some(ex)) ⇒ failStage(ex) - case HubCompleted(None) ⇒ completeStage() - case Wakeup ⇒ + case HubCompleted(Some(ex)) => failStage(ex) + case HubCompleted(None) => completeStage() + case Wakeup => if (isAvailable(out)) onPull() - case Initialize(initialOffset) ⇒ + case Initialize(initialOffset) => offsetInitialized = true previousPublishedOffset = initialOffset offset = initialOffset @@ -765,7 +765,7 @@ object PartitionHub { * @param bufferSize Total number of elements that can be buffered. If this buffer is full, the producer * is backpressured. */ - @ApiMayChange def statefulSink[T](partitioner: () ⇒ (ConsumerInfo, T) ⇒ Long, startAfterNrOfConsumers: Int, + @ApiMayChange def statefulSink[T](partitioner: () => (ConsumerInfo, T) => Long, startAfterNrOfConsumers: Int, bufferSize: Int = defaultBufferSize): Sink[T, Source[T, NotUsed]] = Sink.fromGraph(new PartitionHub[T](partitioner, startAfterNrOfConsumers, bufferSize)) @@ -799,14 +799,14 @@ object PartitionHub { * is backpressured. */ @ApiMayChange - def sink[T](partitioner: (Int, T) ⇒ Int, startAfterNrOfConsumers: Int, + def sink[T](partitioner: (Int, T) => Int, startAfterNrOfConsumers: Int, bufferSize: Int = defaultBufferSize): Sink[T, Source[T, NotUsed]] = { - val fun: (ConsumerInfo, T) ⇒ Long = { (info, elem) ⇒ + val fun: (ConsumerInfo, T) => Long = { (info, elem) => val idx = partitioner(info.size, elem) if (idx < 0) -1L else info.consumerIdByIdx(idx) } - statefulSink(() ⇒ fun, startAfterNrOfConsumers, bufferSize) + statefulSink(() => fun, startAfterNrOfConsumers, bufferSize) } @DoNotInherit @ApiMayChange trait ConsumerInfo extends akka.stream.javadsl.PartitionHub.ConsumerInfo { @@ -983,8 +983,8 @@ object PartitionHub { override def remove(id: Long): Unit = { (if (id < FixedQueues) queues1.getAndSet(id.toInt, null) else queues2.remove(id)) match { - case null ⇒ - case queue ⇒ _totalSize.addAndGet(-queue.size) + case null => + case queue => _totalSize.addAndGet(-queue.size) } } @@ -996,7 +996,7 @@ object PartitionHub { * INTERNAL API */ @InternalApi private[akka] class PartitionHub[T]( - partitioner: () ⇒ (PartitionHub.ConsumerInfo, T) ⇒ Long, + partitioner: () => (PartitionHub.ConsumerInfo, T) => Long, startAfterNrOfConsumers: Int, bufferSize: Int) extends GraphStageWithMaterializedValue[SinkShape[T], Source[T, NotUsed]] { import PartitionHub.Internal._ @@ -1030,7 +1030,7 @@ object PartitionHub { private var callbackCount = 0L private final class ConsumerInfoImpl(val consumers: Vector[Consumer]) - extends ConsumerInfo { info ⇒ + extends ConsumerInfo { info => override def queueSize(consumerId: Long): Int = queue.size(consumerId) @@ -1081,8 +1081,8 @@ object PartitionHub { private def wakeup(id: Long): Unit = { needWakeup.get(id) match { - case None ⇒ // ignore - case Some(consumer) ⇒ + case None => // ignore + case Some(consumer) => needWakeup -= id consumer.callback.invoke(Wakeup) } @@ -1092,7 +1092,7 @@ object PartitionHub { if (consumerInfo.consumers.isEmpty) completeStage() else { - consumerInfo.consumers.foreach(c ⇒ complete(c.id)) + consumerInfo.consumers.foreach(c => complete(c.id)) } } @@ -1109,7 +1109,7 @@ object PartitionHub { private def onEvent(ev: HubEvent): Unit = { callbackCount += 1 ev match { - case NeedWakeup(consumer) ⇒ + case NeedWakeup(consumer) => // Also check if the consumer is now unblocked since we published an element since it went asleep. if (queue.nonEmpty(consumer.id)) consumer.callback.invoke(Wakeup) @@ -1118,11 +1118,11 @@ object PartitionHub { tryPull() } - case TryPull ⇒ + case TryPull => tryPull() - case RegistrationPending ⇒ - state.getAndSet(noRegistrationsState).asInstanceOf[Open].registrations foreach { consumer ⇒ + case RegistrationPending => + state.getAndSet(noRegistrationsState).asInstanceOf[Open].registrations foreach { consumer => val newConsumers = (consumerInfo.consumers :+ consumer).sortBy(_.id) consumerInfo = new ConsumerInfoImpl(newConsumers) queue.init(consumer.id) @@ -1140,7 +1140,7 @@ object PartitionHub { tryPull() } - case UnRegister(id) ⇒ + case UnRegister(id) => val newConsumers = consumerInfo.consumers.filterNot(_.id == id) consumerInfo = new ConsumerInfoImpl(newConsumers) queue.remove(id) @@ -1155,12 +1155,12 @@ object PartitionHub { val failMessage = HubCompleted(Some(ex)) // Notify pending consumers and set tombstone - state.getAndSet(Closed(Some(ex))).asInstanceOf[Open].registrations foreach { consumer ⇒ + state.getAndSet(Closed(Some(ex))).asInstanceOf[Open].registrations foreach { consumer => consumer.callback.invoke(failMessage) } // Notify registered consumers - consumerInfo.consumers.foreach { consumer ⇒ + consumerInfo.consumers.foreach { consumer => consumer.callback.invoke(failMessage) } failStage(ex) @@ -1170,11 +1170,11 @@ object PartitionHub { // Notify pending consumers and set tombstone @tailrec def tryClose(): Unit = state.get() match { - case Closed(_) ⇒ // Already closed, ignore - case open: Open ⇒ + case Closed(_) => // Already closed, ignore + case open: Open => if (state.compareAndSet(open, Closed(None))) { val completedMessage = HubCompleted(None) - open.registrations foreach { consumer ⇒ + open.registrations foreach { consumer => consumer.callback.invoke(completedMessage) } } else tryClose() @@ -1214,20 +1214,20 @@ object PartitionHub { private var callbackCount = 0L override def preStart(): Unit = { - val onHubReady: Try[AsyncCallback[HubEvent]] ⇒ Unit = { - case Success(callback) ⇒ + val onHubReady: Try[AsyncCallback[HubEvent]] => Unit = { + case Success(callback) => hubCallback = callback callback.invoke(RegistrationPending) if (isAvailable(out)) onPull() - case Failure(ex) ⇒ + case Failure(ex) => failStage(ex) } @tailrec def register(): Unit = { logic.state.get() match { - case Closed(Some(ex)) ⇒ failStage(ex) - case Closed(None) ⇒ completeStage() - case previousState @ Open(callbackFuture, registrations) ⇒ + case Closed(Some(ex)) => failStage(ex) + case Closed(None) => completeStage() + case previousState @ Open(callbackFuture, registrations) => val newRegistrations = consumer :: registrations if (logic.state.compareAndSet(previousState, Open(callbackFuture, newRegistrations))) { callbackFuture.onComplete(getAsyncCallback(onHubReady).invoke)(materializer.executionContext) @@ -1244,11 +1244,11 @@ object PartitionHub { val elem = logic.poll(id, hubCallback) elem match { - case null ⇒ + case null => hubCallback.invoke(NeedWakeup(consumer)) - case Completed ⇒ + case Completed => completeStage() - case _ ⇒ + case _ => push(out, elem.asInstanceOf[T]) } } @@ -1262,11 +1262,11 @@ object PartitionHub { private def onCommand(cmd: ConsumerEvent): Unit = { callbackCount += 1 cmd match { - case HubCompleted(Some(ex)) ⇒ failStage(ex) - case HubCompleted(None) ⇒ completeStage() - case Wakeup ⇒ + case HubCompleted(Some(ex)) => failStage(ex) + case HubCompleted(None) => completeStage() + case Wakeup => if (isAvailable(out)) onPull() - case Initialize ⇒ + case Initialize => if (isAvailable(out) && (hubCallback ne null)) onPull() } } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/JsonFraming.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/JsonFraming.scala index 0f48621a3e..2befc0084f 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/JsonFraming.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/JsonFraming.scala @@ -60,17 +60,17 @@ object JsonFraming { override def onUpstreamFinish(): Unit = { buffer.poll() match { - case Some(json) ⇒ emit(out, json) - case _ ⇒ completeStage() + case Some(json) => emit(out, json) + case _ => completeStage() } } def tryPopBuffer() = { try buffer.poll() match { - case Some(json) ⇒ push(out, json) - case _ ⇒ if (isClosed(in)) completeStage() else pull(in) + case Some(json) => push(out, json) + case _ => if (isClosed(in)) completeStage() else pull(in) } catch { - case NonFatal(ex) ⇒ failStage(ex) + case NonFatal(ex) => failStage(ex) } } } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Materialization.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Materialization.scala index 3c848c620a..ed72ae004d 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Materialization.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Materialization.scala @@ -11,13 +11,13 @@ import akka.NotUsed * left (first) or only the right (second) of two input values. */ object Keep { - private val _left = (l: Any, r: Any) ⇒ l - private val _right = (l: Any, r: Any) ⇒ r - private val _both = (l: Any, r: Any) ⇒ (l, r) - private val _none = (l: Any, r: Any) ⇒ NotUsed + private val _left = (l: Any, r: Any) => l + private val _right = (l: Any, r: Any) => r + private val _both = (l: Any, r: Any) => (l, r) + private val _none = (l: Any, r: Any) => NotUsed - def left[L, R]: (L, R) ⇒ L = _left.asInstanceOf[(L, R) ⇒ L] - def right[L, R]: (L, R) ⇒ R = _right.asInstanceOf[(L, R) ⇒ R] - def both[L, R]: (L, R) ⇒ (L, R) = _both.asInstanceOf[(L, R) ⇒ (L, R)] - def none[L, R]: (L, R) ⇒ NotUsed = _none.asInstanceOf[(L, R) ⇒ NotUsed] + def left[L, R]: (L, R) => L = _left.asInstanceOf[(L, R) => L] + def right[L, R]: (L, R) => R = _right.asInstanceOf[(L, R) => R] + def both[L, R]: (L, R) => (L, R) = _both.asInstanceOf[(L, R) => (L, R)] + def none[L, R]: (L, R) => NotUsed = _none.asInstanceOf[(L, R) => NotUsed] } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/MergeLatest.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/MergeLatest.scala index de63723a35..27513ea565 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/MergeLatest.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/MergeLatest.scala @@ -34,10 +34,10 @@ object MergeLatest { } -final class MergeLatest[T, M](val inputPorts: Int, val eagerClose: Boolean)(buildElem: Array[T] ⇒ M) extends GraphStage[UniformFanInShape[T, M]] { +final class MergeLatest[T, M](val inputPorts: Int, val eagerClose: Boolean)(buildElem: Array[T] => M) extends GraphStage[UniformFanInShape[T, M]] { require(inputPorts >= 1, "input ports must be >= 1") - val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i ⇒ Inlet[T]("MergeLatest.in" + i)) + val in: immutable.IndexedSeq[Inlet[T]] = Vector.tabulate(inputPorts)(i => Inlet[T]("MergeLatest.in" + i)) val out: Outlet[M] = Outlet[M]("MergeLatest.out") override val shape: UniformFanInShape[T, M] = UniformFanInShape(out, in: _*) @@ -51,7 +51,7 @@ final class MergeLatest[T, M](val inputPorts: Int, val eagerClose: Boolean)(buil override def preStart(): Unit = in.foreach(tryPull) in.zipWithIndex.foreach { - case (input, index) ⇒ + case (input, index) => setHandler(input, new InHandler { override def onPush(): Unit = { messages.update(index, grab(input)) diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/RestartFlow.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/RestartFlow.scala index 64e468dda4..77c38ef3d1 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/RestartFlow.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/RestartFlow.scala @@ -48,7 +48,7 @@ object RestartFlow { * In order to skip this additional delay pass in `0`. * @param flowFactory A factory for producing the [[Flow]] to wrap. */ - def withBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double)(flowFactory: () ⇒ Flow[In, Out, _]): Flow[In, Out, NotUsed] = { + def withBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double)(flowFactory: () => Flow[In, Out, _]): Flow[In, Out, NotUsed] = { Flow.fromGraph(new RestartWithBackoffFlow(flowFactory, minBackoff, maxBackoff, randomFactor, onlyOnFailures = false, Int.MaxValue)) } @@ -77,7 +77,7 @@ object RestartFlow { * Passing `0` will cause no restarts and a negative number will not cap the amount of restarts. * @param flowFactory A factory for producing the [[Flow]] to wrap. */ - def withBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(flowFactory: () ⇒ Flow[In, Out, _]): Flow[In, Out, NotUsed] = { + def withBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(flowFactory: () => Flow[In, Out, _]): Flow[In, Out, NotUsed] = { Flow.fromGraph(new RestartWithBackoffFlow(flowFactory, minBackoff, maxBackoff, randomFactor, onlyOnFailures = false, maxRestarts)) } @@ -107,19 +107,19 @@ object RestartFlow { * Passing `0` will cause no restarts and a negative number will not cap the amount of restarts. * @param flowFactory A factory for producing the [[Flow]] to wrap. */ - def onFailuresWithBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(flowFactory: () ⇒ Flow[In, Out, _]): Flow[In, Out, NotUsed] = { + def onFailuresWithBackoff[In, Out](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(flowFactory: () => Flow[In, Out, _]): Flow[In, Out, NotUsed] = { Flow.fromGraph(new RestartWithBackoffFlow(flowFactory, minBackoff, maxBackoff, randomFactor, onlyOnFailures = true, maxRestarts)) } } private final class RestartWithBackoffFlow[In, Out]( - flowFactory: () ⇒ Flow[In, Out, _], + flowFactory: () => Flow[In, Out, _], minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, onlyOnFailures: Boolean, - maxRestarts: Int) extends GraphStage[FlowShape[In, Out]] { self ⇒ + maxRestarts: Int) extends GraphStage[FlowShape[In, Out]] { self => val in = Inlet[In]("RestartWithBackoffFlow.in") val out = Outlet[Out]("RestartWithBackoffFlow.out") @@ -161,7 +161,7 @@ private final class RestartWithBackoffFlow[In, Out]( // We need to ensure that the other end of the sub flow is also completed, so that we don't // receive any callbacks from it. activeOutIn.foreach { - case (sourceOut, sinkIn) ⇒ + case (sourceOut, sinkIn) => if (!sourceOut.isClosed) { sourceOut.complete() } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/RestartSink.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/RestartSink.scala index 2cd98f1dd7..8ddb7b6d12 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/RestartSink.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/RestartSink.scala @@ -43,7 +43,7 @@ object RestartSink { * In order to skip this additional delay pass in `0`. * @param sinkFactory A factory for producing the [[Sink]] to wrap. */ - def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double)(sinkFactory: () ⇒ Sink[T, _]): Sink[T, NotUsed] = { + def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double)(sinkFactory: () => Sink[T, _]): Sink[T, NotUsed] = { Sink.fromGraph(new RestartWithBackoffSink(sinkFactory, minBackoff, maxBackoff, randomFactor, Int.MaxValue)) } @@ -73,17 +73,17 @@ object RestartSink { * Passing `0` will cause no restarts and a negative number will not cap the amount of restarts. * @param sinkFactory A factory for producing the [[Sink]] to wrap. */ - def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(sinkFactory: () ⇒ Sink[T, _]): Sink[T, NotUsed] = { + def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(sinkFactory: () => Sink[T, _]): Sink[T, NotUsed] = { Sink.fromGraph(new RestartWithBackoffSink(sinkFactory, minBackoff, maxBackoff, randomFactor, maxRestarts)) } } private final class RestartWithBackoffSink[T]( - sinkFactory: () ⇒ Sink[T, _], + sinkFactory: () => Sink[T, _], minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, - maxRestarts: Int) extends GraphStage[SinkShape[T]] { self ⇒ + maxRestarts: Int) extends GraphStage[SinkShape[T]] { self => val in = Inlet[T]("RestartWithBackoffSink.in") diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/RestartSource.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/RestartSource.scala index 84da5ea164..0a68ca9f24 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/RestartSource.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/RestartSource.scala @@ -39,7 +39,7 @@ object RestartSource { * In order to skip this additional delay pass in `0`. * @param sourceFactory A factory for producing the [[Source]] to wrap. */ - def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double)(sourceFactory: () ⇒ Source[T, _]): Source[T, NotUsed] = { + def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double)(sourceFactory: () => Source[T, _]): Source[T, NotUsed] = { Source.fromGraph(new RestartWithBackoffSource(sourceFactory, minBackoff, maxBackoff, randomFactor, onlyOnFailures = false, Int.MaxValue)) } @@ -66,7 +66,7 @@ object RestartSource { * Passing `0` will cause no restarts and a negative number will not cap the amount of restarts. * @param sourceFactory A factory for producing the [[Source]] to wrap. */ - def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(sourceFactory: () ⇒ Source[T, _]): Source[T, NotUsed] = { + def withBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(sourceFactory: () => Source[T, _]): Source[T, NotUsed] = { Source.fromGraph(new RestartWithBackoffSource(sourceFactory, minBackoff, maxBackoff, randomFactor, onlyOnFailures = false, maxRestarts)) } @@ -90,7 +90,7 @@ object RestartSource { * @param sourceFactory A factory for producing the [[Source]] to wrap. * */ - def onFailuresWithBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double)(sourceFactory: () ⇒ Source[T, _]): Source[T, NotUsed] = { + def onFailuresWithBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double)(sourceFactory: () => Source[T, _]): Source[T, NotUsed] = { Source.fromGraph(new RestartWithBackoffSource(sourceFactory, minBackoff, maxBackoff, randomFactor, onlyOnFailures = true, Int.MaxValue)) } @@ -117,18 +117,18 @@ object RestartSource { * @param sourceFactory A factory for producing the [[Source]] to wrap. * */ - def onFailuresWithBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(sourceFactory: () ⇒ Source[T, _]): Source[T, NotUsed] = { + def onFailuresWithBackoff[T](minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, maxRestarts: Int)(sourceFactory: () => Source[T, _]): Source[T, NotUsed] = { Source.fromGraph(new RestartWithBackoffSource(sourceFactory, minBackoff, maxBackoff, randomFactor, onlyOnFailures = true, maxRestarts)) } } private final class RestartWithBackoffSource[T]( - sourceFactory: () ⇒ Source[T, _], + sourceFactory: () => Source[T, _], minBackoff: FiniteDuration, maxBackoff: FiniteDuration, randomFactor: Double, onlyOnFailures: Boolean, - maxRestarts: Int) extends GraphStage[SourceShape[T]] { self ⇒ + maxRestarts: Int) extends GraphStage[SourceShape[T]] { self => val out = Outlet[T]("RestartWithBackoffSource.out") diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Sink.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Sink.scala index 2a91306354..ecfff583c0 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Sink.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Sink.scala @@ -45,7 +45,7 @@ final class Sink[-In, +Mat]( * * '''Cancels when''' original [[Sink]] cancels */ - def contramap[In2](f: In2 ⇒ In): Sink[In2, Mat] = Flow.fromFunction(f).toMat(this)(Keep.right) + def contramap[In2](f: In2 => In): Sink[In2, Mat] = Flow.fromFunction(f).toMat(this)(Keep.right) /** * Connect this `Sink` to a `Source` and run it. The returned value is the materialized value @@ -57,9 +57,9 @@ final class Sink[-In, +Mat]( /** * Transform only the materialized value of this Sink, leaving all other properties as they were. */ - def mapMaterializedValue[Mat2](f: Mat ⇒ Mat2): Sink[In, Mat2] = + def mapMaterializedValue[Mat2](f: Mat => Mat2): Sink[In, Mat2] = new Sink( - traversalBuilder.transformMat(f.asInstanceOf[Any ⇒ Any]), + traversalBuilder.transformMat(f.asInstanceOf[Any => Any]), shape) /** @@ -136,9 +136,9 @@ object Sink { */ def fromGraph[T, M](g: Graph[SinkShape[T], M]): Sink[T, M] = g match { - case s: Sink[T, M] ⇒ s - case s: javadsl.Sink[T, M] ⇒ s.asScala - case g: GraphStageWithMaterializedValue[SinkShape[T], M] ⇒ + case s: Sink[T, M] => s + case s: javadsl.Sink[T, M] => s.asScala + case g: GraphStageWithMaterializedValue[SinkShape[T], M] => // move these from the stage itself to make the returned source // behave as it is the stage with regards to attributes val attrs = g.traversalBuilder.attributes @@ -148,7 +148,7 @@ object Sink { noAttrStage.shape ).withAttributes(attrs) - case other ⇒ new Sink( + case other => new Sink( LinearTraversalBuilder.fromBuilder(other.traversalBuilder, other.shape, Keep.right), other.shape) } @@ -174,7 +174,7 @@ object Sink { */ def head[T]: Sink[T, Future[T]] = Sink.fromGraph(new HeadOptionStage[T]).withAttributes(DefaultAttributes.headSink) - .mapMaterializedValue(e ⇒ e.map(_.getOrElse(throw new NoSuchElementException("head of empty stream")))(ExecutionContexts.sameThreadExecutionContext)) + .mapMaterializedValue(e => e.map(_.getOrElse(throw new NoSuchElementException("head of empty stream")))(ExecutionContexts.sameThreadExecutionContext)) /** * A `Sink` that materializes into a `Future` of the optional first value received. @@ -195,7 +195,7 @@ object Sink { */ def last[T]: Sink[T, Future[T]] = { Sink.fromGraph(new TakeLastStage[T](1)).withAttributes(DefaultAttributes.lastSink) - .mapMaterializedValue { e ⇒ + .mapMaterializedValue { e => e.map(_.headOption.getOrElse(throw new NoSuchElementException("last of empty stream")))(ExecutionContexts.sameThreadExecutionContext) } } @@ -209,7 +209,7 @@ object Sink { */ def lastOption[T]: Sink[T, Future[Option[T]]] = { Sink.fromGraph(new TakeLastStage[T](1)).withAttributes(DefaultAttributes.lastOptionSink) - .mapMaterializedValue { e ⇒ + .mapMaterializedValue { e => e.map(_.headOption)(ExecutionContexts.sameThreadExecutionContext) } } @@ -277,7 +277,7 @@ object Sink { * normal end of the stream, or completed with `Failure` if there is a failure signaled in * the stream. */ - def foreach[T](f: T ⇒ Unit): Sink[T, Future[Done]] = + def foreach[T](f: T => Unit): Sink[T, Future[Done]] = Flow[T].map(f).toMat(Sink.ignore)(Keep.right).named("foreachSink") /** @@ -286,15 +286,15 @@ object Sink { * normal end of the stream, or completed with `Failure` if there is a failure signaled in * the stream. */ - def foreachAsync[T](parallelism: Int)(f: T ⇒ Future[Unit]): Sink[T, Future[Done]] = + def foreachAsync[T](parallelism: Int)(f: T => Future[Unit]): Sink[T, Future[Done]] = Flow[T].mapAsyncUnordered(parallelism)(f).toMat(Sink.ignore)(Keep.right).named("foreachAsyncSink") /** * Combine several sinks with fan-out strategy like `Broadcast` or `Balance` and returns `Sink`. */ - def combine[T, U](first: Sink[U, _], second: Sink[U, _], rest: Sink[U, _]*)(strategy: Int ⇒ Graph[UniformFanOutShape[T, U], NotUsed]): Sink[T, NotUsed] = + def combine[T, U](first: Sink[U, _], second: Sink[U, _], rest: Sink[U, _]*)(strategy: Int => Graph[UniformFanOutShape[T, U], NotUsed]): Sink[T, NotUsed] = - Sink.fromGraph(GraphDSL.create() { implicit b ⇒ + Sink.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val d = b.add(strategy(rest.size + 2)) d.out(0) ~> first @@ -323,8 +323,8 @@ object Sink { * See also [[Flow.mapAsyncUnordered]] */ @deprecated("Use `foreachAsync` instead, it allows you to choose how to run the procedure, by calling some other API returning a Future or spawning a new Future.", since = "2.5.17") - def foreachParallel[T](parallelism: Int)(f: T ⇒ Unit)(implicit ec: ExecutionContext): Sink[T, Future[Done]] = - Flow[T].mapAsyncUnordered(parallelism)(t ⇒ Future(f(t))).toMat(Sink.ignore)(Keep.right) + def foreachParallel[T](parallelism: Int)(f: T => Unit)(implicit ec: ExecutionContext): Sink[T, Future[Done]] = + Flow[T].mapAsyncUnordered(parallelism)(t => Future(f(t))).toMat(Sink.ignore)(Keep.right) /** * A `Sink` that will invoke the given function for every received element, giving it its previous @@ -335,7 +335,7 @@ object Sink { * * @see [[#foldAsync]] */ - def fold[U, T](zero: U)(f: (U, T) ⇒ U): Sink[T, Future[U]] = + def fold[U, T](zero: U)(f: (U, T) => U): Sink[T, Future[U]] = Flow[T].fold(zero)(f).toMat(Sink.head)(Keep.right).named("foldSink") /** @@ -347,7 +347,7 @@ object Sink { * * @see [[#fold]] */ - def foldAsync[U, T](zero: U)(f: (U, T) ⇒ Future[U]): Sink[T, Future[U]] = Flow[T].foldAsync(zero)(f).toMat(Sink.head)(Keep.right).named("foldAsyncSink") + def foldAsync[U, T](zero: U)(f: (U, T) => Future[U]): Sink[T, Future[U]] = Flow[T].foldAsync(zero)(f).toMat(Sink.head)(Keep.right).named("foldAsyncSink") /** * A `Sink` that will invoke the given function for every received element, giving it its previous @@ -363,7 +363,7 @@ object Sink { * * Adheres to the [[ActorAttributes.SupervisionStrategy]] attribute. */ - def reduce[T](f: (T, T) ⇒ T): Sink[T, Future[T]] = + def reduce[T](f: (T, T) => T): Sink[T, Future[T]] = Flow[T].reduce(f).toMat(Sink.head)(Keep.right).named("reduceSink") /** @@ -371,7 +371,7 @@ object Sink { * completion, apply the provided function with [[scala.util.Success]] * or [[scala.util.Failure]]. */ - def onComplete[T](callback: Try[Done] ⇒ Unit): Sink[T, NotUsed] = { + def onComplete[T](callback: Try[Done] => Unit): Sink[T, NotUsed] = { def newOnCompleteStage(): GraphStage[FlowShape[T, NotUsed]] = { new GraphStage[FlowShape[T, NotUsed]] { @@ -430,7 +430,7 @@ object Sink { * to use a bounded mailbox with zero `mailbox-push-timeout-time` or use a rate * limiting operator in front of this `Sink`. */ - @InternalApi private[akka] def actorRef[T](ref: ActorRef, onCompleteMessage: Any, onFailureMessage: Throwable ⇒ Any): Sink[T, NotUsed] = + @InternalApi private[akka] def actorRef[T](ref: ActorRef, onCompleteMessage: Any, onFailureMessage: Throwable => Any): Sink[T, NotUsed] = fromGraph(new ActorRefSink(ref, onCompleteMessage, onFailureMessage, DefaultAttributes.actorRefSink, shape("ActorRefSink"))) @@ -450,7 +450,7 @@ object Sink { * limiting operator in front of this `Sink`. */ def actorRef[T](ref: ActorRef, onCompleteMessage: Any): Sink[T, NotUsed] = - fromGraph(new ActorRefSink(ref, onCompleteMessage, t ⇒ Status.Failure(t), + fromGraph(new ActorRefSink(ref, onCompleteMessage, t => Status.Failure(t), DefaultAttributes.actorRefSink, shape("ActorRefSink"))) /** @@ -473,9 +473,9 @@ object Sink { * When the stream is completed with failure - result of `onFailureMessage(throwable)` * function will be sent to the destination actor. */ - @InternalApi private[akka] def actorRefWithAck[T](ref: ActorRef, messageAdapter: ActorRef ⇒ T ⇒ Any, - onInitMessage: ActorRef ⇒ Any, ackMessage: Any, onCompleteMessage: Any, - onFailureMessage: (Throwable) ⇒ Any): Sink[T, NotUsed] = + @InternalApi private[akka] def actorRefWithAck[T](ref: ActorRef, messageAdapter: ActorRef => T => Any, + onInitMessage: ActorRef => Any, ackMessage: Any, onCompleteMessage: Any, + onFailureMessage: (Throwable) => Any): Sink[T, NotUsed] = Sink.fromGraph(new ActorRefBackpressureSinkStage(ref, messageAdapter, onInitMessage, ackMessage, onCompleteMessage, onFailureMessage)) /** @@ -493,8 +493,8 @@ object Sink { * */ def actorRefWithAck[T](ref: ActorRef, onInitMessage: Any, ackMessage: Any, onCompleteMessage: Any, - onFailureMessage: (Throwable) ⇒ Any = Status.Failure): Sink[T, NotUsed] = - actorRefWithAck(ref, _ ⇒ identity, _ ⇒ onInitMessage, ackMessage, onCompleteMessage, onFailureMessage) + onFailureMessage: (Throwable) => Any = Status.Failure): Sink[T, NotUsed] = + actorRefWithAck(ref, _ => identity, _ => onInitMessage, ackMessage, onCompleteMessage, onFailureMessage) /** * Creates a `Sink` that is materialized to an [[akka.actor.ActorRef]] which points to an Actor @@ -540,7 +540,7 @@ object Sink { */ @Deprecated @deprecated("Use lazyInitAsync instead. (lazyInitAsync no more needs a fallback function and the materialized value more clearly indicates if the internal sink was materialized or not.)", "2.5.11") - def lazyInit[T, M](sinkFactory: T ⇒ Future[Sink[T, M]], fallback: () ⇒ M): Sink[T, Future[M]] = + def lazyInit[T, M](sinkFactory: T => Future[Sink[T, M]], fallback: () => M): Sink[T, Future[M]] = Sink.fromGraph(new LazySink[T, M](sinkFactory)).mapMaterializedValue(_.map(_.getOrElse(fallback()))(ExecutionContexts.sameThreadExecutionContext)) /** @@ -552,7 +552,7 @@ object Sink { * sink fails then the `Future` is completed with the exception. * Otherwise the `Future` is completed with the materialized value of the internal sink. */ - def lazyInitAsync[T, M](sinkFactory: () ⇒ Future[Sink[T, M]]): Sink[T, Future[Option[M]]] = - Sink.fromGraph(new LazySink[T, M](_ ⇒ sinkFactory())) + def lazyInitAsync[T, M](sinkFactory: () => Future[Sink[T, M]]): Sink[T, Future[Option[M]]] = + Sink.fromGraph(new LazySink[T, M](_ => sinkFactory())) } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Source.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Source.scala index d34abf6d97..e90880db35 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Source.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Source.scala @@ -47,7 +47,7 @@ final class Source[+Out, +Mat]( override def via[T, Mat2](flow: Graph[FlowShape[Out, T], Mat2]): Repr[T] = viaMat(flow)(Keep.left) - override def viaMat[T, Mat2, Mat3](flow: Graph[FlowShape[Out, T], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): Source[T, Mat3] = { + override def viaMat[T, Mat2, Mat3](flow: Graph[FlowShape[Out, T], Mat2])(combine: (Mat, Mat2) => Mat3): Source[T, Mat3] = { if (flow.traversalBuilder eq Flow.identityTraversalBuilder) if (combine == Keep.left) //optimization by returning this @@ -77,15 +77,15 @@ final class Source[+Out, +Mat]( * Connect this [[akka.stream.scaladsl.Source]] to a [[akka.stream.scaladsl.Sink]], * concatenating the processing steps of both. */ - def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): RunnableGraph[Mat3] = { + def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) => Mat3): RunnableGraph[Mat3] = { RunnableGraph(traversalBuilder.append(sink.traversalBuilder, sink.shape, combine)) } /** * Transform only the materialized value of this Source, leaving all other properties as they were. */ - override def mapMaterializedValue[Mat2](f: Mat ⇒ Mat2): ReprMat[Out, Mat2] = - new Source[Out, Mat2](traversalBuilder.transformMat(f.asInstanceOf[Any ⇒ Any]), shape) + override def mapMaterializedValue[Mat2](f: Mat => Mat2): ReprMat[Out, Mat2] = + new Source[Out, Mat2](traversalBuilder.transformMat(f.asInstanceOf[Any => Any]), shape) /** * Materializes this Source, immediately returning (1) its materialized value, and (2) a new Source @@ -110,7 +110,7 @@ final class Source[+Out, +Mat]( * function evaluation when the input stream ends, or completed with `Failure` * if there is a failure signaled in the stream. */ - def runFold[U](zero: U)(f: (U, Out) ⇒ U)(implicit materializer: Materializer): Future[U] = runWith(Sink.fold(zero)(f)) + def runFold[U](zero: U)(f: (U, Out) => U)(implicit materializer: Materializer): Future[U] = runWith(Sink.fold(zero)(f)) /** * Shortcut for running this `Source` with a foldAsync function. @@ -120,7 +120,7 @@ final class Source[+Out, +Mat]( * function evaluation when the input stream ends, or completed with `Failure` * if there is a failure signaled in the stream. */ - def runFoldAsync[U](zero: U)(f: (U, Out) ⇒ Future[U])(implicit materializer: Materializer): Future[U] = runWith(Sink.foldAsync(zero)(f)) + def runFoldAsync[U](zero: U)(f: (U, Out) => Future[U])(implicit materializer: Materializer): Future[U] = runWith(Sink.foldAsync(zero)(f)) /** * Shortcut for running this `Source` with a reduce function. @@ -135,7 +135,7 @@ final class Source[+Out, +Mat]( * which is semantically in-line with that Scala's standard library collections * do in such situations. */ - def runReduce[U >: Out](f: (U, U) ⇒ U)(implicit materializer: Materializer): Future[U] = + def runReduce[U >: Out](f: (U, U) => U)(implicit materializer: Materializer): Future[U] = runWith(Sink.reduce(f)) /** @@ -146,7 +146,7 @@ final class Source[+Out, +Mat]( * the stream. */ // FIXME: Out => Unit should stay, right?? - def runForeach(f: Out ⇒ Unit)(implicit materializer: Materializer): Future[Done] = runWith(Sink.foreach(f)) + def runForeach(f: Out => Unit)(implicit materializer: Materializer): Future[Done] = runWith(Sink.foreach(f)) /** * Replace the attributes of this [[Source]] with the given ones. If this Source is a composite @@ -200,8 +200,8 @@ final class Source[+Out, +Mat]( * Combines several sources with fan-in strategy like `Merge` or `Concat` and returns `Source`. */ @deprecated("Use `Source.combine` on companion object instead", "2.5.5") - def combine[T, U](first: Source[T, _], second: Source[T, _], rest: Source[T, _]*)(strategy: Int ⇒ Graph[UniformFanInShape[T, U], NotUsed]): Source[U, NotUsed] = - Source.fromGraph(GraphDSL.create() { implicit b ⇒ + def combine[T, U](first: Source[T, _], second: Source[T, _], rest: Source[T, _]*)(strategy: Int => Graph[UniformFanInShape[T, U], NotUsed]): Source[U, NotUsed] = + Source.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val c = b.add(strategy(rest.size + 2)) first ~> c.in(0) @@ -220,7 +220,7 @@ final class Source[+Out, +Mat]( * API MAY CHANGE */ @ApiMayChange - def asSourceWithContext[Ctx](f: Out ⇒ Ctx): SourceWithContext[Out, Ctx, Mat] = new SourceWithContext(this.map(e ⇒ (e, f(e)))) + def asSourceWithContext[Ctx](f: Out => Ctx): SourceWithContext[Out, Ctx, Mat] = new SourceWithContext(this.map(e => (e, f(e)))) } object Source { @@ -248,7 +248,7 @@ object Source { * Elements are pulled out of the iterator in accordance with the demand coming * from the downstream transformation steps. */ - def fromIterator[T](f: () ⇒ Iterator[T]): Source[T, NotUsed] = + def fromIterator[T](f: () => Iterator[T]): Source[T, NotUsed] = apply(new immutable.Iterable[T] { override def iterator: Iterator[T] = f() override def toString: String = "() => Iterator" @@ -260,9 +260,9 @@ object Source { * Starts a new 'cycled' `Source` from the given elements. The producer stream of elements * will continue infinitely by repeating the sequence of elements provided by function parameter. */ - def cycle[T](f: () ⇒ Iterator[T]): Source[T, NotUsed] = { + def cycle[T](f: () => Iterator[T]): Source[T, NotUsed] = { val iterator = Iterator.continually { val i = f(); if (i.isEmpty) throw new IllegalArgumentException("empty iterator") else i }.flatten - fromIterator(() ⇒ iterator).withAttributes(DefaultAttributes.cycledSource) + fromIterator(() => iterator).withAttributes(DefaultAttributes.cycledSource) } /** @@ -270,9 +270,9 @@ object Source { * it so also in type. */ def fromGraph[T, M](g: Graph[SourceShape[T], M]): Source[T, M] = g match { - case s: Source[T, M] ⇒ s - case s: javadsl.Source[T, M] ⇒ s.asScala - case g: GraphStageWithMaterializedValue[SourceShape[T], M] ⇒ + case s: Source[T, M] => s + case s: javadsl.Source[T, M] => s.asScala + case g: GraphStageWithMaterializedValue[SourceShape[T], M] => // move these from the stage itself to make the returned source // behave as it is the stage with regards to attributes val attrs = g.traversalBuilder.attributes @@ -281,7 +281,7 @@ object Source { LinearTraversalBuilder.fromBuilder(noAttrStage.traversalBuilder, noAttrStage.shape, Keep.right), noAttrStage.shape ).withAttributes(attrs) - case other ⇒ + case other => // composite source shaped graph new Source( LinearTraversalBuilder.fromBuilder(other.traversalBuilder, other.shape, Keep.right), @@ -355,7 +355,7 @@ object Source { */ def repeat[T](element: T): Source[T, NotUsed] = { val next = Some((element, element)) - unfold(element)(_ ⇒ next).withAttributes(DefaultAttributes.repeat) + unfold(element)(_ => next).withAttributes(DefaultAttributes.repeat) } /** @@ -365,13 +365,13 @@ object Source { * For example, all the Fibonacci numbers under 10M: * * {{{ - * Source.unfold(0 → 1) { - * case (a, _) if a > 10000000 ⇒ None - * case (a, b) ⇒ Some((b → (a + b)) → a) + * Source.unfold(0 -> 1) { + * case (a, _) if a > 10000000 => None + * case (a, b) => Some((b -> (a + b)) -> a) * } * }}} */ - def unfold[S, E](s: S)(f: S ⇒ Option[(S, E)]): Source[E, NotUsed] = + def unfold[S, E](s: S)(f: S => Option[(S, E)]): Source[E, NotUsed] = Source.fromGraph(new Unfold(s, f)) /** @@ -380,16 +380,16 @@ object Source { * async fibonacci example: * * {{{ - * Source.unfoldAsync(0 → 1) { - * case (a, _) if a > 10000000 ⇒ Future.successful(None) - * case (a, b) ⇒ Future{ + * Source.unfoldAsync(0 -> 1) { + * case (a, _) if a > 10000000 => Future.successful(None) + * case (a, b) => Future{ * Thread.sleep(1000) - * Some((b → (a + b)) → a) + * Some((b -> (a + b)) -> a) * } * } * }}} */ - def unfoldAsync[S, E](s: S)(f: S ⇒ Future[Option[(S, E)]]): Source[E, NotUsed] = + def unfoldAsync[S, E](s: S)(f: S => Future[Option[(S, E)]]): Source[E, NotUsed] = Source.fromGraph(new UnfoldAsync(s, f)) /** @@ -424,7 +424,7 @@ object Source { * the materialized future is completed with its value, if downstream cancels or fails without any demand the * create factory is never called and the materialized `Future` is failed. */ - def lazily[T, M](create: () ⇒ Source[T, M]): Source[T, Future[M]] = + def lazily[T, M](create: () => Source[T, M]): Source[T, Future[M]] = Source.fromGraph(new LazySource[T, M](create)) /** @@ -434,8 +434,8 @@ object Source { * * @see [[Source.lazily]] */ - def lazilyAsync[T](create: () ⇒ Future[T]): Source[T, Future[NotUsed]] = - lazily(() ⇒ fromFuture(create())) + def lazilyAsync[T](create: () => Future[T]): Source[T, Future[NotUsed]] = + lazily(() => fromFuture(create())) /** * Creates a `Source` that is materialized as a [[org.reactivestreams.Subscriber]] @@ -540,17 +540,17 @@ object Source { def actorRef[T](bufferSize: Int, overflowStrategy: OverflowStrategy): Source[T, ActorRef] = actorRef( { - case akka.actor.Status.Success ⇒ - case akka.actor.Status.Success(_) ⇒ + case akka.actor.Status.Success => + case akka.actor.Status.Success(_) => }, - { case akka.actor.Status.Failure(cause) ⇒ cause }, + { case akka.actor.Status.Failure(cause) => cause }, bufferSize, overflowStrategy) /** * Combines several sources with fan-in strategy like `Merge` or `Concat` and returns `Source`. */ - def combine[T, U](first: Source[T, _], second: Source[T, _], rest: Source[T, _]*)(strategy: Int ⇒ Graph[UniformFanInShape[T, U], NotUsed]): Source[U, NotUsed] = - Source.fromGraph(GraphDSL.create() { implicit b ⇒ + def combine[T, U](first: Source[T, _], second: Source[T, _], rest: Source[T, _]*)(strategy: Int => Graph[UniformFanInShape[T, U], NotUsed]): Source[U, NotUsed] = + Source.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val c = b.add(strategy(rest.size + 2)) first ~> c.in(0) @@ -568,8 +568,8 @@ object Source { /** * Combines two sources with fan-in strategy like `Merge` or `Concat` and returns `Source` with a materialized value. */ - def combineMat[T, U, M1, M2, M](first: Source[T, M1], second: Source[T, M2])(strategy: Int ⇒ Graph[UniformFanInShape[T, U], NotUsed])(matF: (M1, M2) ⇒ M): Source[U, M] = { - val secondPartiallyCombined = GraphDSL.create(second) { implicit b ⇒ secondShape ⇒ + def combineMat[T, U, M1, M2, M](first: Source[T, M1], second: Source[T, M2])(strategy: Int => Graph[UniformFanInShape[T, U], NotUsed])(matF: (M1, M2) => M): Source[U, M] = { + val secondPartiallyCombined = GraphDSL.create(second) { implicit b => secondShape => import GraphDSL.Implicits._ val c = b.add(strategy(2)) secondShape ~> c.in(1) @@ -586,11 +586,11 @@ object Source { /* * Combine the elements of multiple streams into a stream of sequences using a combiner function. */ - def zipWithN[T, O](zipper: immutable.Seq[T] ⇒ O)(sources: immutable.Seq[Source[T, _]]): Source[O, NotUsed] = { + def zipWithN[T, O](zipper: immutable.Seq[T] => O)(sources: immutable.Seq[Source[T, _]]): Source[O, NotUsed] = { val source = sources match { - case immutable.Seq() ⇒ empty[O] - case immutable.Seq(source) ⇒ source.map(t ⇒ zipper(immutable.Seq(t))).mapMaterializedValue(_ ⇒ NotUsed) - case s1 +: s2 +: ss ⇒ combine(s1, s2, ss: _*)(ZipWithN(zipper)) + case immutable.Seq() => empty[O] + case immutable.Seq(source) => source.map(t => zipper(immutable.Seq(t))).mapMaterializedValue(_ => NotUsed) + case s1 +: s2 +: ss => combine(s1, s2, ss: _*)(ZipWithN(zipper)) } source.addAttributes(DefaultAttributes.zipWithN) @@ -655,7 +655,7 @@ object Source { * is received. Stream calls close and completes when `read` returns None. * @param close - function that closes resource */ - def unfoldResource[T, S](create: () ⇒ S, read: (S) ⇒ Option[T], close: (S) ⇒ Unit): Source[T, NotUsed] = + def unfoldResource[T, S](create: () => S, read: (S) => Option[T], close: (S) => Unit): Source[T, NotUsed] = Source.fromGraph(new UnfoldResourceSource(create, read, close)) /** @@ -678,7 +678,7 @@ object Source { * is received. Stream calls close and completes when `Future` from read function returns None. * @param close - function that closes resource */ - def unfoldResourceAsync[T, S](create: () ⇒ Future[S], read: (S) ⇒ Future[Option[T]], close: (S) ⇒ Future[Done]): Source[T, NotUsed] = + def unfoldResourceAsync[T, S](create: () => Future[S], read: (S) => Future[Option[T]], close: (S) => Future[Done]): Source[T, NotUsed] = Source.fromGraph(new UnfoldResourceSourceAsync(create, read, close)) } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/SourceWithContext.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/SourceWithContext.scala index 232b54e7fa..f19300a106 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/SourceWithContext.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/SourceWithContext.scala @@ -41,7 +41,7 @@ final class SourceWithContext[+Out, +Ctx, +Mat] private[stream] ( override def via[Out2, Ctx2, Mat2](viaFlow: Graph[FlowShape[(Out, Ctx), (Out2, Ctx2)], Mat2]): Repr[Out2, Ctx2] = new SourceWithContext(delegate.via(viaFlow)) - override def viaMat[Out2, Ctx2, Mat2, Mat3](flow: Graph[FlowShape[(Out, Ctx), (Out2, Ctx2)], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): SourceWithContext[Out2, Ctx2, Mat3] = + override def viaMat[Out2, Ctx2, Mat2, Mat3](flow: Graph[FlowShape[(Out, Ctx), (Out2, Ctx2)], Mat2])(combine: (Mat, Mat2) => Mat3): SourceWithContext[Out2, Ctx2, Mat3] = new SourceWithContext(delegate.viaMat(flow)(combine)) /** @@ -63,7 +63,7 @@ final class SourceWithContext[+Out, +Ctx, +Mat] private[stream] ( * Connect this [[akka.stream.scaladsl.SourceWithContext]] to a [[akka.stream.scaladsl.Sink]], * concatenating the processing steps of both. */ - def toMat[Mat2, Mat3](sink: Graph[SinkShape[(Out, Ctx)], Mat2])(combine: (Mat, Mat2) ⇒ Mat3): RunnableGraph[Mat3] = + def toMat[Mat2, Mat3](sink: Graph[SinkShape[(Out, Ctx)], Mat2])(combine: (Mat, Mat2) => Mat3): RunnableGraph[Mat3] = delegate.toMat(sink)(combine) /** diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/StreamConverters.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/StreamConverters.scala index 6e1573dd8d..3e72848998 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/StreamConverters.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/StreamConverters.scala @@ -24,8 +24,8 @@ import akka.NotUsed */ object StreamConverters { - import Source.{ shape ⇒ sourceShape } - import Sink.{ shape ⇒ sinkShape } + import Source.{ shape => sourceShape } + import Sink.{ shape => sinkShape } /** * Creates a Source from an [[InputStream]] created by the given function. @@ -45,7 +45,7 @@ object StreamConverters { * @param in a function which creates the InputStream to read from * @param chunkSize the size of each read operation, defaults to 8192 */ - def fromInputStream(in: () ⇒ InputStream, chunkSize: Int = 8192): Source[ByteString, Future[IOResult]] = + def fromInputStream(in: () => InputStream, chunkSize: Int = 8192): Source[ByteString, Future[IOResult]] = Source.fromGraph(new InputStreamSource(in, chunkSize, DefaultAttributes.inputStreamSource, sourceShape("InputStreamSource"))) /** @@ -78,7 +78,7 @@ object StreamConverters { * The [[OutputStream]] will be closed when the stream flowing into this [[Sink]] is completed. The [[Sink]] * will cancel the stream when the [[OutputStream]] is no longer writable. */ - def fromOutputStream(out: () ⇒ OutputStream, autoFlush: Boolean = false): Sink[ByteString, Future[IOResult]] = + def fromOutputStream(out: () => OutputStream, autoFlush: Boolean = false): Sink[ByteString, Future[IOResult]] = Sink.fromGraph(new OutputStreamSink(out, DefaultAttributes.outputStreamSink, sinkShape("OutputStreamSink"), autoFlush)) /** @@ -108,10 +108,10 @@ object StreamConverters { * Note that a flow can be materialized multiple times, so the function producing the ``Collector`` must be able * to handle multiple invocations. */ - def javaCollector[T, R](collectorFactory: () ⇒ java.util.stream.Collector[T, _ <: Any, R]): Sink[T, Future[R]] = - Flow[T].fold(() ⇒ - new CollectorState[T, R](collectorFactory().asInstanceOf[Collector[T, Any, R]])) { (state, elem) ⇒ () ⇒ state().update(elem) } - .map(state ⇒ state().finish()) + def javaCollector[T, R](collectorFactory: () => java.util.stream.Collector[T, _ <: Any, R]): Sink[T, Future[R]] = + Flow[T].fold(() => + new CollectorState[T, R](collectorFactory().asInstanceOf[Collector[T, Any, R]])) { (state, elem) => () => state().update(elem) } + .map(state => state().finish()) .toMat(Sink.head)(Keep.right).withAttributes(DefaultAttributes.javaCollector) /** @@ -124,26 +124,26 @@ object StreamConverters { * Note that a flow can be materialized multiple times, so the function producing the ``Collector`` must be able * to handle multiple invocations. */ - def javaCollectorParallelUnordered[T, R](parallelism: Int)(collectorFactory: () ⇒ java.util.stream.Collector[T, _ <: Any, R]): Sink[T, Future[R]] = { + def javaCollectorParallelUnordered[T, R](parallelism: Int)(collectorFactory: () => java.util.stream.Collector[T, _ <: Any, R]): Sink[T, Future[R]] = { if (parallelism == 1) javaCollector[T, R](collectorFactory) else { - Sink.fromGraph(GraphDSL.create(Sink.head[R]) { implicit b ⇒ sink ⇒ + Sink.fromGraph(GraphDSL.create(Sink.head[R]) { implicit b => sink => import GraphDSL.Implicits._ val collector = collectorFactory().asInstanceOf[Collector[T, Any, R]] val balance = b.add(Balance[T](parallelism)) - val merge = b.add(Merge[() ⇒ CollectorState[T, R]](parallelism)) + val merge = b.add(Merge[() => CollectorState[T, R]](parallelism)) - for (i ← 0 until parallelism) { + for (i <- 0 until parallelism) { val worker = Flow[T] - .fold(() ⇒ new CollectorState(collector)) { (state, elem) ⇒ () ⇒ state().update(elem) } + .fold(() => new CollectorState(collector)) { (state, elem) => () => state().update(elem) } .async balance.out(i) ~> worker ~> merge.in(i) } merge.out - .fold(() ⇒ new ReducerState(collector)) { (state, elem) ⇒ () ⇒ state().update(elem().accumulated) } - .map(state ⇒ state().finish()) ~> sink.in + .fold(() => new ReducerState(collector)) { (state, elem) => () => state().update(elem().accumulated) } + .map(state => state().finish()) ~> sink.in SinkShape(balance.in) }).withAttributes(DefaultAttributes.javaCollectorParallelUnordered) @@ -166,7 +166,7 @@ object StreamConverters { def asJavaStream[T](): Sink[T, java.util.stream.Stream[T]] = { // TODO removing the QueueSink name, see issue #22523 Sink.fromGraph(new QueueSink[T]().withAttributes(Attributes.none)) - .mapMaterializedValue(queue ⇒ StreamSupport.stream( + .mapMaterializedValue(queue => StreamSupport.stream( Spliterators.spliteratorUnknownSize(new java.util.Iterator[T] { var nextElementFuture: Future[Option[T]] = queue.pull() var nextElement: Option[T] = _ @@ -189,11 +189,11 @@ object StreamConverters { * Creates a source that wraps a Java 8 ``Stream``. ``Source`` uses a stream iterator to get all its * elements and send them downstream on demand. * - * Example usage: `Source.fromJavaStream(() ⇒ IntStream.rangeClosed(1, 10))` + * Example usage: `Source.fromJavaStream(() => IntStream.rangeClosed(1, 10))` * * You can use [[Source.async]] to create asynchronous boundaries between synchronous Java ``Stream`` * and the rest of flow. */ - def fromJavaStream[T, S <: java.util.stream.BaseStream[T, S]](stream: () ⇒ java.util.stream.BaseStream[T, S]): Source[T, NotUsed] = + def fromJavaStream[T, S <: java.util.stream.BaseStream[T, S]](stream: () => java.util.stream.BaseStream[T, S]): Source[T, NotUsed] = Source.fromGraph(new JavaStreamSource[T, S](stream)).withAttributes(DefaultAttributes.fromJavaStream) } diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/TLS.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/TLS.scala index d37a115712..89c4334c6f 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/TLS.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/TLS.scala @@ -79,13 +79,13 @@ object TLS { def theSslConfig(system: ActorSystem): AkkaSSLConfig = sslConfig.getOrElse(AkkaSSLConfig(system)) - val createSSLEngine = { system: ActorSystem ⇒ + val createSSLEngine = { system: ActorSystem => val config = theSslConfig(system) val engine = hostInfo match { - case Some((hostname, port)) if !config.config.loose.disableSNI ⇒ + case Some((hostname, port)) if !config.config.loose.disableSNI => sslContext.createSSLEngine(hostname, port) - case _ ⇒ sslContext.createSSLEngine() + case _ => sslContext.createSSLEngine() } config.sslEngineConfigurator.configure(engine, sslContext) @@ -106,16 +106,16 @@ object TLS { TlsUtils.applySessionParameters(engine, finalSessionParameters) engine } - def verifySession: (ActorSystem, SSLSession) ⇒ Try[Unit] = + def verifySession: (ActorSystem, SSLSession) => Try[Unit] = hostInfo match { - case Some((hostname, _)) ⇒ { (system, session) ⇒ + case Some((hostname, _)) => { (system, session) => val hostnameVerifier = theSslConfig(system).hostnameVerifier if (!hostnameVerifier.verify(hostname, session)) Failure(new ConnectionException(s"Hostname verification failed! Expected session to be for $hostname")) else Success(()) } - case None ⇒ (_, _) ⇒ Success(()) + case None => (_, _) => Success(()) } scaladsl.BidiFlow.fromGraph(TlsModule(Attributes.none, createSSLEngine, verifySession, closing)) @@ -169,11 +169,11 @@ object TLS { * For a description of the `closing` parameter please refer to [[TLSClosing]]. */ def apply( - createSSLEngine: () ⇒ SSLEngine, // we don't offer the internal `ActorSystem => SSLEngine` API here, see #21753 - verifySession: SSLSession ⇒ Try[Unit], // we don't offer the internal API that provides `ActorSystem` here, see #21753 + createSSLEngine: () => SSLEngine, // we don't offer the internal `ActorSystem => SSLEngine` API here, see #21753 + verifySession: SSLSession => Try[Unit], // we don't offer the internal API that provides `ActorSystem` here, see #21753 closing: TLSClosing ): scaladsl.BidiFlow[SslTlsOutbound, ByteString, ByteString, SslTlsInbound, NotUsed] = - scaladsl.BidiFlow.fromGraph(TlsModule(Attributes.none, _ ⇒ createSSLEngine(), (_, session) ⇒ verifySession(session), closing)) + scaladsl.BidiFlow.fromGraph(TlsModule(Attributes.none, _ => createSSLEngine(), (_, session) => verifySession(session), closing)) /** * Create a StreamTls [[akka.stream.scaladsl.BidiFlow]]. This is a low-level interface. @@ -184,10 +184,10 @@ object TLS { * For a description of the `closing` parameter please refer to [[TLSClosing]]. */ def apply( - createSSLEngine: () ⇒ SSLEngine, // we don't offer the internal `ActorSystem => SSLEngine` API here, see #21753 + createSSLEngine: () => SSLEngine, // we don't offer the internal `ActorSystem => SSLEngine` API here, see #21753 closing: TLSClosing ): scaladsl.BidiFlow[SslTlsOutbound, ByteString, ByteString, SslTlsInbound, NotUsed] = - apply(createSSLEngine, _ ⇒ Success(()), closing) + apply(createSSLEngine, _ => Success(()), closing) } /** @@ -203,8 +203,8 @@ object TLSPlacebo { def apply(): scaladsl.BidiFlow[SslTlsOutbound, ByteString, ByteString, SessionBytes, NotUsed] = instance private val instance: scaladsl.BidiFlow[SslTlsOutbound, ByteString, ByteString, SessionBytes, NotUsed] = - scaladsl.BidiFlow.fromGraph(scaladsl.GraphDSL.create() { implicit b ⇒ - val top = b.add(scaladsl.Flow[SslTlsOutbound].collect { case SendBytes(bytes) ⇒ bytes }) + scaladsl.BidiFlow.fromGraph(scaladsl.GraphDSL.create() { implicit b => + val top = b.add(scaladsl.Flow[SslTlsOutbound].collect { case SendBytes(bytes) => bytes }) val bottom = b.add(scaladsl.Flow[ByteString].map(SessionBytes(dummySession, _))) BidiShape.fromFlows(top, bottom) }) @@ -240,14 +240,14 @@ trait ScalaSessionAPI { */ def peerCertificates: List[Certificate] = try Option(session.getPeerCertificates).map(_.toList).getOrElse(Nil) - catch { case e: SSLPeerUnverifiedException ⇒ Nil } + catch { case e: SSLPeerUnverifiedException => Nil } /** * Scala API: Extract the Principal that the peer engine presented during * this session’s negotiation. */ def peerPrincipal: Option[Principal] = try Option(session.getPeerPrincipal) - catch { case e: SSLPeerUnverifiedException ⇒ None } + catch { case e: SSLPeerUnverifiedException => None } } object ScalaSessionAPI { diff --git a/akka-stream/src/main/scala/akka/stream/scaladsl/Tcp.scala b/akka-stream/src/main/scala/akka/stream/scaladsl/Tcp.scala index 9ed696f3e0..e90ccbcd4b 100644 --- a/akka-stream/src/main/scala/akka/stream/scaladsl/Tcp.scala +++ b/akka-stream/src/main/scala/akka/stream/scaladsl/Tcp.scala @@ -13,7 +13,7 @@ import javax.net.ssl.SSLSession import akka.actor._ import akka.annotation.{ ApiMayChange, InternalApi } import akka.io.Inet.SocketOption -import akka.io.{ IO, Tcp ⇒ IoTcp } +import akka.io.{ IO, Tcp => IoTcp } import akka.stream.TLSProtocol.NegotiateNewSession import akka.stream._ import akka.stream.impl.fusing.GraphStages.detacher @@ -39,7 +39,7 @@ object Tcp extends ExtensionId[Tcp] with ExtensionIdProvider { * @param whenUnbound A future that is completed when the server is unbound, or failed if the server binding fails */ final case class ServerBinding @InternalApi private[akka] (localAddress: InetSocketAddress)( - private val unbindAction: () ⇒ Future[Unit], + private val unbindAction: () => Future[Unit], val whenUnbound: Future[Done] ) { def unbind(): Future[Unit] = unbindAction() @@ -81,7 +81,7 @@ object Tcp extends ExtensionId[Tcp] with ExtensionIdProvider { private val tlsWrapping: BidiFlow[ByteString, TLSProtocol.SendBytes, TLSProtocol.SslTlsInbound, ByteString, NotUsed] = BidiFlow.fromFlows( Flow[ByteString].map(TLSProtocol.SendBytes), Flow[TLSProtocol.SslTlsInbound].collect { - case sb: TLSProtocol.SessionBytes ⇒ sb.bytes + case sb: TLSProtocol.SessionBytes => sb.bytes // ignore other kinds of inbounds (currently only Truncated) } ) @@ -164,7 +164,7 @@ final class Tcp(system: ExtendedActorSystem) extends akka.actor.Extension { options: immutable.Traversable[SocketOption] = Nil, halfClose: Boolean = false, idleTimeout: Duration = Duration.Inf)(implicit m: Materializer): Future[ServerBinding] = { - bind(interface, port, backlog, options, halfClose, idleTimeout).to(Sink.foreach { conn: IncomingConnection ⇒ + bind(interface, port, backlog, options, halfClose, idleTimeout).to(Sink.foreach { conn: IncomingConnection => conn.flow.join(handler).run() }).run() } @@ -207,8 +207,8 @@ final class Tcp(system: ExtendedActorSystem) extends akka.actor.Extension { settings.ioSettings)).via(detacher[ByteString]) // must read ahead for proper completions idleTimeout match { - case d: FiniteDuration ⇒ tcpFlow.join(TcpIdleTimeout(d, Some(remoteAddress))) - case _ ⇒ tcpFlow + case d: FiniteDuration => tcpFlow.join(TcpIdleTimeout(d, Some(remoteAddress))) + case _ => tcpFlow } } @@ -274,12 +274,12 @@ final class Tcp(system: ExtendedActorSystem) extends akka.actor.Extension { */ @InternalApi private[akka] def outgoingTlsConnectionWithSSLEngine( remoteAddress: InetSocketAddress, - createSSLEngine: () ⇒ SSLEngine, + createSSLEngine: () => SSLEngine, localAddress: Option[InetSocketAddress] = None, options: immutable.Traversable[SocketOption] = Nil, connectTimeout: Duration = Duration.Inf, idleTimeout: Duration = Duration.Inf, - verifySession: SSLSession ⇒ Try[Unit], + verifySession: SSLSession => Try[Unit], closing: TLSClosing = IgnoreComplete): Flow[ByteString, ByteString, Future[OutgoingConnection]] = { val connection = outgoingConnection(remoteAddress, localAddress, options, true, connectTimeout, idleTimeout) @@ -309,7 +309,7 @@ final class Tcp(system: ExtendedActorSystem) extends akka.actor.Extension { val tls = tlsWrapping.atop(TLS(sslContext, negotiateNewSession, TLSRole.server)).reversed - bind(interface, port, backlog, options, true, idleTimeout).map { incomingConnection ⇒ + bind(interface, port, backlog, options, true, idleTimeout).map { incomingConnection => incomingConnection.copy( flow = incomingConnection.flow.join(tls) ) @@ -322,16 +322,16 @@ final class Tcp(system: ExtendedActorSystem) extends akka.actor.Extension { @InternalApi private[akka] def bindTlsWithSSLEngine( interface: String, port: Int, - createSSLEngine: () ⇒ SSLEngine, + createSSLEngine: () => SSLEngine, backlog: Int = 100, options: immutable.Traversable[SocketOption] = Nil, idleTimeout: Duration = Duration.Inf, - verifySession: SSLSession ⇒ Try[Unit], + verifySession: SSLSession => Try[Unit], closing: TLSClosing = IgnoreComplete): Source[IncomingConnection, Future[ServerBinding]] = { val tls = tlsWrapping.atop(TLS(createSSLEngine, verifySession, closing)).reversed - bind(interface, port, backlog, options, true, idleTimeout).map { incomingConnection ⇒ + bind(interface, port, backlog, options, true, idleTimeout).map { incomingConnection => incomingConnection.copy( flow = incomingConnection.flow.join(tls) ) @@ -359,7 +359,7 @@ final class Tcp(system: ExtendedActorSystem) extends akka.actor.Extension { options: immutable.Traversable[SocketOption] = Nil, idleTimeout: Duration = Duration.Inf)(implicit m: Materializer): Future[ServerBinding] = { bindTls(interface, port, sslContext, negotiateNewSession, backlog, options, idleTimeout) - .to(Sink.foreach { conn: IncomingConnection ⇒ + .to(Sink.foreach { conn: IncomingConnection => conn.handleWith(handler) }).run() } diff --git a/akka-stream/src/main/scala/akka/stream/serialization/StreamRefSerializer.scala b/akka-stream/src/main/scala/akka/stream/serialization/StreamRefSerializer.scala index 46f1e05b13..d41f99a12e 100644 --- a/akka-stream/src/main/scala/akka/stream/serialization/StreamRefSerializer.scala +++ b/akka-stream/src/main/scala/akka/stream/serialization/StreamRefSerializer.scala @@ -28,46 +28,46 @@ private[akka] final class StreamRefSerializer(val system: ExtendedActorSystem) e override def manifest(o: AnyRef): String = o match { // protocol - case _: StreamRefsProtocol.SequencedOnNext[_] ⇒ SequencedOnNextManifest - case _: StreamRefsProtocol.CumulativeDemand ⇒ CumulativeDemandManifest + case _: StreamRefsProtocol.SequencedOnNext[_] => SequencedOnNextManifest + case _: StreamRefsProtocol.CumulativeDemand => CumulativeDemandManifest // handshake - case _: StreamRefsProtocol.OnSubscribeHandshake ⇒ OnSubscribeHandshakeManifest + case _: StreamRefsProtocol.OnSubscribeHandshake => OnSubscribeHandshakeManifest // completion - case _: StreamRefsProtocol.RemoteStreamFailure ⇒ RemoteSinkFailureManifest - case _: StreamRefsProtocol.RemoteStreamCompleted ⇒ RemoteSinkCompletedManifest + case _: StreamRefsProtocol.RemoteStreamFailure => RemoteSinkFailureManifest + case _: StreamRefsProtocol.RemoteStreamCompleted => RemoteSinkCompletedManifest // refs - case _: SourceRefImpl[_] ⇒ SourceRefManifest - // case _: MaterializedSourceRef[_] ⇒ SourceRefManifest - case _: SinkRefImpl[_] ⇒ SinkRefManifest - // case _: MaterializedSinkRef[_] ⇒ SinkRefManifest + case _: SourceRefImpl[_] => SourceRefManifest + // case _: MaterializedSourceRef[_] => SourceRefManifest + case _: SinkRefImpl[_] => SinkRefManifest + // case _: MaterializedSinkRef[_] => SinkRefManifest } override def toBinary(o: AnyRef): Array[Byte] = o match { // protocol - case o: StreamRefsProtocol.SequencedOnNext[_] ⇒ serializeSequencedOnNext(o).toByteArray - case d: StreamRefsProtocol.CumulativeDemand ⇒ serializeCumulativeDemand(d).toByteArray + case o: StreamRefsProtocol.SequencedOnNext[_] => serializeSequencedOnNext(o).toByteArray + case d: StreamRefsProtocol.CumulativeDemand => serializeCumulativeDemand(d).toByteArray // handshake - case h: StreamRefsProtocol.OnSubscribeHandshake ⇒ serializeOnSubscribeHandshake(h).toByteArray + case h: StreamRefsProtocol.OnSubscribeHandshake => serializeOnSubscribeHandshake(h).toByteArray // termination - case d: StreamRefsProtocol.RemoteStreamFailure ⇒ serializeRemoteSinkFailure(d).toByteArray - case d: StreamRefsProtocol.RemoteStreamCompleted ⇒ serializeRemoteSinkCompleted(d).toByteArray + case d: StreamRefsProtocol.RemoteStreamFailure => serializeRemoteSinkFailure(d).toByteArray + case d: StreamRefsProtocol.RemoteStreamCompleted => serializeRemoteSinkCompleted(d).toByteArray // refs - case ref: SinkRefImpl[_] ⇒ serializeSinkRef(ref).toByteArray - // case ref: MaterializedSinkRef[_] ⇒ ??? // serializeSinkRef(ref).toByteArray - case ref: SourceRefImpl[_] ⇒ serializeSourceRef(ref).toByteArray - // case ref: MaterializedSourceRef[_] ⇒ serializeSourceRef(ref.).toByteArray + case ref: SinkRefImpl[_] => serializeSinkRef(ref).toByteArray + // case ref: MaterializedSinkRef[_] => ??? // serializeSinkRef(ref).toByteArray + case ref: SourceRefImpl[_] => serializeSourceRef(ref).toByteArray + // case ref: MaterializedSourceRef[_] => serializeSourceRef(ref.).toByteArray } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { // protocol - case OnSubscribeHandshakeManifest ⇒ deserializeOnSubscribeHandshake(bytes) - case SequencedOnNextManifest ⇒ deserializeSequencedOnNext(bytes) - case CumulativeDemandManifest ⇒ deserializeCumulativeDemand(bytes) - case RemoteSinkCompletedManifest ⇒ deserializeRemoteStreamCompleted(bytes) - case RemoteSinkFailureManifest ⇒ deserializeRemoteStreamFailure(bytes) + case OnSubscribeHandshakeManifest => deserializeOnSubscribeHandshake(bytes) + case SequencedOnNextManifest => deserializeSequencedOnNext(bytes) + case CumulativeDemandManifest => deserializeCumulativeDemand(bytes) + case RemoteSinkCompletedManifest => deserializeRemoteStreamCompleted(bytes) + case RemoteSinkFailureManifest => deserializeRemoteStreamFailure(bytes) // refs - case SinkRefManifest ⇒ deserializeSinkRef(bytes) - case SourceRefManifest ⇒ deserializeSourceRef(bytes) + case SinkRefManifest => deserializeSinkRef(bytes) + case SourceRefManifest => deserializeSourceRef(bytes) } // ----- diff --git a/akka-stream/src/main/scala/akka/stream/snapshot/MaterializerState.scala b/akka-stream/src/main/scala/akka/stream/snapshot/MaterializerState.scala index 0fcda7a721..40fbd5d26a 100644 --- a/akka-stream/src/main/scala/akka/stream/snapshot/MaterializerState.scala +++ b/akka-stream/src/main/scala/akka/stream/snapshot/MaterializerState.scala @@ -32,7 +32,7 @@ object MaterializerState { @ApiMayChange def streamSnapshots(mat: Materializer): Future[immutable.Seq[StreamSnapshot]] = { mat match { - case impl: PhasedFusingActorMaterializer ⇒ + case impl: PhasedFusingActorMaterializer => import impl.system.dispatcher requestFromSupervisor(impl.supervisor) } @@ -45,7 +45,7 @@ object MaterializerState { implicit val timeout: Timeout = 10.seconds (supervisor ? StreamSupervisor.GetChildren) .mapTo[StreamSupervisor.Children] - .flatMap(msg ⇒ + .flatMap(msg => Future.sequence(msg.children.toVector.map(requestFromChild)) ) } diff --git a/akka-stream/src/main/scala/akka/stream/stage/GraphStage.scala b/akka-stream/src/main/scala/akka/stream/stage/GraphStage.scala index db5f653d5e..c954a20806 100644 --- a/akka-stream/src/main/scala/akka/stream/stage/GraphStage.scala +++ b/akka-stream/src/main/scala/akka/stream/stage/GraphStage.scala @@ -75,7 +75,7 @@ abstract class AbstractGraphStageWithMaterializedValue[+S <: Shape, M] extends G @throws(classOf[Exception]) final def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, M) = { val pair = createLogicAndMaterializedValuePair(inheritedAttributes) - pair.first → pair.second + pair.first -> pair.second } @throws(classOf[Exception]) @@ -128,7 +128,7 @@ object GraphStageLogic { * Input handler that terminates the state upon receiving completion if the * given condition holds at that time. The operator fails upon receiving a failure. */ - class ConditionalTerminateInput(predicate: () ⇒ Boolean) extends InHandler { + class ConditionalTerminateInput(predicate: () => Boolean) extends InHandler { override def onPush(): Unit = () override def onUpstreamFinish(): Unit = if (predicate()) GraphInterpreter.currentInterpreter.activeStage.completeStage() @@ -165,13 +165,13 @@ object GraphStageLogic { * Output handler that terminates the state upon receiving completion if the * given condition holds at that time. The operator fails upon receiving a failure. */ - class ConditionalTerminateOutput(predicate: () ⇒ Boolean) extends OutHandler { + class ConditionalTerminateOutput(predicate: () => Boolean) extends OutHandler { override def onPull(): Unit = () override def onDownstreamFinish(): Unit = if (predicate()) GraphInterpreter.currentInterpreter.activeStage.completeStage() } - private object DoNothing extends (() ⇒ Unit) { + private object DoNothing extends (() => Unit) { def apply(): Unit = () } @@ -182,14 +182,14 @@ object GraphStageLogic { */ final class StageActor( materializer: ActorMaterializer, - getAsyncCallback: StageActorRef.Receive ⇒ AsyncCallback[(ActorRef, Any)], + getAsyncCallback: StageActorRef.Receive => AsyncCallback[(ActorRef, Any)], initialReceive: StageActorRef.Receive, name: String) { // not really needed, but let's keep MiMa happy def this( materializer: akka.stream.ActorMaterializer, - getAsyncCallback: StageActorRef.Receive ⇒ AsyncCallback[(ActorRef, Any)], + getAsyncCallback: StageActorRef.Receive => AsyncCallback[(ActorRef, Any)], initialReceive: StageActorRef.Receive ) { this(materializer, getAsyncCallback, initialReceive, "") @@ -197,18 +197,18 @@ object GraphStageLogic { private val callback = getAsyncCallback(internalReceive) private def cell = materializer.supervisor match { - case ref: LocalActorRef ⇒ ref.underlying - case ref: RepointableActorRef if ref.isStarted ⇒ ref.underlying.asInstanceOf[ActorCell] - case unknown ⇒ + case ref: LocalActorRef => ref.underlying + case ref: RepointableActorRef if ref.isStarted => ref.underlying.asInstanceOf[ActorCell] + case unknown => throw new IllegalStateException(s"Stream supervisor must be a local actor, was [${unknown.getClass.getName}]") } private val functionRef: FunctionRef = cell.addFunctionRef({ - case (_, m @ (PoisonPill | Kill)) ⇒ + case (_, m @ (PoisonPill | Kill)) => materializer.logger.warning("{} message sent to StageActor({}) will be ignored, since it is not a real Actor." + "Use a custom message type to communicate with it instead.", m, functionRef.path) - case pair ⇒ callback.invoke(pair) + case pair => callback.invoke(pair) }, name) /** @@ -224,12 +224,12 @@ object GraphStageLogic { /** INTERNAL API */ private[akka] def internalReceive(pack: (ActorRef, Any)): Unit = { pack._2 match { - case Terminated(ref) ⇒ + case Terminated(ref) => if (functionRef.isWatching(ref)) { functionRef.unwatch(ref) behavior(pack) } - case _ ⇒ behavior(pack) + case _ => behavior(pack) } } @@ -248,7 +248,7 @@ object GraphStageLogic { def unwatch(actorRef: ActorRef): Unit = functionRef.unwatch(actorRef) } object StageActorRef { - type Receive = ((ActorRef, Any)) ⇒ Unit + type Receive = ((ActorRef, Any)) => Unit } /** @@ -377,7 +377,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * Input handler that terminates the state upon receiving completion if the * given condition holds at that time. The operator fails upon receiving a failure. */ - final protected def conditionalTerminateInput(predicate: () ⇒ Boolean): InHandler = new ConditionalTerminateInput(predicate) + final protected def conditionalTerminateInput(predicate: () => Boolean): InHandler = new ConditionalTerminateInput(predicate) /** * Input handler that does not terminate the operator upon receiving completion * nor failure. @@ -398,7 +398,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * Output handler that terminates the state upon receiving completion if the * given condition holds at that time. The operator fails upon receiving a failure. */ - final protected def conditionalTerminateOutput(predicate: () ⇒ Boolean): OutHandler = new ConditionalTerminateOutput(predicate) + final protected def conditionalTerminateOutput(predicate: () => Boolean): OutHandler = new ConditionalTerminateOutput(predicate) /** * Assigns callbacks for the events for an [[Inlet]] @@ -443,8 +443,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: private def getNonEmittingHandler(out: Outlet[_]): OutHandler = getHandler(out) match { - case e: Emitting[_] ⇒ e.previous - case other ⇒ other + case e: Emitting[_] => e.previous + case other => other } /** @@ -532,8 +532,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: // Slow path on failure if ((connection.portState & (InReady | InFailed)) == (InReady | InFailed)) { connection.slot match { - case Failed(_, elem) ⇒ elem.asInstanceOf[AnyRef] ne Empty - case _ ⇒ false // This can only be Empty actually (if a cancel was concurrent with a failure) + case Failed(_, elem) => elem.asInstanceOf[AnyRef] ne Empty + case _ => false // This can only be Empty actually (if a cancel was concurrent with a failure) } } else false } @@ -588,8 +588,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: */ final protected def complete[T](out: Outlet[T]): Unit = getHandler(out) match { - case e: Emitting[_] ⇒ e.addFollowUp(new EmittingCompletion(e.out, e.previous)) - case _ ⇒ interpreter.complete(conn(out)) + case e: Emitting[_] => e.addFollowUp(new EmittingCompletion(e.out, e.previous)) + case _ => interpreter.complete(conn(out)) } /** @@ -607,8 +607,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: if (i < inCount) interpreter.cancel(portToConn(i)) else handlers(i) match { - case e: Emitting[_] ⇒ e.addFollowUp(new EmittingCompletion(e.out, e.previous)) - case _ ⇒ interpreter.complete(portToConn(i)) + case e: Emitting[_] => e.addFollowUp(new EmittingCompletion(e.out, e.previous)) + case _ => interpreter.complete(portToConn(i)) } i += 1 } @@ -651,7 +651,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * If upstream closes before N elements have been read, * the `onClose` function is invoked with the elements which were read. */ - final protected def readN[T](in: Inlet[T], n: Int)(andThen: Seq[T] ⇒ Unit, onClose: Seq[T] ⇒ Unit): Unit = + final protected def readN[T](in: Inlet[T], n: Int)(andThen: Seq[T] => Unit, onClose: Seq[T] => Unit): Unit = //FIXME `onClose` is a poor name for `onComplete` rename this at the earliest possible opportunity if (n < 0) throw new IllegalArgumentException("cannot read negative number of elements") else if (n == 0) andThen(Nil) @@ -668,12 +668,12 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: requireNotReading(in) if (!hasBeenPulled(in)) pull(in) setHandler(in, new Reading(in, n - pos, getHandler(in))( - (elem: T) ⇒ { + (elem: T) => { result(pos) = elem pos += 1 if (pos == n) andThen(result) }, - () ⇒ onClose(result.take(pos)))) + () => onClose(result.take(pos)))) } else andThen(result) } @@ -686,7 +686,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: final protected def readN[T](in: Inlet[T], n: Int, andThen: Procedure[java.util.List[T]], onClose: Procedure[java.util.List[T]]): Unit = { //FIXME `onClose` is a poor name for `onComplete` rename this at the earliest possible opportunity import collection.JavaConverters._ - readN(in, n)(seq ⇒ andThen(seq.asJava), seq ⇒ onClose(seq.asJava)) + readN(in, n)(seq => andThen(seq.asJava), seq => onClose(seq.asJava)) } /** @@ -695,7 +695,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * for the given inlet if suspension is needed and reinstalls the current * handler upon receiving the `onPush()` signal (before invoking the `andThen` function). */ - final protected def read[T](in: Inlet[T])(andThen: T ⇒ Unit, onClose: () ⇒ Unit): Unit = { + final protected def read[T](in: Inlet[T])(andThen: T => Unit, onClose: () => Unit): Unit = { if (isAvailable(in)) { val elem = grab(in) andThen(elem) @@ -725,9 +725,9 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: */ final protected def abortReading(in: Inlet[_]): Unit = getHandler(in) match { - case r: Reading[_] ⇒ + case r: Reading[_] => setHandler(in, r.previous) - case _ ⇒ + case _ => } private def requireNotReading(in: Inlet[_]): Unit = @@ -738,7 +738,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * Caution: for n == 1 andThen is called after resetting the handler, for * other values it is called without resetting the handler. n MUST be positive. */ - private final class Reading[T](in: Inlet[T], private var n: Int, val previous: InHandler)(andThen: T ⇒ Unit, onComplete: () ⇒ Unit) extends InHandler { + private final class Reading[T](in: Inlet[T], private var n: Int, val previous: InHandler)(andThen: T => Unit, onComplete: () => Unit) extends InHandler { require(n > 0, "number of elements to read must be positive!") override def onPush(): Unit = { @@ -770,7 +770,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * is needed and reinstalls the current handler upon receiving an `onPull()` * signal (before invoking the `andThen` function). */ - final protected def emitMultiple[T](out: Outlet[T], elems: immutable.Iterable[T], andThen: () ⇒ Unit): Unit = + final protected def emitMultiple[T](out: Outlet[T], elems: immutable.Iterable[T], andThen: () => Unit): Unit = emitMultiple(out, elems.iterator, andThen) /** @@ -814,7 +814,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * is needed and reinstalls the current handler upon receiving an `onPull()` * signal (before invoking the `andThen` function). */ - final protected def emitMultiple[T](out: Outlet[T], elems: Iterator[T], andThen: () ⇒ Unit): Unit = + final protected def emitMultiple[T](out: Outlet[T], elems: Iterator[T], andThen: () => Unit): Unit = if (elems.hasNext) { if (isAvailable(out)) { push(out, elems.next()) @@ -841,7 +841,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * is needed and reinstalls the current handler upon receiving an `onPull()` * signal (before invoking the `andThen` function). */ - final protected def emit[T](out: Outlet[T], elem: T, andThen: () ⇒ Unit): Unit = + final protected def emit[T](out: Outlet[T], elem: T, andThen: () => Unit): Unit = if (isAvailable(out)) { push(out, elem) andThen() @@ -868,17 +868,17 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: */ final protected def abortEmitting(out: Outlet[_]): Unit = getHandler(out) match { - case e: Emitting[_] ⇒ setHandler(out, e.previous) - case _ ⇒ + case e: Emitting[_] => setHandler(out, e.previous) + case _ => } private def setOrAddEmitting[T](out: Outlet[T], next: Emitting[T]): Unit = getHandler(out) match { - case e: Emitting[_] ⇒ e.asInstanceOf[Emitting[T]].addFollowUp(next) - case _ ⇒ setHandler(out, next) + case e: Emitting[_] => e.asInstanceOf[Emitting[T]].addFollowUp(next) + case _ => setHandler(out, next) } - private abstract class Emitting[T](val out: Outlet[T], val previous: OutHandler, andThen: () ⇒ Unit) extends OutHandler { + private abstract class Emitting[T](val out: Outlet[T], val previous: OutHandler, andThen: () => Unit) extends OutHandler { private var followUps: Emitting[T] = _ private var followUpsTail: Emitting[T] = _ private def as[U] = this.asInstanceOf[Emitting[U]] @@ -952,7 +952,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: override def onDownstreamFinish(): Unit = previous.onDownstreamFinish() } - private class EmittingSingle[T](_out: Outlet[T], elem: T, _previous: OutHandler, _andThen: () ⇒ Unit) + private class EmittingSingle[T](_out: Outlet[T], elem: T, _previous: OutHandler, _andThen: () => Unit) extends Emitting(_out, _previous, _andThen) { override def onPull(): Unit = { @@ -961,7 +961,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: } } - private class EmittingIterator[T](_out: Outlet[T], elems: Iterator[T], _previous: OutHandler, _andThen: () ⇒ Unit) + private class EmittingIterator[T](_out: Outlet[T], elems: Iterator[T], _previous: OutHandler, _andThen: () => Unit) extends Emitting(_out, _previous, _andThen) { override def onPull(): Unit = { @@ -985,7 +985,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: final protected def passAlong[Out, In <: Out](from: Inlet[In], to: Outlet[Out], doFinish: Boolean = true, doFail: Boolean = true, doPull: Boolean = false): Unit = { - class PassAlongHandler extends InHandler with (() ⇒ Unit) { + class PassAlongHandler extends InHandler with (() => Unit) { override def apply(): Unit = tryPull(from) override def onPush(): Unit = { @@ -1023,7 +1023,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * * This object can be cached and reused within the same [[GraphStageLogic]]. */ - final def getAsyncCallback[T](handler: T ⇒ Unit): AsyncCallback[T] = { + final def getAsyncCallback[T](handler: T => Unit): AsyncCallback[T] = { val callback = new ConcurrentAsyncCallback[T](handler) if (_interpreter != null) callback.onStart() else callbacksWaitingForInterpreter = callback :: callbacksWaitingForInterpreter @@ -1052,7 +1052,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * [[onStop()]] puts class in `Completed` state * "Real world" calls of [[invokeWithFeedback()]] always return failed promises for `Completed` state */ - private final class ConcurrentAsyncCallback[T](handler: T ⇒ Unit) extends AsyncCallback[T] { + private final class ConcurrentAsyncCallback[T](handler: T => Unit) extends AsyncCallback[T] { sealed trait State // waiting for materialization completion or during dispatching of initially queued events @@ -1070,8 +1070,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: private[stage] def onStart(): Unit = { // dispatch callbacks that have been queued before the interpreter was started (currentState.getAndSet(NoPendingEvents): @unchecked) match { - case Pending(l) ⇒ if (l.nonEmpty) l.reverse.foreach(evt ⇒ onAsyncInput(evt.e, evt.handlingPromise)) - case s ⇒ throw new IllegalStateException(s"Unexpected callback state [$s]") + case Pending(l) => if (l.nonEmpty) l.reverse.foreach(evt => onAsyncInput(evt.e, evt.handlingPromise)) + case s => throw new IllegalStateException(s"Unexpected callback state [$s]") } // in the meantime more callbacks might have been queued (we keep queueing them to ensure order) @@ -1112,18 +1112,18 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: @tailrec private def invokeWithPromise(event: T, promise: Promise[Done]): Unit = currentState.get() match { - case Initialized ⇒ + case Initialized => // started - can just dispatch async message to interpreter onAsyncInput(event, promise) - case list @ Pending(l) ⇒ + case list @ Pending(l) => // not started yet if (!currentState.compareAndSet(list, Pending(Event(event, promise) :: l))) invokeWithPromise(event, promise) } private def onAsyncInput(event: T, promise: Promise[Done]): Unit = - interpreter.onAsyncInput(GraphStageLogic.this, event, promise, handler.asInstanceOf[Any ⇒ Unit]) + interpreter.onAsyncInput(GraphStageLogic.this, event, promise, handler.asInstanceOf[Any => Unit]) } /** @@ -1147,8 +1147,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: private var _stageActor: StageActor = _ final def stageActor: StageActor = _stageActor match { - case null ⇒ throw StageActorRefNotInitializedException() - case ref ⇒ ref + case null => throw StageActorRefNotInitializedException() + case ref => ref } /** @@ -1170,13 +1170,13 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: */ // FIXME: I don't like the Pair allocation :( @ApiMayChange - final protected def getStageActor(receive: ((ActorRef, Any)) ⇒ Unit): StageActor = + final protected def getStageActor(receive: ((ActorRef, Any)) => Unit): StageActor = _stageActor match { - case null ⇒ + case null => val actorMaterializer = ActorMaterializerHelper.downcast(interpreter.materializer) _stageActor = new StageActor(actorMaterializer, getAsyncCallback, receive, stageActorName) _stageActor - case existing ⇒ + case existing => existing.become(receive) existing } @@ -1271,16 +1271,16 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: private var closed = false private var pulled = false - private val _sink = new SubSink[T](name, getAsyncCallback[ActorSubscriberMessage] { msg ⇒ + private val _sink = new SubSink[T](name, getAsyncCallback[ActorSubscriberMessage] { msg => if (!closed) msg match { - case OnNext(e) ⇒ + case OnNext(e) => elem = e.asInstanceOf[T] pulled = false handler.onPush() - case OnComplete ⇒ + case OnComplete => closed = true handler.onUpstreamFinish() - case OnError(ex) ⇒ + case OnError(ex) => closed = true handler.onUpstreamFailure(ex) } @@ -1336,12 +1336,12 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: private var closed = false private val callback = getAsyncCallback[SubSink.Command] { - case SubSink.RequestOne ⇒ + case SubSink.RequestOne => if (!closed) { available = true handler.onPull() } - case SubSink.Cancel ⇒ + case SubSink.Cancel => if (!closed) { available = false closed = true @@ -1466,10 +1466,10 @@ abstract class TimerGraphStageLogic(_shape: Shape) extends GraphStageLogic(_shap val Id = scheduled.timerId val timerKey = scheduled.timerKey keyToTimers.get(timerKey) match { - case Some(Timer(Id, _)) ⇒ + case Some(Timer(Id, _)) => if (!scheduled.repeating) keyToTimers -= timerKey onTimer(timerKey) - case _ ⇒ + case _ => } } @@ -1485,7 +1485,7 @@ abstract class TimerGraphStageLogic(_shape: Shape) extends GraphStageLogic(_shap protected[stream] override def afterPostStop(): Unit = { super.afterPostStop() if (keyToTimers ne null) { - keyToTimers.foreach { case (_, Timer(_, task)) ⇒ task.cancel() } + keyToTimers.foreach { case (_, Timer(_, task)) => task.cancel() } keyToTimers.clear() } } @@ -1552,7 +1552,7 @@ abstract class TimerGraphStageLogic(_shape: Shape) extends GraphStageLogic(_shap * @param timerKey key of the timer to cancel */ final protected def cancelTimer(timerKey: Any): Unit = - keyToTimers.get(timerKey).foreach { t ⇒ + keyToTimers.get(timerKey).foreach { t => t.task.cancel() keyToTimers -= timerKey } diff --git a/akka-stream/src/main/scala/akka/stream/stage/StageLogging.scala b/akka-stream/src/main/scala/akka/stream/stage/StageLogging.scala index 94a2f421e2..830030e087 100644 --- a/akka-stream/src/main/scala/akka/stream/stage/StageLogging.scala +++ b/akka-stream/src/main/scala/akka/stream/stage/StageLogging.scala @@ -18,7 +18,7 @@ import akka.stream.MaterializerLoggingProvider * itself would not know if you're calling it from a "on element" context or not, which is why * these decisions have to be handled by the operator itself. */ -trait StageLogging { self: GraphStageLogic ⇒ +trait StageLogging { self: GraphStageLogic => private[this] var _log: LoggingAdapter = _ /** Override to customise reported log source */ @@ -28,9 +28,9 @@ trait StageLogging { self: GraphStageLogic ⇒ // only used in StageLogic, i.e. thread safe if (_log eq null) { materializer match { - case p: MaterializerLoggingProvider ⇒ + case p: MaterializerLoggingProvider => _log = p.makeLogger(logSource) - case _ ⇒ + case _ => _log = NoLogging } } diff --git a/akka-stream/src/main/scala/com/typesafe/sslconfig/akka/AkkaSSLConfig.scala b/akka-stream/src/main/scala/com/typesafe/sslconfig/akka/AkkaSSLConfig.scala index 95141777a7..b3367bd18a 100644 --- a/akka-stream/src/main/scala/com/typesafe/sslconfig/akka/AkkaSSLConfig.scala +++ b/akka-stream/src/main/scala/com/typesafe/sslconfig/akka/AkkaSSLConfig.scala @@ -52,7 +52,7 @@ final class AkkaSSLConfig(system: ExtendedActorSystem, val config: SSLConfigSett * Please note that the ActorSystem-wide extension always remains configured via typesafe config, * custom ones can be created for special-handling specific connections */ - def mapSettings(f: SSLConfigSettings ⇒ SSLConfigSettings): AkkaSSLConfig = + def mapSettings(f: SSLConfigSettings => SSLConfigSettings): AkkaSSLConfig = new AkkaSSLConfig(system, f(config)) /** @@ -114,7 +114,7 @@ final class AkkaSSLConfig(system: ExtendedActorSystem, val config: SSLConfigSett else config.hostnameVerifierClass.asInstanceOf[Class[HostnameVerifier]] val v = system.dynamicAccess.createInstanceFor[HostnameVerifier](clazz, Nil) - .orElse(system.dynamicAccess.createInstanceFor[HostnameVerifier](clazz, List(classOf[LoggerFactory] → mkLogger))) + .orElse(system.dynamicAccess.createInstanceFor[HostnameVerifier](clazz, List(classOf[LoggerFactory] -> mkLogger))) .getOrElse(throw new Exception("Unable to obtain hostname verifier for class: " + clazz)) log.debug("buildHostnameVerifier: created hostname verifier: {}", v) @@ -142,11 +142,11 @@ final class AkkaSSLConfig(system: ExtendedActorSystem, val config: SSLConfigSett val disabledKeyAlgorithms = sslConfig.disabledKeyAlgorithms.mkString(",") // TODO Sub optimal, we got a Seq... val constraints = AlgorithmConstraintsParser.parseAll(AlgorithmConstraintsParser.line, disabledKeyAlgorithms).get.toSet val algorithmChecker = new AlgorithmChecker(mkLogger, keyConstraints = constraints, signatureConstraints = Set()) - for (cert ← trustManager.getAcceptedIssuers) { + for (cert <- trustManager.getAcceptedIssuers) { try { algorithmChecker.checkKeyAlgorithms(cert) } catch { - case e: CertPathValidatorException ⇒ + case e: CertPathValidatorException => log.warning("You are using ssl-config.default=true and have a weak certificate in your default trust store! (You can modify akka.ssl-config.disabledKeyAlgorithms to remove this message.)", e) } } @@ -154,12 +154,12 @@ final class AkkaSSLConfig(system: ExtendedActorSystem, val config: SSLConfigSett def configureProtocols(existingProtocols: Array[String], sslConfig: SSLConfigSettings): Array[String] = { val definedProtocols = sslConfig.enabledProtocols match { - case Some(configuredProtocols) ⇒ + case Some(configuredProtocols) => // If we are given a specific list of protocols, then return it in exactly that order, // assuming that it's actually possible in the SSL context. configuredProtocols.filter(existingProtocols.contains).toArray - case None ⇒ + case None => // Otherwise, we return the default protocols in the given list. Protocols.recommendedProtocols.filter(existingProtocols.contains) } @@ -167,7 +167,7 @@ final class AkkaSSLConfig(system: ExtendedActorSystem, val config: SSLConfigSett val allowWeakProtocols = sslConfig.loose.allowWeakProtocols if (!allowWeakProtocols) { val deprecatedProtocols = Protocols.deprecatedProtocols - for (deprecatedProtocol ← deprecatedProtocols) { + for (deprecatedProtocol <- deprecatedProtocols) { if (definedProtocols.contains(deprecatedProtocol)) { throw new IllegalStateException(s"Weak protocol $deprecatedProtocol found in ssl-config.protocols!") } @@ -178,18 +178,18 @@ final class AkkaSSLConfig(system: ExtendedActorSystem, val config: SSLConfigSett def configureCipherSuites(existingCiphers: Array[String], sslConfig: SSLConfigSettings): Array[String] = { val definedCiphers = sslConfig.enabledCipherSuites match { - case Some(configuredCiphers) ⇒ + case Some(configuredCiphers) => // If we are given a specific list of ciphers, return it in that order. configuredCiphers.filter(existingCiphers.contains(_)).toArray - case None ⇒ + case None => Ciphers.recommendedCiphers.filter(existingCiphers.contains(_)).toArray } val allowWeakCiphers = sslConfig.loose.allowWeakCiphers if (!allowWeakCiphers) { val deprecatedCiphers = Ciphers.deprecatedCiphers - for (deprecatedCipher ← deprecatedCiphers) { + for (deprecatedCipher <- deprecatedCiphers) { if (definedCiphers.contains(deprecatedCipher)) { throw new IllegalStateException(s"Weak cipher $deprecatedCipher found in ssl-config.ciphers!") } diff --git a/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala b/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala index 660bd9e308..7fd6f82343 100644 --- a/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala +++ b/akka-testkit/src/main/scala/akka/testkit/CallingThreadDispatcher.scala @@ -51,18 +51,18 @@ private[testkit] class CallingThreadDispatcherQueues extends Extension { // we have to forget about long-gone threads sometime private def gc(): Unit = { queues = queues.foldLeft(Map.newBuilder[CallingThreadMailbox, Set[WeakReference[MessageQueue]]]) { - case (m, (k, v)) ⇒ + case (m, (k, v)) => val nv = v filter (_.get ne null) - if (nv.isEmpty) m else m += (k → nv) + if (nv.isEmpty) m else m += (k -> nv) }.result } protected[akka] def registerQueue(mbox: CallingThreadMailbox, q: MessageQueue): Unit = synchronized { if (queues contains mbox) { val newSet = queues(mbox) + new WeakReference(q) - queues += mbox → newSet + queues += mbox -> newSet } else { - queues += mbox → Set(new WeakReference(q)) + queues += mbox -> Set(new WeakReference(q)) } val now = System.nanoTime if (now - lastGC > 1000000000l) { @@ -83,7 +83,7 @@ private[testkit] class CallingThreadDispatcherQueues extends Extension { protected[akka] def gatherFromAllOtherQueues(mbox: CallingThreadMailbox, own: MessageQueue): Unit = synchronized { if (queues contains mbox) { for { - ref ← queues(mbox) + ref <- queues(mbox) q = ref.get if (q ne null) && (q ne own) } { @@ -148,17 +148,17 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte protected[akka] override def register(actor: ActorCell): Unit = { super.register(actor) actor.mailbox match { - case mbox: CallingThreadMailbox ⇒ + case mbox: CallingThreadMailbox => val queue = mbox.queue runQueue(mbox, queue) - case x ⇒ throw ActorInitializationException("expected CallingThreadMailbox, got " + x.getClass) + case x => throw ActorInitializationException("expected CallingThreadMailbox, got " + x.getClass) } } protected[akka] override def unregister(actor: ActorCell): Unit = { val mbox = actor.mailbox match { - case m: CallingThreadMailbox ⇒ Some(m) - case _ ⇒ None + case m: CallingThreadMailbox => Some(m) + case _ => None } super.unregister(actor) mbox foreach CallingThreadDispatcherQueues(actor.system).unregisterQueues @@ -166,14 +166,14 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte protected[akka] override def suspend(actor: ActorCell): Unit = { actor.mailbox match { - case m: CallingThreadMailbox ⇒ { m.suspendSwitch.switchOn; m.suspend() } - case m ⇒ m.systemEnqueue(actor.self, Suspend()) + case m: CallingThreadMailbox => { m.suspendSwitch.switchOn; m.suspend() } + case m => m.systemEnqueue(actor.self, Suspend()) } } protected[akka] override def resume(actor: ActorCell): Unit = { actor.mailbox match { - case mbox: CallingThreadMailbox ⇒ + case mbox: CallingThreadMailbox => val queue = mbox.queue val switched = mbox.suspendSwitch.switchOff { CallingThreadDispatcherQueues(actor.system).gatherFromAllOtherQueues(mbox, queue) @@ -181,22 +181,22 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte } if (switched) runQueue(mbox, queue) - case m ⇒ m.systemEnqueue(actor.self, Resume(causedByFailure = null)) + case m => m.systemEnqueue(actor.self, Resume(causedByFailure = null)) } } protected[akka] override def systemDispatch(receiver: ActorCell, message: SystemMessage): Unit = { receiver.mailbox match { - case mbox: CallingThreadMailbox ⇒ + case mbox: CallingThreadMailbox => mbox.systemEnqueue(receiver.self, message) runQueue(mbox, mbox.queue) - case m ⇒ m.systemEnqueue(receiver.self, message) + case m => m.systemEnqueue(receiver.self, message) } } protected[akka] override def dispatch(receiver: ActorCell, handle: Envelope): Unit = { receiver.mailbox match { - case mbox: CallingThreadMailbox ⇒ + case mbox: CallingThreadMailbox => val queue = mbox.queue val execute = mbox.suspendSwitch.fold { queue.enqueue(receiver.self, handle) @@ -206,7 +206,7 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte true } if (execute) runQueue(mbox, queue) - case m ⇒ m.enqueue(receiver.self, handle) + case m => m.enqueue(receiver.self, handle) } } @@ -252,12 +252,12 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte intex = checkThreadInterruption(intex) true } catch { - case ie: InterruptedException ⇒ + case ie: InterruptedException => log.error(ie, "Interrupted during message processing") Thread.interrupted() // clear interrupted flag before we continue, exception will be thrown later intex = ie true - case NonFatal(e) ⇒ + case NonFatal(e) => log.error(e, "Error during message processing") false } @@ -274,7 +274,7 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte val gotLock = try { mbox.ctdLock.tryLock(50, TimeUnit.MILLISECONDS) } catch { - case ie: InterruptedException ⇒ + case ie: InterruptedException => Thread.interrupted() // clear interrupted flag before we continue, exception will be thrown later intex = ie false diff --git a/akka-testkit/src/main/scala/akka/testkit/ExplicitlyTriggeredScheduler.scala b/akka-testkit/src/main/scala/akka/testkit/ExplicitlyTriggeredScheduler.scala index fd413cb694..97f2f7a95a 100644 --- a/akka-testkit/src/main/scala/akka/testkit/ExplicitlyTriggeredScheduler.scala +++ b/akka-testkit/src/main/scala/akka/testkit/ExplicitlyTriggeredScheduler.scala @@ -58,7 +58,7 @@ class ExplicitlyTriggeredScheduler(@unused config: Config, log: LoggingAdapter, val newTime = currentTime.get + amount.toMillis if (log.isDebugEnabled) - log.debug(s"Time proceeds from ${currentTime.get} to $newTime, currently scheduled for this period:" + scheduledTasks(newTime).map(item ⇒ s"\n- $item")) + log.debug(s"Time proceeds from ${currentTime.get} to $newTime, currently scheduled for this period:" + scheduledTasks(newTime).map(item => s"\n- $item")) executeTasks(newTime) currentTime.set(newTime) @@ -75,17 +75,17 @@ class ExplicitlyTriggeredScheduler(@unused config: Config, log: LoggingAdapter, @tailrec private[testkit] final def executeTasks(runTo: Long): Unit = { scheduledTasks(runTo).headOption match { - case Some(task) ⇒ + case Some(task) => currentTime.set(task.time) val runResult = Try(task.runnable.run()) scheduled.remove(task) if (runResult.isSuccess) - task.interval.foreach(i ⇒ scheduled.put(task.copy(time = task.time + i.toMillis), ())) + task.interval.foreach(i => scheduled.put(task.copy(time = task.time + i.toMillis), ())) // running the runnable might have scheduled new events executeTasks(runTo) - case _ ⇒ // Done + case _ => // Done } } diff --git a/akka-testkit/src/main/scala/akka/testkit/SocketUtil.scala b/akka-testkit/src/main/scala/akka/testkit/SocketUtil.scala index e6f600052d..0521067e04 100644 --- a/akka-testkit/src/main/scala/akka/testkit/SocketUtil.scala +++ b/akka-testkit/src/main/scala/akka/testkit/SocketUtil.scala @@ -24,7 +24,7 @@ object SocketUtil { SocketUtil.temporaryServerAddress(address = "127.20.0.0") true } catch { - case _: java.net.BindException ⇒ + case _: java.net.BindException => false } } @@ -52,16 +52,16 @@ object SocketUtil { ds.bind(new InetSocketAddress("localhost", tcpPort)) tcpPort } catch { - case NonFatal(_) ⇒ findBoth(tries - 1) + case NonFatal(_) => findBoth(tries - 1) } finally { ds.close() } } protocol match { - case Tcp ⇒ temporaryLocalPort(udp = false) - case Udp ⇒ temporaryLocalPort(udp = true) - case Both ⇒ findBoth(5) + case Tcp => temporaryLocalPort(udp = false) + case Udp => temporaryLocalPort(udp = true) + case Both => findBoth(5) } } @@ -77,10 +77,10 @@ object SocketUtil { Vector.fill(numberOfAddresses) { val address = hostname match { - case RANDOM_LOOPBACK_ADDRESS ⇒ + case RANDOM_LOOPBACK_ADDRESS => if (canBindOnAlternativeLoopbackAddresses) s"127.20.${Random.nextInt(256)}.${Random.nextInt(256)}" else "127.0.0.1" - case other ⇒ + case other => other } @@ -94,12 +94,12 @@ object SocketUtil { (ss, new InetSocketAddress(address, ss.getLocalPort)) } - } collect { case (socket, address) ⇒ socket.close(); address } + } collect { case (socket, address) => socket.close(); address } } def temporaryServerHostnameAndPort(interface: String = RANDOM_LOOPBACK_ADDRESS): (String, Int) = { val socketAddress = temporaryServerAddress(interface) - socketAddress.getHostString → socketAddress.getPort + socketAddress.getHostString -> socketAddress.getPort } def temporaryUdpIpv6Port(iface: NetworkInterface) = { diff --git a/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala b/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala index 9b35984085..7bd908be68 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestActorRef.scala @@ -30,13 +30,13 @@ class TestActorRef[T <: Actor]( else _props.dispatcher) val dispatcher = _system.dispatchers.lookup(props.dispatcher) private val disregard = _supervisor match { - case l: LocalActorRef ⇒ l.underlying.reserveChild(name) - case r: RepointableActorRef ⇒ r.underlying match { - case _: UnstartedCell ⇒ throw new IllegalStateException("cannot attach a TestActor to an unstarted top-level actor, ensure that it is started by sending a message and observing the reply") - case c: ActorCell ⇒ c.reserveChild(name) - case o ⇒ _system.log.error("trying to attach child {} to unknown type of supervisor cell {}, this is not going to end well", name, o.getClass) + case l: LocalActorRef => l.underlying.reserveChild(name) + case r: RepointableActorRef => r.underlying match { + case _: UnstartedCell => throw new IllegalStateException("cannot attach a TestActor to an unstarted top-level actor, ensure that it is started by sending a message and observing the reply") + case c: ActorCell => c.reserveChild(name) + case o => _system.log.error("trying to attach child {} to unknown type of supervisor cell {}, this is not going to end well", name, o.getClass) } - case s ⇒ _system.log.error("trying to attach child {} to unknown type of supervisor {}, this is not going to end well", name, s.getClass) + case s => _system.log.error("trying to attach child {} to unknown type of supervisor {}, this is not going to end well", name, s.getClass) } } with LocalActorRef( _system.asInstanceOf[ActorSystemImpl], @@ -56,8 +56,8 @@ class TestActorRef[T <: Actor]( new ActorCell(system, ref, props, dispatcher, supervisor) { override def autoReceiveMessage(msg: Envelope): Unit = { msg.message match { - case InternalGetActor ⇒ sender() ! actor - case _ ⇒ super.autoReceiveMessage(msg) + case InternalGetActor => sender() ! actor + case _ => super.autoReceiveMessage(msg) } } } @@ -88,10 +88,10 @@ class TestActorRef[T <: Actor]( // volatile mailbox read to bring in actor field if (isTerminated) throw IllegalActorStateException("underlying actor is terminated") underlying.actor.asInstanceOf[T] match { - case null ⇒ + case null => val t = TestKitExtension(_system).DefaultTimeout Await.result(this.?(InternalGetActor)(t), t.duration).asInstanceOf[T] - case ref ⇒ ref + case ref => ref } } @@ -127,9 +127,9 @@ object TestActorRef { "$" + akka.util.Helpers.base64(l) } - def apply[T <: Actor: ClassTag](factory: ⇒ T)(implicit system: ActorSystem): TestActorRef[T] = apply[T](Props(factory), randomName) + def apply[T <: Actor: ClassTag](factory: => T)(implicit system: ActorSystem): TestActorRef[T] = apply[T](Props(factory), randomName) - def apply[T <: Actor: ClassTag](factory: ⇒ T, name: String)(implicit system: ActorSystem): TestActorRef[T] = apply[T](Props(factory), name) + def apply[T <: Actor: ClassTag](factory: => T, name: String)(implicit system: ActorSystem): TestActorRef[T] = apply[T](Props(factory), name) def apply[T <: Actor](props: Props)(implicit system: ActorSystem): TestActorRef[T] = apply[T](props, randomName) @@ -149,7 +149,7 @@ object TestActorRef { def apply[T <: Actor](implicit t: ClassTag[T], system: ActorSystem): TestActorRef[T] = apply[T](randomName) private def dynamicCreateRecover[U]: PartialFunction[Throwable, U] = { - case exception ⇒ throw ActorInitializationException( + case exception => throw ActorInitializationException( null, "Could not instantiate Actor" + "\nMake sure Actor is NOT defined inside a class/trait," + diff --git a/akka-testkit/src/main/scala/akka/testkit/TestActors.scala b/akka-testkit/src/main/scala/akka/testkit/TestActors.scala index 6cadb05822..087b391085 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestActors.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestActors.scala @@ -16,7 +16,7 @@ object TestActors { */ class EchoActor extends Actor { override def receive = { - case message ⇒ sender() ! message + case message => sender() ! message } } @@ -25,7 +25,7 @@ object TestActors { */ class BlackholeActor extends Actor { override def receive = { - case _ ⇒ // ignore... + case _ => // ignore... } } @@ -36,7 +36,7 @@ object TestActors { */ class ForwardActor(ref: ActorRef) extends Actor { override def receive = { - case message ⇒ ref forward message + case message => ref forward message } } diff --git a/akka-testkit/src/main/scala/akka/testkit/TestBarrier.scala b/akka-testkit/src/main/scala/akka/testkit/TestBarrier.scala index 2d26477581..cbc91dc02e 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestBarrier.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestBarrier.scala @@ -32,7 +32,7 @@ class TestBarrier(count: Int) { try { barrier.await(timeout.dilated.toNanos, TimeUnit.NANOSECONDS) } catch { - case _: TimeoutException ⇒ + case _: TimeoutException => throw new TestBarrierTimeoutException("Timeout of %s and time factor of %s" format (timeout.toString, TestKitExtension(system).TestTimeFactor)) } diff --git a/akka-testkit/src/main/scala/akka/testkit/TestEventListener.scala b/akka-testkit/src/main/scala/akka/testkit/TestEventListener.scala index 4018732445..2e923596d0 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestEventListener.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestEventListener.scala @@ -14,7 +14,7 @@ import akka.event.Logging.{ Warning, LogEvent, InitializeLogger, Info, Error, De import akka.event.Logging import akka.actor.NoSerializationVerificationNeeded import akka.japi.Util.immutableSeq -import java.lang.{ Iterable ⇒ JIterable } +import java.lang.{ Iterable => JIterable } import akka.util.BoxedType import akka.util.ccompat._ @@ -105,7 +105,7 @@ abstract class EventFilter(occurrences: Int) { * Apply this filter while executing the given code block. Care is taken to * remove the filter when the block is finished or aborted. */ - def intercept[T](code: ⇒ T)(implicit system: ActorSystem): T = { + def intercept[T](code: => T)(implicit system: ActorSystem): T = { system.eventStream publish TestEvent.Mute(this) val leeway = TestKitExtension(system).TestEventFilterLeeway.dilated try { @@ -132,8 +132,8 @@ abstract class EventFilter(occurrences: Int) { val msgstr = if (msg != null) msg.toString else "null" (source.isDefined && source.get == src || source.isEmpty) && (message match { - case Left(s) ⇒ if (complete) msgstr == s else msgstr.startsWith(s) - case Right(p) ⇒ p.findFirstIn(msgstr).isDefined + case Left(s) => if (complete) msgstr == s else msgstr.startsWith(s) + case Right(p) => p.findFirstIn(msgstr).isDefined }) } } @@ -282,10 +282,10 @@ final case class ErrorFilter( def matches(event: LogEvent) = { event match { - case Error(cause, src, _, msg) if (throwable eq Error.NoCause.getClass) || (throwable isInstance cause) ⇒ + case Error(cause, src, _, msg) if (throwable eq Error.NoCause.getClass) || (throwable isInstance cause) => (msg == null && cause.getMessage == null && cause.getStackTrace.length == 0) || doMatch(src, msg) || doMatch(src, cause.getMessage) - case _ ⇒ false + case _ => false } } @@ -333,8 +333,8 @@ final case class WarningFilter( def matches(event: LogEvent) = { event match { - case Warning(src, _, msg) ⇒ doMatch(src, msg) - case _ ⇒ false + case Warning(src, _, msg) => doMatch(src, msg) + case _ => false } } @@ -377,8 +377,8 @@ final case class InfoFilter( def matches(event: LogEvent) = { event match { - case Info(src, _, msg) ⇒ doMatch(src, msg) - case _ ⇒ false + case Info(src, _, msg) => doMatch(src, msg) + case _ => false } } @@ -421,8 +421,8 @@ final case class DebugFilter( def matches(event: LogEvent) = { event match { - case Debug(src, _, msg) ⇒ doMatch(src, msg) - case _ ⇒ false + case Debug(src, _, msg) => doMatch(src, msg) + case _ => false } } @@ -473,8 +473,8 @@ final case class DeadLettersFilter(val messageClass: Class[_])(occurrences: Int) def matches(event: LogEvent) = { event match { - case Warning(_, _, msg) ⇒ BoxedType(messageClass) isInstance msg - case _ ⇒ false + case Warning(_, _, msg) => BoxedType(messageClass) isInstance msg + case _ => false } } @@ -498,13 +498,13 @@ class TestEventListener extends Logging.DefaultLogger { var filters: List[EventFilter] = Nil override def receive = { - case InitializeLogger(bus) ⇒ + case InitializeLogger(bus) => Seq(classOf[Mute], classOf[UnMute], classOf[DeadLetter], classOf[UnhandledMessage]) foreach (bus.subscribe(context.self, _)) sender() ! LoggerInitialized - case Mute(filters) ⇒ filters foreach addFilter - case UnMute(filters) ⇒ filters foreach removeFilter - case event: LogEvent ⇒ if (!filter(event)) print(event) - case DeadLetter(msg, snd, rcp) ⇒ + case Mute(filters) => filters foreach addFilter + case UnMute(filters) => filters foreach removeFilter + case event: LogEvent => if (!filter(event)) print(event) + case DeadLetter(msg, snd, rcp) => if (!msg.isInstanceOf[Terminate]) { val event = Warning(rcp.path.toString, rcp.getClass, msg) if (!filter(event)) { @@ -516,22 +516,22 @@ class TestEventListener extends Logging.DefaultLogger { if (!filter(event2)) print(event2) } } - case UnhandledMessage(msg, sender, rcp) ⇒ + case UnhandledMessage(msg, sender, rcp) => val event = Warning(rcp.path.toString, rcp.getClass, "unhandled message from " + sender + ": " + msg) if (!filter(event)) print(event) - case m ⇒ print(Debug(context.system.name, this.getClass, m)) + case m => print(Debug(context.system.name, this.getClass, m)) } - def filter(event: LogEvent): Boolean = filters exists (f ⇒ try { f(event) } catch { case _: Exception ⇒ false }) + def filter(event: LogEvent): Boolean = filters exists (f => try { f(event) } catch { case _: Exception => false }) def addFilter(filter: EventFilter): Unit = filters ::= filter def removeFilter(filter: EventFilter): Unit = { @scala.annotation.tailrec def removeFirst(list: List[EventFilter], zipped: List[EventFilter] = Nil): List[EventFilter] = list match { - case head :: tail if head == filter ⇒ tail.reverse_:::(zipped) - case head :: tail ⇒ removeFirst(tail, head :: zipped) - case Nil ⇒ filters // filter not found, just return original list + case head :: tail if head == filter => tail.reverse_:::(zipped) + case head :: tail => removeFirst(tail, head :: zipped) + case Nil => filters // filter not found, just return original list } filters = removeFirst(filters) } diff --git a/akka-testkit/src/main/scala/akka/testkit/TestFSMRef.scala b/akka-testkit/src/main/scala/akka/testkit/TestFSMRef.scala index 464822c570..1f69ebdf97 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestFSMRef.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestFSMRef.scala @@ -86,22 +86,22 @@ class TestFSMRef[S, D, T <: Actor]( object TestFSMRef { - def apply[S, D, T <: Actor: ClassTag](factory: ⇒ T)(implicit ev: T <:< FSM[S, D], system: ActorSystem): TestFSMRef[S, D, T] = { + def apply[S, D, T <: Actor: ClassTag](factory: => T)(implicit ev: T <:< FSM[S, D], system: ActorSystem): TestFSMRef[S, D, T] = { val impl = system.asInstanceOf[ActorSystemImpl] new TestFSMRef(impl, Props(factory), impl.guardian.asInstanceOf[InternalActorRef], TestActorRef.randomName) } - def apply[S, D, T <: Actor: ClassTag](factory: ⇒ T, name: String)(implicit ev: T <:< FSM[S, D], system: ActorSystem): TestFSMRef[S, D, T] = { + def apply[S, D, T <: Actor: ClassTag](factory: => T, name: String)(implicit ev: T <:< FSM[S, D], system: ActorSystem): TestFSMRef[S, D, T] = { val impl = system.asInstanceOf[ActorSystemImpl] new TestFSMRef(impl, Props(factory), impl.guardian.asInstanceOf[InternalActorRef], name) } - def apply[S, D, T <: Actor: ClassTag](factory: ⇒ T, supervisor: ActorRef, name: String)(implicit ev: T <:< FSM[S, D], system: ActorSystem): TestFSMRef[S, D, T] = { + def apply[S, D, T <: Actor: ClassTag](factory: => T, supervisor: ActorRef, name: String)(implicit ev: T <:< FSM[S, D], system: ActorSystem): TestFSMRef[S, D, T] = { val impl = system.asInstanceOf[ActorSystemImpl] new TestFSMRef(impl, Props(factory), supervisor.asInstanceOf[InternalActorRef], name) } - def apply[S, D, T <: Actor: ClassTag](factory: ⇒ T, supervisor: ActorRef)(implicit ev: T <:< FSM[S, D], system: ActorSystem): TestFSMRef[S, D, T] = { + def apply[S, D, T <: Actor: ClassTag](factory: => T, supervisor: ActorRef)(implicit ev: T <:< FSM[S, D], system: ActorSystem): TestFSMRef[S, D, T] = { val impl = system.asInstanceOf[ActorSystemImpl] new TestFSMRef(impl, Props(factory), supervisor.asInstanceOf[InternalActorRef], TestActorRef.randomName) } diff --git a/akka-testkit/src/main/scala/akka/testkit/TestKit.scala b/akka-testkit/src/main/scala/akka/testkit/TestKit.scala index d1fa2a706e..2d7292351d 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestKit.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestKit.scala @@ -47,8 +47,8 @@ object TestActor { final case class SetAutoPilot(ap: AutoPilot) extends NoSerializationVerificationNeeded final case class Spawn(props: Props, name: Option[String] = None, strategy: Option[SupervisorStrategy] = None) extends NoSerializationVerificationNeeded { def apply(context: ActorRefFactory): ActorRef = name match { - case Some(n) ⇒ context.actorOf(props, n) - case None ⇒ context.actorOf(props) + case Some(n) => context.actorOf(props, n) + case None => context.actorOf(props) } } @@ -62,7 +62,7 @@ object TestActor { override def sender: ActorRef = throw IllegalActorStateException("last receive did not dequeue a message") } - val FALSE = (_: Any) ⇒ false + val FALSE = (_: Any) => false /** INTERNAL API */ private[TestActor] class DelegatingSupervisorStrategy extends SupervisorStrategy { @@ -72,7 +72,7 @@ object TestActor { private def delegate(child: ActorRef) = delegates.get(child).getOrElse(stoppingStrategy) - def update(child: ActorRef, supervisor: SupervisorStrategy): Unit = delegates += (child → supervisor) + def update(child: ActorRef, supervisor: SupervisorStrategy): Unit = delegates += (child -> supervisor) override def decider = defaultDecider // not actually invoked @@ -103,26 +103,26 @@ class TestActor(queue: BlockingDeque[TestActor.Message]) extends Actor { var autopilot: AutoPilot = NoAutoPilot def receive = { - case SetIgnore(ign) ⇒ ignore = ign - case Watch(ref) ⇒ context.watch(ref) - case UnWatch(ref) ⇒ context.unwatch(ref) - case SetAutoPilot(pilot) ⇒ autopilot = pilot - case spawn: Spawn ⇒ + case SetIgnore(ign) => ignore = ign + case Watch(ref) => context.watch(ref) + case UnWatch(ref) => context.unwatch(ref) + case SetAutoPilot(pilot) => autopilot = pilot + case spawn: Spawn => val actor = spawn(context) - for (s ← spawn.strategy) supervisorStrategy(actor) = s + for (s <- spawn.strategy) supervisorStrategy(actor) = s queue.offerLast(RealMessage(actor, self)) - case x: AnyRef ⇒ + case x: AnyRef => autopilot = autopilot.run(sender(), x) match { - case KeepRunning ⇒ autopilot - case other ⇒ other + case KeepRunning => autopilot + case other => other } - val observe = ignore map (ignoreFunc ⇒ !ignoreFunc.applyOrElse(x, FALSE)) getOrElse true + val observe = ignore map (ignoreFunc => !ignoreFunc.applyOrElse(x, FALSE)) getOrElse true if (observe) queue.offerLast(RealMessage(x, sender())) } override def postStop() = { import scala.collection.JavaConverters._ - queue.asScala foreach { m ⇒ context.system.deadLetters.tell(DeadLetter(m.msg, m.sender, self), m.sender) } + queue.asScala foreach { m => context.system.deadLetters.tell(DeadLetter(m.msg, m.sender, self), m.sender) } } } @@ -169,8 +169,8 @@ trait TestKitBase { .withDispatcher(CallingThreadDispatcher.Id), "%s-%d".format(testActorName, TestKit.testActorId.incrementAndGet)) awaitCond(ref match { - case r: RepointableRef ⇒ r.isStarted - case _ ⇒ true + case r: RepointableRef => r.isStarted + case _ => true }, 3.seconds.dilated, 10.millis) ref } @@ -235,8 +235,8 @@ trait TestKitBase { * call. */ def remaining: FiniteDuration = end match { - case f: FiniteDuration ⇒ f - now - case _ ⇒ throw new AssertionError("`remaining` may not be called outside of `within`") + case f: FiniteDuration => f - now + case _ => throw new AssertionError("`remaining` may not be called outside of `within`") } /** @@ -244,15 +244,15 @@ trait TestKitBase { * block or missing that it returns the given duration. */ def remainingOr(duration: FiniteDuration): FiniteDuration = end match { - case x if x eq Duration.Undefined ⇒ duration - case x if !x.isFinite ⇒ throw new IllegalArgumentException("`end` cannot be infinite") - case f: FiniteDuration ⇒ f - now + case x if x eq Duration.Undefined => duration + case x if !x.isFinite => throw new IllegalArgumentException("`end` cannot be infinite") + case f: FiniteDuration => f - now } private def remainingOrDilated(max: Duration): FiniteDuration = max match { - case x if x eq Duration.Undefined ⇒ remainingOrDefault - case x if !x.isFinite ⇒ throw new IllegalArgumentException("max duration cannot be infinite") - case f: FiniteDuration ⇒ f.dilated + case x if x eq Duration.Undefined => remainingOrDefault + case x if !x.isFinite => throw new IllegalArgumentException("max duration cannot be infinite") + case f: FiniteDuration => f.dilated } /** @@ -270,7 +270,7 @@ trait TestKitBase { * Note that the timeout is scaled using Duration.dilated, * which uses the configuration entry "akka.test.timefactor". */ - def awaitCond(p: ⇒ Boolean, max: Duration = Duration.Undefined, interval: Duration = 100.millis, message: String = ""): Unit = { + def awaitCond(p: => Boolean, max: Duration = Duration.Undefined, interval: Duration = 100.millis, message: String = ""): Unit = { val _max = remainingOrDilated(max) val stop = now + _max @@ -298,7 +298,7 @@ trait TestKitBase { * Note that the timeout is scaled using Duration.dilated, * which uses the configuration entry "akka.test.timefactor". */ - def awaitAssert[A](a: ⇒ A, max: Duration = Duration.Undefined, interval: Duration = 100.millis): A = { + def awaitAssert[A](a: => A, max: Duration = Duration.Undefined, interval: Duration = 100.millis): A = { val _max = remainingOrDilated(max) val stop = now + _max @@ -313,7 +313,7 @@ trait TestKitBase { failed = false aRes } catch { - case NonFatal(e) ⇒ + case NonFatal(e) => failed = true if ((now + t) >= stop) throw e else null.asInstanceOf[A] @@ -345,7 +345,7 @@ trait TestKitBase { * } * }}} */ - def within[T](min: FiniteDuration, max: FiniteDuration)(f: ⇒ T): T = { + def within[T](min: FiniteDuration, max: FiniteDuration)(f: => T): T = { val _max = max.dilated val start = now val rem = if (end == Duration.Undefined) Duration.Inf else end - start @@ -371,7 +371,7 @@ trait TestKitBase { /** * Same as calling `within(0 seconds, max)(f)`. */ - def within[T](max: FiniteDuration)(f: ⇒ T): T = within(0 seconds, max)(f) + def within[T](max: FiniteDuration)(f: => T): T = within(0 seconds, max)(f) /** * Same as `expectMsg(remainingOrDefault, obj)`, but correctly treating the timeFactor. @@ -433,7 +433,7 @@ trait TestKitBase { */ def expectTerminated(target: ActorRef, max: Duration = Duration.Undefined): Terminated = expectMsgPF(max, "Terminated " + target) { - case t @ Terminated(`target`) ⇒ t + case t @ Terminated(`target`) => t } /** @@ -549,7 +549,7 @@ trait TestKitBase { private def expectMsgAnyClassOf_internal[C](max: FiniteDuration, obj: Class[_ <: C]*): C = { val o = receiveOne(max) assert(o ne null, s"timeout ($max) during expectMsgAnyClassOf waiting for ${obj.mkString("(", ", ", ")")}") - assert(obj exists (c ⇒ BoxedType(c) isInstance o), s"found unexpected $o") + assert(obj exists (c => BoxedType(c) isInstance o), s"found unexpected $o") o.asInstanceOf[C] } @@ -583,8 +583,8 @@ trait TestKitBase { private def expectMsgAllOf_internal[T](max: FiniteDuration, obj: T*): immutable.Seq[T] = { val recv = receiveN_internal(obj.size, max) - val missing = obj filterNot (x ⇒ recv exists (x == _)) - val unexpected = recv filterNot (x ⇒ obj exists (x == _)) + val missing = obj filterNot (x => recv exists (x == _)) + val unexpected = recv filterNot (x => obj exists (x == _)) checkMissingAndUnexpected(missing, unexpected, "not found", "found unexpected") recv.asInstanceOf[immutable.Seq[T]] } @@ -606,8 +606,8 @@ trait TestKitBase { private def internalExpectMsgAllClassOf[T](max: FiniteDuration, obj: Class[_ <: T]*): immutable.Seq[T] = { val recv = receiveN_internal(obj.size, max) - val missing = obj filterNot (x ⇒ recv exists (_.getClass eq BoxedType(x))) - val unexpected = recv filterNot (x ⇒ obj exists (c ⇒ BoxedType(c) eq x.getClass)) + val missing = obj filterNot (x => recv exists (_.getClass eq BoxedType(x))) + val unexpected = recv filterNot (x => obj exists (c => BoxedType(c) eq x.getClass)) checkMissingAndUnexpected(missing, unexpected, "not found", "found non-matching object(s)") recv.asInstanceOf[immutable.Seq[T]] } @@ -632,8 +632,8 @@ trait TestKitBase { private def internalExpectMsgAllConformingOf[T](max: FiniteDuration, obj: Class[_ <: T]*): immutable.Seq[T] = { val recv = receiveN_internal(obj.size, max) - val missing = obj filterNot (x ⇒ recv exists (BoxedType(x) isInstance _)) - val unexpected = recv filterNot (x ⇒ obj exists (c ⇒ BoxedType(c) isInstance x)) + val missing = obj filterNot (x => recv exists (BoxedType(x) isInstance _)) + val unexpected = recv filterNot (x => obj exists (c => BoxedType(c) isInstance x)) checkMissingAndUnexpected(missing, unexpected, "not found", "found non-matching object(s)") recv.asInstanceOf[immutable.Seq[T]] } @@ -728,13 +728,13 @@ trait TestKitBase { else { receiveOne((stop - now) min idle) lastMessage match { - case NullMessage ⇒ + case NullMessage => lastMessage = msg acc.reverse - case RealMessage(o, _) if (f isDefinedAt o) ⇒ + case RealMessage(o, _) if (f isDefinedAt o) => msg = lastMessage doit(f(o) :: acc, count + 1) - case RealMessage(_, _) ⇒ + case RealMessage(_, _) => queue.offerFirst(lastMessage) lastMessage = msg acc.reverse @@ -760,7 +760,7 @@ trait TestKitBase { private def receiveN_internal(n: Int, max: Duration): immutable.Seq[AnyRef] = { val stop = max + now - for { x ← 1 to n } yield { + for { x <- 1 to n } yield { val timeout = stop - now val o = receiveOne(timeout) assert(o ne null, s"timeout ($max) while expecting $n messages (got ${x - 1})") @@ -785,10 +785,10 @@ trait TestKitBase { } lastWasNoMsg = false message match { - case null ⇒ + case null => lastMessage = NullMessage null - case RealMessage(msg, _) ⇒ + case RealMessage(msg, _) => lastMessage = message msg } @@ -902,7 +902,7 @@ object TestKit { * Await until the given condition evaluates to `true` or the timeout * expires, whichever comes first. */ - def awaitCond(p: ⇒ Boolean, max: Duration, interval: Duration = 100.millis, noThrow: Boolean = false): Boolean = { + def awaitCond(p: => Boolean, max: Duration, interval: Duration = 100.millis, noThrow: Boolean = false): Boolean = { val stop = now + max @tailrec @@ -939,7 +939,7 @@ object TestKit { verifySystemShutdown: Boolean = false): Unit = { actorSystem.terminate() try Await.ready(actorSystem.whenTerminated, duration) catch { - case _: TimeoutException ⇒ + case _: TimeoutException => val msg = "Failed to stop [%s] within [%s] \n%s".format(actorSystem.name, duration, actorSystem.asInstanceOf[ActorSystemImpl].printTree) if (verifySystemShutdown) throw new RuntimeException(msg) @@ -991,11 +991,11 @@ object TestProbe { def apply(name: String)(implicit system: ActorSystem) = new TestProbe(system, name) } -trait ImplicitSender { this: TestKitBase ⇒ +trait ImplicitSender { this: TestKitBase => implicit def self = testActor } -trait DefaultTimeout { this: TestKitBase ⇒ +trait DefaultTimeout { this: TestKitBase => implicit val timeout: Timeout = testKitSettings.DefaultTimeout } @@ -1021,6 +1021,6 @@ private[testkit] abstract class CachingPartialFunction[A, B <: AnyRef] extends s def `match`(x: A): B var cache: B = _ - final def isDefinedAt(x: A): Boolean = try { cache = `match`(x); true } catch { case NoMatch ⇒ cache = null.asInstanceOf[B]; false } + final def isDefinedAt(x: A): Boolean = try { cache = `match`(x); true } catch { case NoMatch => cache = null.asInstanceOf[B]; false } final override def apply(x: A): B = cache } diff --git a/akka-testkit/src/main/scala/akka/testkit/TestKitExtension.scala b/akka-testkit/src/main/scala/akka/testkit/TestKitExtension.scala index dd5982a668..ba374f72dd 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestKitExtension.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestKitExtension.scala @@ -19,7 +19,7 @@ class TestKitSettings(val config: Config) extends Extension { import akka.util.Helpers._ val TestTimeFactor = config.getDouble("akka.test.timefactor"). - requiring(tf ⇒ !tf.isInfinite && tf > 0, "akka.test.timefactor must be positive finite double") + requiring(tf => !tf.isInfinite && tf > 0, "akka.test.timefactor must be positive finite double") val SingleExpectDefaultTimeout: FiniteDuration = config.getMillisDuration("akka.test.single-expect-default") val TestEventFilterLeeway: FiniteDuration = config.getMillisDuration("akka.test.filter-leeway") val DefaultTimeout: Timeout = Timeout(config.getMillisDuration("akka.test.default-timeout")) diff --git a/akka-testkit/src/main/scala/akka/testkit/TestLatch.scala b/akka-testkit/src/main/scala/akka/testkit/TestLatch.scala index eb565f51ba..b5c352a4e2 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestLatch.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestLatch.scala @@ -34,8 +34,8 @@ class TestLatch(count: Int = 1)(implicit system: ActorSystem) extends Awaitable[ @throws(classOf[TimeoutException]) def ready(atMost: Duration)(implicit permit: CanAwait) = { val waitTime = atMost match { - case f: FiniteDuration ⇒ f - case _ ⇒ throw new IllegalArgumentException("TestLatch does not support waiting for " + atMost) + case f: FiniteDuration => f + case _ => throw new IllegalArgumentException("TestLatch does not support waiting for " + atMost) } val opened = latch.await(waitTime.dilated.toNanos, TimeUnit.NANOSECONDS) if (!opened) throw new TimeoutException( diff --git a/akka-testkit/src/main/scala/akka/testkit/javadsl/TestKit.scala b/akka-testkit/src/main/scala/akka/testkit/javadsl/TestKit.scala index 210620d0a2..12775ecad9 100644 --- a/akka-testkit/src/main/scala/akka/testkit/javadsl/TestKit.scala +++ b/akka-testkit/src/main/scala/akka/testkit/javadsl/TestKit.scala @@ -4,8 +4,8 @@ package akka.testkit.javadsl -import java.util.function.{ Supplier, Function ⇒ JFunction } -import java.util.{ List ⇒ JList } +import java.util.function.{ Supplier, Function => JFunction } +import java.util.{ List => JList } import akka.actor._ import akka.testkit.{ TestActor, TestDuration, TestProbe } @@ -59,8 +59,8 @@ class TestKit(system: ActorSystem) { def duration(s: String): FiniteDuration = { Duration.apply(s) match { - case fd: FiniteDuration ⇒ fd - case _ ⇒ throw new IllegalArgumentException("duration() is only for finite durations, use Duration.Inf() and friends") + case fd: FiniteDuration => fd + case _ => throw new IllegalArgumentException("duration() is only for finite durations, use Duration.Inf() and friends") } } @@ -900,6 +900,6 @@ private abstract class CachingPartialFunction[A, B] extends scala.runtime.Abstra def `match`(x: A): B var cache: B = _ - final def isDefinedAt(x: A): Boolean = try { cache = `match`(x); true } catch { case NoMatch ⇒ cache = null.asInstanceOf[B]; false } + final def isDefinedAt(x: A): Boolean = try { cache = `match`(x); true } catch { case NoMatch => cache = null.asInstanceOf[B]; false } final override def apply(x: A): B = cache } diff --git a/akka-testkit/src/main/scala/akka/testkit/package.scala b/akka-testkit/src/main/scala/akka/testkit/package.scala index 10fe2b5478..83ff4507aa 100644 --- a/akka-testkit/src/main/scala/akka/testkit/package.scala +++ b/akka-testkit/src/main/scala/akka/testkit/package.scala @@ -12,7 +12,7 @@ import scala.collection.immutable import java.util.concurrent.TimeUnit.MILLISECONDS package object testkit { - def filterEvents[T](eventFilters: Iterable[EventFilter])(block: ⇒ T)(implicit system: ActorSystem): T = { + def filterEvents[T](eventFilters: Iterable[EventFilter])(block: => T)(implicit system: ActorSystem): T = { def now = System.currentTimeMillis system.eventStream.publish(TestEvent.Mute(eventFilters.to(immutable.Seq))) @@ -32,9 +32,9 @@ package object testkit { } } - def filterEvents[T](eventFilters: EventFilter*)(block: ⇒ T)(implicit system: ActorSystem): T = filterEvents(eventFilters.toSeq)(block) + def filterEvents[T](eventFilters: EventFilter*)(block: => T)(implicit system: ActorSystem): T = filterEvents(eventFilters.toSeq)(block) - def filterException[T <: Throwable](block: ⇒ Unit)(implicit system: ActorSystem, t: ClassTag[T]): Unit = EventFilter[T]() intercept (block) + def filterException[T <: Throwable](block: => Unit)(implicit system: ActorSystem, t: ClassTag[T]): Unit = EventFilter[T]() intercept (block) /** * Scala API. Scale timeouts (durations) during tests with the configured diff --git a/akka-testkit/src/test/scala/akka/testkit/AkkaSpec.scala b/akka-testkit/src/test/scala/akka/testkit/AkkaSpec.scala index 0a25cc9ce7..f1823a8772 100644 --- a/akka-testkit/src/test/scala/akka/testkit/AkkaSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/AkkaSpec.scala @@ -48,8 +48,8 @@ object AkkaSpec { val s = (Thread.currentThread.getStackTrace map (_.getClassName) drop 1) .dropWhile(_ matches "(java.lang.Thread|.*AkkaSpec.*|.*\\.StreamSpec.*|.*MultiNodeSpec.*|.*\\.Abstract.*)") val reduced = s.lastIndexWhere(_ == clazz.getName) match { - case -1 ⇒ s - case z ⇒ s drop (z + 1) + case -1 => s + case z => s drop (z + 1) } reduced.head.replaceFirst(""".*\.""", "").replaceAll("[^a-zA-Z_0-9]", "_") } @@ -94,7 +94,7 @@ abstract class AkkaSpec(_system: ActorSystem) protected def afterTermination(): Unit = {} - def spawn(dispatcherId: String = Dispatchers.DefaultDispatcherId)(body: ⇒ Unit): Unit = + def spawn(dispatcherId: String = Dispatchers.DefaultDispatcherId)(body: => Unit): Unit = Future(body)(system.dispatchers.lookup(dispatcherId)) override def expectedTestDuration: FiniteDuration = 60 seconds diff --git a/akka-testkit/src/test/scala/akka/testkit/AkkaSpecSpec.scala b/akka-testkit/src/test/scala/akka/testkit/AkkaSpecSpec.scala index c50086859f..84bf1b0079 100644 --- a/akka-testkit/src/test/scala/akka/testkit/AkkaSpecSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/AkkaSpecSpec.scala @@ -35,8 +35,8 @@ class AkkaSpecSpec extends WordSpec with Matchers { // verbose config just for demonstration purposes, please leave in in case of debugging import scala.collection.JavaConverters._ val conf = Map( - "akka.actor.debug.lifecycle" → true, "akka.actor.debug.event-stream" → true, - "akka.loglevel" → "DEBUG", "akka.stdout-loglevel" → "DEBUG") + "akka.actor.debug.lifecycle" -> true, "akka.actor.debug.event-stream" -> true, + "akka.loglevel" -> "DEBUG", "akka.stdout-loglevel" -> "DEBUG") val system = ActorSystem("AkkaSpec1", ConfigFactory.parseMap(conf.asJava).withFallback(AkkaSpec.testConf)) var refs = Seq.empty[ActorRef] val spec = new AkkaSpec(system) { refs = Seq(testActor, system.actorOf(Props.empty, "name")) } @@ -64,8 +64,8 @@ class AkkaSpecSpec extends WordSpec with Matchers { implicit val timeout = TestKitExtension(system).DefaultTimeout val davyJones = otherSystem.actorOf(Props(new Actor { def receive = { - case m: DeadLetter ⇒ locker :+= m - case "Die!" ⇒ sender() ! "finally gone"; context.stop(self) + case m: DeadLetter => locker :+= m + case "Die!" => sender() ! "finally gone"; context.stop(self) } }), "davyJones") @@ -79,7 +79,7 @@ class AkkaSpecSpec extends WordSpec with Matchers { * a chance to put the message into its private queue */ probe.receiveWhile(1 second) { - case null ⇒ + case null => } val latch = new TestLatch(1)(system) diff --git a/akka-testkit/src/test/scala/akka/testkit/Coroner.scala b/akka-testkit/src/test/scala/akka/testkit/Coroner.scala index 0ffd8e5571..e8b1f1f66b 100644 --- a/akka-testkit/src/test/scala/akka/testkit/Coroner.scala +++ b/akka-testkit/src/test/scala/akka/testkit/Coroner.scala @@ -64,7 +64,7 @@ object Coroner { } override def result(atMost: Duration)(implicit permit: CanAwait): Boolean = - try { Await.result(cancelPromise.future, atMost) } catch { case _: TimeoutException ⇒ false } + try { Await.result(cancelPromise.future, atMost) } catch { case _: TimeoutException => false } } @@ -96,7 +96,7 @@ object Coroner { watchedHandle.expired() out.println(s"Coroner not cancelled after ${duration.toMillis}ms. Looking for signs of foul play...") try printReport(reportTitle, out) catch { - case NonFatal(ex) ⇒ { + case NonFatal(ex) => { out.println("Error displaying Coroner's Report") ex.printStackTrace(out) } @@ -160,7 +160,7 @@ object Coroner { if (threadInfos.isEmpty) { println("None") } else { - for (ti ← threadInfos.sortBy(_.getThreadName)) { println(threadInfoToString(ti)) } + for (ti <- threadInfos.sortBy(_.getThreadName)) { println(threadInfoToString(ti)) } } } @@ -201,27 +201,27 @@ object Coroner { } val stackTrace = ti.getStackTrace - for (i ← 0 until stackTrace.length) { + for (i <- 0 until stackTrace.length) { val ste = stackTrace(i) appendMsg("\tat ", ste) if (i == 0 && ti.getLockInfo != null) { import java.lang.Thread.State._ ti.getThreadState match { - case BLOCKED ⇒ appendMsg("\t- blocked on ", ti.getLockInfo) - case WAITING ⇒ appendMsg("\t- waiting on ", ti.getLockInfo) - case TIMED_WAITING ⇒ appendMsg("\t- waiting on ", ti.getLockInfo) - case _ ⇒ + case BLOCKED => appendMsg("\t- blocked on ", ti.getLockInfo) + case WAITING => appendMsg("\t- waiting on ", ti.getLockInfo) + case TIMED_WAITING => appendMsg("\t- waiting on ", ti.getLockInfo) + case _ => } } - for (mi ← ti.getLockedMonitors if mi.getLockedStackDepth == i) + for (mi <- ti.getLockedMonitors if mi.getLockedStackDepth == i) appendMsg("\t- locked ", mi) } val locks = ti.getLockedSynchronizers if (locks.length > 0) { appendMsg("\n\tNumber of locked synchronizers = ", locks.length) - for (li ← locks) appendMsg("\t- ", li) + for (li <- locks) appendMsg("\t- ", li) } sb.append('\n') sb.toString @@ -247,7 +247,7 @@ object Coroner { * counts during start and stop. */ trait WatchedByCoroner { - self: TestKit ⇒ + self: TestKit => @volatile private var coronerWatch: Coroner.WatchHandle = _ diff --git a/akka-testkit/src/test/scala/akka/testkit/CoronerSpec.scala b/akka-testkit/src/test/scala/akka/testkit/CoronerSpec.scala index b7ced83f42..c2c9e479ed 100644 --- a/akka-testkit/src/test/scala/akka/testkit/CoronerSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/CoronerSpec.scala @@ -15,7 +15,7 @@ import scala.concurrent.Await class CoronerSpec extends WordSpec with Matchers { - private def captureOutput[A](f: PrintStream ⇒ A): (A, String) = { + private def captureOutput[A](f: PrintStream => A): (A, String) = { val bytes = new ByteArrayOutputStream() val out = new PrintStream(bytes, true, "UTF-8") val result = f(out) @@ -25,7 +25,7 @@ class CoronerSpec extends WordSpec with Matchers { "A Coroner" must { "generate a report if enough time passes" in { - val (_, report) = captureOutput(out ⇒ { + val (_, report) = captureOutput(out => { val coroner = Coroner.watch(100.milliseconds, "XXXX", out) Await.ready(coroner, 5.seconds) coroner.cancel() @@ -35,7 +35,7 @@ class CoronerSpec extends WordSpec with Matchers { } "not generate a report if cancelled early" in { - val (_, report) = captureOutput(out ⇒ { + val (_, report) = captureOutput(out => { val coroner = Coroner.watch(60.seconds, "XXXX", out) coroner.cancel() Await.ready(coroner, 1.seconds) @@ -44,7 +44,7 @@ class CoronerSpec extends WordSpec with Matchers { } "display thread counts if enabled" in { - val (_, report) = captureOutput(out ⇒ { + val (_, report) = captureOutput(out => { val coroner = Coroner.watch(60.seconds, "XXXX", out, displayThreadCounts = true) coroner.cancel() Await.ready(coroner, 1.second) @@ -69,12 +69,12 @@ class CoronerSpec extends WordSpec with Matchers { val ready = new Semaphore(0) val proceed = new Semaphore(0) val t = new Thread(new Runnable { - def run = try recursiveLock(initialLocks) catch { case _: InterruptedException ⇒ () } + def run = try recursiveLock(initialLocks) catch { case _: InterruptedException => () } def recursiveLock(locks: List[ReentrantLock]): Unit = { locks match { - case Nil ⇒ () - case lock :: rest ⇒ { + case Nil => () + case lock :: rest => { ready.release() proceed.acquire() lock.lockInterruptibly() // Allows us to break deadlock and free threads diff --git a/akka-testkit/src/test/scala/akka/testkit/JavaTestKitSpec.scala b/akka-testkit/src/test/scala/akka/testkit/JavaTestKitSpec.scala index 8eee059ae5..31dcbc8574 100644 --- a/akka-testkit/src/test/scala/akka/testkit/JavaTestKitSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/JavaTestKitSpec.scala @@ -16,7 +16,7 @@ class JavaTestKitSpec extends AkkaSpec with DefaultTimeout { "be able to receiveN messages" in { new JavaTestKit(system) { val sent = List(1, 2, 3, 4, 5) - for (m ← sent) { getRef() ! m } + for (m <- sent) { getRef() ! m } val received = receiveN(sent.size, 5 seconds) sent.toSet should be(received.toSet) } @@ -25,7 +25,7 @@ class JavaTestKitSpec extends AkkaSpec with DefaultTimeout { "be able to receiveN messages with default duration" in { new JavaTestKit(system) { val sent = List(1, 2, 3) - for (m ← sent) { getRef() ! m } + for (m <- sent) { getRef() ! m } val received = receiveN(sent.size) sent.toSet should be(received.toSet) } @@ -33,7 +33,7 @@ class JavaTestKitSpec extends AkkaSpec with DefaultTimeout { "be able to expectTerminated" in { new JavaTestKit(system) { - val actor = system.actorOf(Props(new Actor { def receive = { case _ ⇒ } })) + val actor = system.actorOf(Props(new Actor { def receive = { case _ => } })) watch(actor) system stop actor diff --git a/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala b/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala index 12cb5ee78e..99554bae45 100644 --- a/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/TestActorRefSpec.scala @@ -40,26 +40,26 @@ object TestActorRefSpec { var replyTo: ActorRef = null def receiveT = { - case "complexRequest" ⇒ { + case "complexRequest" => { replyTo = sender() val worker = TestActorRef(Props[WorkerActor]) worker ! "work" } - case "complexRequest2" ⇒ + case "complexRequest2" => val worker = TestActorRef(Props[WorkerActor]) worker ! sender() - case "workDone" ⇒ replyTo ! "complexReply" - case "simpleRequest" ⇒ sender() ! "simpleReply" + case "workDone" => replyTo ! "complexReply" + case "simpleRequest" => sender() ! "simpleReply" } } class WorkerActor() extends TActor { def receiveT = { - case "work" ⇒ + case "work" => sender() ! "workDone" context stop self - case replyTo: Promise[_] ⇒ replyTo.asInstanceOf[Promise[Any]].success("complexReply") - case replyTo: ActorRef ⇒ replyTo ! "complexReply" + case replyTo: Promise[_] => replyTo.asInstanceOf[Promise[Any]].success("complexReply") + case replyTo: ActorRef => replyTo ! "complexReply" } val supervisor = context.parent @@ -69,13 +69,13 @@ object TestActorRefSpec { class SenderActor(replyActor: ActorRef) extends TActor { def receiveT = { - case "complex" ⇒ replyActor ! "complexRequest" - case "complex2" ⇒ replyActor ! "complexRequest2" - case "simple" ⇒ replyActor ! "simpleRequest" - case "complexReply" ⇒ { + case "complex" => replyActor ! "complexRequest" + case "complex2" => replyActor ! "complexRequest2" + case "simple" => replyActor ! "simpleRequest" + case "complexReply" => { counter -= 1 } - case "simpleReply" ⇒ { + case "simpleReply" => { counter -= 1 } } @@ -85,14 +85,14 @@ object TestActorRefSpec { var count = 0 var msg: String = _ def receive = { - case Warning(_, _, m: String) ⇒ count += 1; msg = m + case Warning(_, _, m: String) => count += 1; msg = m } } class ReceiveTimeoutActor(target: ActorRef) extends Actor { context setReceiveTimeout 1.second def receive = { - case ReceiveTimeout ⇒ + case ReceiveTimeout => target ! "timeout" context stop self } @@ -120,8 +120,8 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA "used with TestActorRef" in { val a = TestActorRef(Props(new Actor { - val nested = TestActorRef(Props(new Actor { def receive = { case _ ⇒ } })) - def receive = { case _ ⇒ sender() ! nested } + val nested = TestActorRef(Props(new Actor { def receive = { case _ => } })) + def receive = { case _ => sender() ! nested } })) a should not be (null) val nested = Await.result((a ? "any").mapTo[ActorRef], timeout.duration) @@ -131,8 +131,8 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA "used with ActorRef" in { val a = TestActorRef(Props(new Actor { - val nested = context.actorOf(Props(new Actor { def receive = { case _ ⇒ } })) - def receive = { case _ ⇒ sender() ! nested } + val nested = context.actorOf(Props(new Actor { def receive = { case _ => } })) + def receive = { case _ => sender() ! nested } })) a should not be (null) val nested = Await.result((a ? "any").mapTo[ActorRef], timeout.duration) @@ -173,13 +173,13 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA system.actorOf(Props(new Actor { context.watch(a) def receive = { - case t: Terminated ⇒ testActor forward WrappedTerminated(t) - case x ⇒ testActor forward x + case t: Terminated => testActor forward WrappedTerminated(t) + case x => testActor forward x } })) a.!(PoisonPill)(testActor) expectMsgPF(5 seconds) { - case WrappedTerminated(Terminated(`a`)) ⇒ true + case WrappedTerminated(Terminated(`a`)) => true } a.isTerminated should ===(true) assertThread() @@ -192,7 +192,7 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA val boss = TestActorRef(Props(new TActor { val ref = TestActorRef(Props(new TActor { - def receiveT = { case _ ⇒ } + def receiveT = { case _ => } override def preRestart(reason: Throwable, msg: Option[Any]): Unit = { counter -= 1 } override def postRestart(reason: Throwable): Unit = { counter -= 1 } }), self, "child") @@ -200,7 +200,7 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA override def supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 5, withinTimeRange = 1 second)(List(classOf[ActorKilledException])) - def receiveT = { case "sendKill" ⇒ ref ! Kill } + def receiveT = { case "sendKill" => ref ! Kill } })) boss ! "sendKill" @@ -231,7 +231,7 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA class TA extends TActor { var s: String = _ def receiveT = { - case x: String ⇒ s = x + case x: String => s = x } } val ref = TestActorRef(new TA) @@ -273,8 +273,8 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA val parent = TestProbe() val child = TestActorRef(Props(new Actor { def receive: Receive = { - case 1 ⇒ throw new RuntimeException("expected") - case x ⇒ sender() ! x + case 1 => throw new RuntimeException("expected") + case x => sender() ! x } }), parent.ref, "Child") @@ -286,8 +286,8 @@ class TestActorRefSpec extends AkkaSpec("disp1.type=Dispatcher") with BeforeAndA val parent = TestProbe() val child = parent.childActorOf(Props(new Actor { def receive: Receive = { - case 1 ⇒ throw new RuntimeException("expected") - case x ⇒ sender() ! x + case 1 => throw new RuntimeException("expected") + case x => sender() ! x } }), "Child") diff --git a/akka-testkit/src/test/scala/akka/testkit/TestFSMRefSpec.scala b/akka-testkit/src/test/scala/akka/testkit/TestFSMRefSpec.scala index 3751618d6d..bee0124c6f 100644 --- a/akka-testkit/src/test/scala/akka/testkit/TestFSMRefSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/TestFSMRefSpec.scala @@ -17,11 +17,11 @@ class TestFSMRefSpec extends AkkaSpec { val fsm = TestFSMRef(new Actor with FSM[Int, String] { startWith(1, "") when(1) { - case Event("go", _) ⇒ goto(2) using "go" - case Event(StateTimeout, _) ⇒ goto(2) using "timeout" + case Event("go", _) => goto(2) using "go" + case Event(StateTimeout, _) => goto(2) using "timeout" } when(2) { - case Event("back", _) ⇒ goto(1) using "back" + case Event("back", _) => goto(1) using "back" } }, "test-fsm-ref-1") fsm.stateName should ===(1) @@ -45,7 +45,7 @@ class TestFSMRefSpec extends AkkaSpec { val fsm = TestFSMRef(new Actor with FSM[Int, Null] { startWith(1, null) when(1) { - case x ⇒ stay + case x => stay } }, "test-fsm-ref-2") fsm.isTimerActive("test") should ===(false) @@ -60,12 +60,12 @@ class TestFSMRefSpec extends AkkaSpec { val guardian = system.asInstanceOf[ActorSystemImpl].guardian - val parent = system.actorOf(Props(new Actor { def receive = { case _ ⇒ } })) + val parent = system.actorOf(Props(new Actor { def receive = { case _ => } })) class TestFSMActor extends Actor with FSM[Int, Null] { startWith(1, null) when(1) { - case x ⇒ stay + case x => stay } val supervisor = context.parent val name = context.self.path.name diff --git a/akka-testkit/src/test/scala/akka/testkit/TestProbeSpec.scala b/akka-testkit/src/test/scala/akka/testkit/TestProbeSpec.scala index 7f7d554d39..450b342503 100644 --- a/akka-testkit/src/test/scala/akka/testkit/TestProbeSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/TestProbeSpec.scala @@ -60,8 +60,8 @@ class TestProbeSpec extends AkkaSpec with DefaultTimeout with Eventually { val restarts = new AtomicInteger(0) class FailingActor extends Actor { - override def receive = msg ⇒ msg match { - case _ ⇒ + override def receive = msg => msg match { + case _ => throw new RuntimeException("simulated failure") } @@ -79,16 +79,16 @@ class TestProbeSpec extends AkkaSpec with DefaultTimeout with Eventually { } } - def assertFailureMessageContains(expectedHint: String)(block: ⇒ Unit): Unit = { + def assertFailureMessageContains(expectedHint: String)(block: => Unit): Unit = { Try { block } match { - case scala.util.Failure(e: AssertionError) ⇒ + case scala.util.Failure(e: AssertionError) => if (!(e.getMessage contains expectedHint)) fail(s"failure message did not contain hint! Was: ${e.getMessage}, expected to contain $expectedHint") - case scala.util.Failure(oth) ⇒ + case scala.util.Failure(oth) => fail(s"expected AssertionError but got: $oth") - case scala.util.Success(result) ⇒ + case scala.util.Success(result) => fail(s"expected failure but got: $result") } } @@ -118,8 +118,8 @@ class TestProbeSpec extends AkkaSpec with DefaultTimeout with Eventually { probe.setAutoPilot(new TestActor.AutoPilot { def run(sender: ActorRef, msg: Any): TestActor.AutoPilot = msg match { - case "stop" ⇒ TestActor.NoAutoPilot - case x ⇒ testActor.tell(x, sender); TestActor.KeepRunning + case "stop" => TestActor.NoAutoPilot + case x => testActor.tell(x, sender); TestActor.KeepRunning } }) //#autopilot @@ -138,7 +138,7 @@ class TestProbeSpec extends AkkaSpec with DefaultTimeout with Eventually { } "be able to expect primitive types" in { - for (_ ← 1 to 7) testActor ! 42 + for (_ <- 1 to 7) testActor ! 42 expectMsgType[Int] should ===(42) expectMsgAnyClassOf(classOf[Int]) should ===(42) expectMsgAllClassOf(classOf[Int]) should ===(Seq(42)) @@ -156,8 +156,8 @@ class TestProbeSpec extends AkkaSpec with DefaultTimeout with Eventually { probe.ref ! "done" probe.fishForMessage() { - case "fishForMe" ⇒ true - case _ ⇒ false + case "fishForMe" => true + case _ => false } probe.expectMsg(1 second, "done") @@ -171,7 +171,7 @@ class TestProbeSpec extends AkkaSpec with DefaultTimeout with Eventually { probe.ref ! "done" val msg: String = probe.fishForSpecificMessage() { - case msg @ "fishForMe" ⇒ msg + case msg @ "fishForMe" => msg } msg should be("fishForMe") @@ -180,7 +180,7 @@ class TestProbeSpec extends AkkaSpec with DefaultTimeout with Eventually { } "be able to ignore primitive types" in { - ignoreMsg { case 42 ⇒ true } + ignoreMsg { case 42 => true } testActor ! 42 testActor ! "pigdog" expectMsg("pigdog") diff --git a/akka-testkit/src/test/scala/akka/testkit/TestTimeSpec.scala b/akka-testkit/src/test/scala/akka/testkit/TestTimeSpec.scala index 45b1fe0b49..17dce102b7 100644 --- a/akka-testkit/src/test/scala/akka/testkit/TestTimeSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/TestTimeSpec.scala @@ -7,7 +7,7 @@ package akka.testkit import scala.concurrent.duration._ import org.scalatest.exceptions.TestFailedException -class TestTimeSpec extends AkkaSpec(Map("akka.test.timefactor" → 2.0)) { +class TestTimeSpec extends AkkaSpec(Map("akka.test.timefactor" -> 2.0)) { "A TestKit" must { diff --git a/akka-testkit/src/test/scala/akka/testkit/WithLogCapturing.scala b/akka-testkit/src/test/scala/akka/testkit/WithLogCapturing.scala index e831ce2404..6305061e36 100644 --- a/akka-testkit/src/test/scala/akka/testkit/WithLogCapturing.scala +++ b/akka-testkit/src/test/scala/akka/testkit/WithLogCapturing.scala @@ -14,7 +14,7 @@ import org.scalatest.{ Outcome, SuiteMixin, TestSuite } /** * Mixin this trait to a test to make log lines appear only when the test failed. */ -trait WithLogCapturing extends SuiteMixin { this: TestSuite ⇒ +trait WithLogCapturing extends SuiteMixin { this: TestSuite => implicit def system: ActorSystem abstract override def withFixture(test: NoArgTest): Outcome = { @@ -48,7 +48,7 @@ trait WithLogCapturing extends SuiteMixin { this: TestSuite ⇒ } /** Adds a prefix to every line printed out during execution of the thunk. */ - private def withPrefixedOut[T](prefix: String)(thunk: ⇒ T): T = { + private def withPrefixedOut[T](prefix: String)(thunk: => T): T = { val oldOut = Console.out val prefixingOut = new PrintStream(new OutputStream { @@ -71,8 +71,8 @@ trait WithLogCapturing extends SuiteMixin { this: TestSuite ⇒ */ class DebugLogSilencingTestEventListener extends TestEventListener { override def print(event: Any): Unit = event match { - case _: Debug ⇒ // ignore - case _ ⇒ super.print(event) + case _: Debug => // ignore + case _ => super.print(event) } } diff --git a/akka-testkit/src/test/scala/akka/testkit/metrics/FileDescriptorMetricSet.scala b/akka-testkit/src/test/scala/akka/testkit/metrics/FileDescriptorMetricSet.scala index df89319af0..2895764cdf 100644 --- a/akka-testkit/src/test/scala/akka/testkit/metrics/FileDescriptorMetricSet.scala +++ b/akka-testkit/src/test/scala/akka/testkit/metrics/FileDescriptorMetricSet.scala @@ -19,15 +19,15 @@ private[akka] class FileDescriptorMetricSet(os: OperatingSystemMXBean = Manageme override def getMetrics: util.Map[String, Metric] = { Map[String, Metric]( - name("file-descriptors", "open") → new Gauge[Long] { + name("file-descriptors", "open") -> new Gauge[Long] { override def getValue: Long = invoke("getOpenFileDescriptorCount") }, - name("file-descriptors", "max") → new Gauge[Long] { + name("file-descriptors", "max") -> new Gauge[Long] { override def getValue: Long = invoke("getMaxFileDescriptorCount") }, - name("file-descriptors", "ratio") → new FileDescriptorRatioGauge(os)).asJava + name("file-descriptors", "ratio") -> new FileDescriptorRatioGauge(os)).asJava } private def invoke(name: String): Long = { diff --git a/akka-testkit/src/test/scala/akka/testkit/metrics/HdrHistogram.scala b/akka-testkit/src/test/scala/akka/testkit/metrics/HdrHistogram.scala index b9b5271cca..ae8fea86dd 100644 --- a/akka-testkit/src/test/scala/akka/testkit/metrics/HdrHistogram.scala +++ b/akka-testkit/src/test/scala/akka/testkit/metrics/HdrHistogram.scala @@ -5,7 +5,7 @@ package akka.testkit.metrics import com.codahale.metrics.Metric -import org.{ HdrHistogram ⇒ hdr } +import org.{ HdrHistogram => hdr } /** * Adapts Gil Tene's HdrHistogram to Metric's Metric interface. @@ -28,7 +28,7 @@ private[akka] class HdrHistogram( try hist.recordValue(value) catch { - case ex: ArrayIndexOutOfBoundsException ⇒ throw wrapHistogramOutOfBoundsException(value, ex) + case ex: ArrayIndexOutOfBoundsException => throw wrapHistogramOutOfBoundsException(value, ex) } } @@ -36,7 +36,7 @@ private[akka] class HdrHistogram( try hist.recordValueWithCount(value, count) catch { - case ex: ArrayIndexOutOfBoundsException ⇒ throw wrapHistogramOutOfBoundsException(value, ex) + case ex: ArrayIndexOutOfBoundsException => throw wrapHistogramOutOfBoundsException(value, ex) } } diff --git a/akka-testkit/src/test/scala/akka/testkit/metrics/MemoryUsageSnapshotting.scala b/akka-testkit/src/test/scala/akka/testkit/metrics/MemoryUsageSnapshotting.scala index ab6e5c9d5b..1e545e7ee1 100644 --- a/akka-testkit/src/test/scala/akka/testkit/metrics/MemoryUsageSnapshotting.scala +++ b/akka-testkit/src/test/scala/akka/testkit/metrics/MemoryUsageSnapshotting.scala @@ -8,7 +8,7 @@ import com.codahale.metrics._ import com.codahale.metrics.jvm private[akka] trait MemoryUsageSnapshotting extends MetricsPrefix { - this: jvm.MemoryUsageGaugeSet ⇒ + this: jvm.MemoryUsageGaugeSet => // accessing metrics in order to not to duplicate mxBean access too much diff --git a/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKit.scala b/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKit.scala index 841ad5a85b..86be4b58a3 100644 --- a/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKit.scala +++ b/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKit.scala @@ -26,7 +26,7 @@ import scala.reflect.ClassTag * Reporting defaults to `ConsoleReporter`. */ private[akka] trait MetricsKit extends MetricsKitOps { - this: Notifying ⇒ + this: Notifying => import MetricsKit._ import collection.JavaConverters._ @@ -147,12 +147,12 @@ private[akka] trait MetricsKit extends MetricsKitOps { reporters foreach { _.stop() } } - private[metrics] def getOrRegister[M <: Metric](key: String, metric: ⇒ M)(implicit tag: ClassTag[M]): M = { + private[metrics] def getOrRegister[M <: Metric](key: String, metric: => M)(implicit tag: ClassTag[M]): M = { import collection.JavaConverters._ registry.getMetrics.asScala.find(_._1 == key).map(_._2) match { - case Some(existing: M) ⇒ existing - case Some(existing) ⇒ throw new IllegalArgumentException("Key: [%s] is already for different kind of metric! Was [%s], expected [%s]".format(key, metric.getClass.getSimpleName, tag.runtimeClass.getSimpleName)) - case _ ⇒ registry.register(key, metric) + case Some(existing: M) => existing + case Some(existing) => throw new IllegalArgumentException("Key: [%s] is already for different kind of metric! Was [%s], expected [%s]".format(key, metric.getClass.getSimpleName, tag.runtimeClass.getSimpleName)) + case _ => registry.register(key, metric) } } @@ -183,7 +183,7 @@ private[akka] object MetricsKit { /** Provides access to custom Akka `com.codahale.metrics.Metric`, with named methods. */ trait AkkaMetricRegistry { - this: MetricRegistry ⇒ + this: MetricRegistry => def getKnownOpsInTimespanCounters = filterFor(classOf[KnownOpsInTimespanTimer]) def getHdrHistograms = filterFor(classOf[HdrHistogram]) @@ -192,9 +192,9 @@ trait AkkaMetricRegistry { import collection.JavaConverters._ private def filterFor[T](clazz: Class[T]): mutable.Iterable[(String, T)] = for { - (key, metric) ← getMetrics.asScala + (key, metric) <- getMetrics.asScala if clazz.isInstance(metric) - } yield key → metric.asInstanceOf[T] + } yield key -> metric.asInstanceOf[T] } private[akka] class MetricsKitSettings(config: Config) { diff --git a/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKitOps.scala b/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKitOps.scala index 1e5a83ee5c..2a846f09cc 100644 --- a/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKitOps.scala +++ b/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKitOps.scala @@ -15,7 +15,7 @@ import com.codahale.metrics.jvm.MemoryUsageGaugeSet * Extracted to give easy overview of user-API detached from MetricsKit internals. */ private[akka] trait MetricsKitOps extends MetricKeyDSL { - this: MetricsKit ⇒ + this: MetricsKit => type MetricKey = MetricKeyDSL#MetricKey @@ -31,7 +31,7 @@ private[akka] trait MetricsKitOps extends MetricKeyDSL { * * Do not use for short running pieces of code. */ - def timedWithKnownOps[T](key: MetricKey, ops: Long)(run: ⇒ T): T = { + def timedWithKnownOps[T](key: MetricKey, ops: Long)(run: => T): T = { val c = getOrRegister(key.toString, new KnownOpsInTimespanTimer(expectedOps = ops)) try run finally c.stop() } @@ -94,6 +94,6 @@ private[metrics] trait MetricsPrefix extends MetricSet { abstract override def getMetrics: util.Map[String, Metric] = { // does not have to be fast, is only called once during registering registry import collection.JavaConverters._ - (super.getMetrics.asScala.map { case (k, v) ⇒ (prefix / k).toString → v }).asJava + (super.getMetrics.asScala.map { case (k, v) => (prefix / k).toString -> v }).asJava } } diff --git a/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKitSpec.scala b/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKitSpec.scala index 8cda42697c..86c97e038b 100644 --- a/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKitSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/metrics/MetricsKitSpec.scala @@ -54,8 +54,8 @@ class MetricsKitSpec extends WordSpec with Matchers with BeforeAndAfter with Bef val hist = hdrHistogram(KitKey / "hist", highestTrackableValue = maxMillis, 4, "ns") for { - n ← 1 to 11 - i ← 0L to 1579331 + n <- 1 to 11 + i <- 0L to 1579331 } hist.update(i) hist.update(1579331) diff --git a/akka-testkit/src/test/scala/akka/testkit/metrics/reporter/AkkaConsoleReporter.scala b/akka-testkit/src/test/scala/akka/testkit/metrics/reporter/AkkaConsoleReporter.scala index 6ae67a2756..4c1b7c1c04 100644 --- a/akka-testkit/src/test/scala/akka/testkit/metrics/reporter/AkkaConsoleReporter.scala +++ b/akka-testkit/src/test/scala/akka/testkit/metrics/reporter/AkkaConsoleReporter.scala @@ -41,10 +41,10 @@ class AkkaConsoleReporter( output.flush() } - def printMetrics[T <: Metric](metrics: Iterable[(String, T)], printer: T ⇒ Unit)(implicit clazz: ClassTag[T]): Unit = { + def printMetrics[T <: Metric](metrics: Iterable[(String, T)], printer: T => Unit)(implicit clazz: ClassTag[T]): Unit = { if (!metrics.isEmpty) { printWithBanner(s"-- ${simpleName(metrics.head._2.getClass)}", '-') - for ((key, metric) ← metrics) { + for ((key, metric) <- metrics) { output.println(" " + key) printer(metric) } diff --git a/build.sbt b/build.sbt index 79af1c6658..dfaa6e42db 100644 --- a/build.sbt +++ b/build.sbt @@ -58,8 +58,8 @@ lazy val root = Project( .settings(rootSettings: _*) .settings(unidocRootIgnoreProjects := (CrossVersion.partialVersion(scalaVersion.value) match { - case Some((2, n)) if n == 11 ⇒ aggregatedProjects // ignore all, don't unidoc when scalaVersion is 2.11 - case _ ⇒ Seq(remoteTests, benchJmh, benchJmhTyped, protobuf, akkaScalaNightly, docs) + case Some((2, n)) if n == 11 => aggregatedProjects // ignore all, don't unidoc when scalaVersion is 2.11 + case _ => Seq(remoteTests, benchJmh, benchJmhTyped, protobuf, akkaScalaNightly, docs) }), crossScalaVersions := Nil, // Allows some modules (typed) to be only for 2.12 sbt/sbt#3465 ) diff --git a/project/AkkaBuild.scala b/project/AkkaBuild.scala index 8ae41f0c69..e37e515a2c 100644 --- a/project/AkkaBuild.scala +++ b/project/AkkaBuild.scala @@ -46,8 +46,8 @@ object AkkaBuild { val (mavenLocalResolver, mavenLocalResolverSettings) = System.getProperty("akka.build.M2Dir") match { - case null ⇒ (Resolver.mavenLocal, Seq.empty) - case path ⇒ + case null => (Resolver.mavenLocal, Seq.empty) + case path => // Maven resolver settings def deliverPattern(outputPath: File): String = (outputPath / "[artifact]-[revision](-[classifier]).[ext]").absolutePath @@ -78,7 +78,7 @@ object AkkaBuild { Seq(resolvers += Resolver.sonatypeRepo("snapshots")) else Seq.empty } ++ Seq( - pomIncludeRepository := (_ ⇒ false) // do not leak internal repositories during staging + pomIncludeRepository := (_ => false) // do not leak internal repositories during staging ) private def allWarnings: Boolean = System.getProperty("akka.allwarnings", "false").toBoolean @@ -107,7 +107,7 @@ object AkkaBuild { // -release 8 is not enough, for some reason we need the 8 rt.jar explicitly #25330 Seq("-release", "8", "-javabootclasspath", CrossJava.Keys.fullJavaHomes.value("8") + "/jre/lib/rt.jar")), scalacOptions in Compile ++= (if (allWarnings) Seq("-deprecation") else Nil), - scalacOptions in Test := (scalacOptions in Test).value.filterNot(opt ⇒ + scalacOptions in Test := (scalacOptions in Test).value.filterNot(opt => opt == "-Xlog-reflective-calls" || opt.contains("genjavadoc")), javacOptions in compile ++= DefaultJavacOptions ++ ( if (System.getProperty("java.version").startsWith("1.")) @@ -199,7 +199,7 @@ object AkkaBuild { val base = (javaOptions in Test).value val akkaSysProps: Seq[String] = sys.props.filter(_._1.startsWith("akka")) - .map { case (key, value) ⇒ s"-D$key=$value" }(breakOut) + .map { case (key, value) => s"-D$key=$value" }(breakOut) base ++ akkaSysProps }, @@ -209,12 +209,12 @@ object AkkaBuild { testGrouping in Test := { val original: Seq[Tests.Group] = (testGrouping in Test).value - original.map { group ⇒ + original.map { group => group.runPolicy match { - case Tests.SubProcess(forkOptions) ⇒ + case Tests.SubProcess(forkOptions) => group.copy(runPolicy = Tests.SubProcess(forkOptions.withWorkingDirectory( workingDirectory = Some(new File(System.getProperty("user.dir")))))) - case _ ⇒ group + case _ => group } } }, diff --git a/project/AutomaticModuleName.scala b/project/AutomaticModuleName.scala index f1660fb66f..b5fe01c716 100644 --- a/project/AutomaticModuleName.scala +++ b/project/AutomaticModuleName.scala @@ -19,6 +19,6 @@ object AutomaticModuleName { private val AutomaticModuleName = "Automatic-Module-Name" def settings(name: String): Seq[Def.Setting[Task[Seq[PackageOption]]]] = Seq( - packageOptions in (Compile, packageBin) += Package.ManifestAttributes(AutomaticModuleName → name) + packageOptions in (Compile, packageBin) += Package.ManifestAttributes(AutomaticModuleName -> name) ) } diff --git a/project/CliOptions.scala b/project/CliOptions.scala index 98b5b6244e..8fa132a016 100644 --- a/project/CliOptions.scala +++ b/project/CliOptions.scala @@ -12,7 +12,7 @@ object CliOption { def apply[T](path: String, default: T)(implicit ev: CliOptionParser[T]): CliOption[T] = ev.parse(path, default) implicit class BooleanCliOption(cliOption: CliOption[Boolean]) { - def ifTrue[A](a: ⇒ A): Option[A] = if (cliOption.get) Some(a) else None + def ifTrue[A](a: => A): Option[A] = if (cliOption.get) Some(a) else None } trait CliOptionParser[T] { diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 191360ab3d..64af9e389d 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -26,15 +26,15 @@ object Dependencies { scalaStmVersion := sys.props.get("akka.build.scalaStmVersion").getOrElse("0.9"), scalaCheckVersion := sys.props.get("akka.build.scalaCheckVersion").getOrElse( CrossVersion.partialVersion(scalaVersion.value) match { - case Some((2, n)) if n >= 12 ⇒ "1.14.0" // does not work for 2.11 - case _ ⇒ "1.13.2" + case Some((2, n)) if n >= 12 => "1.14.0" // does not work for 2.11 + case _ => "1.13.2" }), scalaTestVersion := "3.0.6-SNAP6", java8CompatVersion := { CrossVersion.partialVersion(scalaVersion.value) match { - case Some((2, n)) if n >= 13 ⇒ "0.9.0" - case Some((2, n)) if n == 12 ⇒ "0.8.0" - case _ ⇒ "0.7.0" + case Some((2, n)) if n >= 13 => "0.9.0" + case Some((2, n)) if n == 12 => "0.8.0" + case _ => "0.7.0" } }) @@ -212,16 +212,16 @@ object Dependencies { } object DependencyHelpers { - case class ScalaVersionDependentModuleID(modules: String ⇒ Seq[ModuleID]) { + case class ScalaVersionDependentModuleID(modules: String => Seq[ModuleID]) { def %(config: String): ScalaVersionDependentModuleID = - ScalaVersionDependentModuleID(version ⇒ modules(version).map(_ % config)) + ScalaVersionDependentModuleID(version => modules(version).map(_ % config)) } object ScalaVersionDependentModuleID { - implicit def liftConstantModule(mod: ModuleID): ScalaVersionDependentModuleID = versioned(_ ⇒ mod) + implicit def liftConstantModule(mod: ModuleID): ScalaVersionDependentModuleID = versioned(_ => mod) - def versioned(f: String ⇒ ModuleID): ScalaVersionDependentModuleID = ScalaVersionDependentModuleID(v ⇒ Seq(f(v))) + def versioned(f: String => ModuleID): ScalaVersionDependentModuleID = ScalaVersionDependentModuleID(v => Seq(f(v))) def fromPF(f: PartialFunction[String, ModuleID]): ScalaVersionDependentModuleID = - ScalaVersionDependentModuleID(version ⇒ if (f.isDefinedAt(version)) Seq(f(version)) else Nil) + ScalaVersionDependentModuleID(version => if (f.isDefinedAt(version)) Seq(f(version)) else Nil) } /** @@ -229,16 +229,16 @@ object DependencyHelpers { * dependent entries. */ def versionDependentDeps(modules: ScalaVersionDependentModuleID*): Def.Setting[Seq[ModuleID]] = - libraryDependencies ++= modules.flatMap(m ⇒ m.modules(scalaVersion.value)) + libraryDependencies ++= modules.flatMap(m => m.modules(scalaVersion.value)) val ScalaVersion = """\d\.\d+\.\d+(?:-(?:M|RC)\d+)?""".r - val nominalScalaVersion: String ⇒ String = { + val nominalScalaVersion: String => String = { // matches: // 2.12.0-M1 // 2.12.0-RC1 // 2.12.0 - case version @ ScalaVersion() ⇒ version + case version @ ScalaVersion() => version // transforms 2.12.0-custom-version to 2.12.0 - case version ⇒ version.takeWhile(_ != '-') + case version => version.takeWhile(_ != '-') } } diff --git a/project/Doc.scala b/project/Doc.scala index 1a55c8b1cb..f951401634 100644 --- a/project/Doc.scala +++ b/project/Doc.scala @@ -56,7 +56,7 @@ object Scaladoc extends AutoPlugin { val curr = dirs.head val (newDirs, files) = curr.listFiles.partition(_.isDirectory) val rest = dirs.tail ++ newDirs - val hasDiagram = files exists { f ⇒ + val hasDiagram = files exists { f => val name = f.getName if (name.endsWith(".html") && !name.startsWith("index-") && !name.equals("index.html") && !name.equals("package.html")) { @@ -66,7 +66,7 @@ object Scaladoc extends AutoPlugin { lines.contains(" throw new IllegalStateException("Scaladoc verification failed for file '" + f + "'", e) } finally source.close() hd } else false diff --git a/project/MiMa.scala b/project/MiMa.scala index d4956ddf14..02af607d2d 100644 --- a/project/MiMa.scala +++ b/project/MiMa.scala @@ -23,7 +23,7 @@ object MiMa extends AutoPlugin { def akkaPreviousArtifacts(projectName: String, organization: String, scalaBinaryVersion: String): Set[sbt.ModuleID] = { val versions: Seq[String] = { val akka24NoStreamVersions = Seq("2.4.0", "2.4.1") - val akka25Versions = (0 to latestPatchOf25).map(patch ⇒ s"2.5.$patch") + val akka25Versions = (0 to latestPatchOf25).map(patch => s"2.5.$patch") val akka24StreamVersions = (2 to 12).map("2.4." + _) val akka25DiscoveryVersions = (19 to latestPatchOf25).map(patch => s"2.5.$patch") val akka24WithScala212 = @@ -41,7 +41,7 @@ object MiMa extends AutoPlugin { ) scalaBinaryVersion match { - case "2.11" ⇒ + case "2.11" => if (akka2519NewArtifacts.contains(projectName)) akka25DiscoveryVersions else if (akka250NewArtifacts.contains(projectName)) akka25Versions @@ -50,7 +50,7 @@ object MiMa extends AutoPlugin { else Seq.empty } ++ akka24StreamVersions ++ akka24WithScala212 ++ akka25Versions - case "2.12" ⇒ + case "2.12" => if (akka2519NewArtifacts.contains(projectName)) akka25DiscoveryVersions else if (akka250NewArtifacts.contains(projectName)) @@ -69,7 +69,7 @@ object MiMa extends AutoPlugin { "akka-distributed-data") // check against all binary compatible artifacts - versions.map { v ⇒ + versions.map { v => val adjustedProjectName = if (akka25PromotedArtifacts(projectName) && v.startsWith("2.4")) projectName + "-experimental" diff --git a/project/MultiNode.scala b/project/MultiNode.scala index 3fb12dbfa6..723cef8ff5 100644 --- a/project/MultiNode.scala +++ b/project/MultiNode.scala @@ -46,10 +46,10 @@ object MultiNode extends AutoPlugin { val MultinodeJvmArgs = "multinode\\.(D|X)(.*)".r val knownPrefix = Set("multnode.", "akka.", "MultiJvm.") val akkaProperties = System.getProperties.stringPropertyNames.asScala.toList.collect { - case MultinodeJvmArgs(a, b) ⇒ + case MultinodeJvmArgs(a, b) => val value = System.getProperty("multinode." + a + b) "-" + a + b + (if (value == "") "" else "=" + value) - case key: String if knownPrefix.exists(pre ⇒ key.startsWith(pre)) ⇒ "-D" + key + "=" + System.getProperty(key) + case key: String if knownPrefix.exists(pre => key.startsWith(pre)) => "-D" + key + "=" + System.getProperty(key) } "-Xmx256m" :: akkaProperties ::: CliOptions.sbtLogNoFormat.ifTrue("-Dakka.test.nocolor=true").toList @@ -106,9 +106,9 @@ object MultiNode extends AutoPlugin { implicit class TestResultOps(val self: TestResult) extends AnyVal { def id: Int = self match { - case TestResult.Passed ⇒ 0 - case TestResult.Failed ⇒ 1 - case TestResult.Error ⇒ 2 + case TestResult.Passed => 0 + case TestResult.Failed => 1 + case TestResult.Error => 2 } } } @@ -123,7 +123,7 @@ object MultiNodeScalaTest extends AutoPlugin { override lazy val projectSettings = Seq( extraOptions in MultiJvm := { val src = (sourceDirectory in MultiJvm).value - (name: String) ⇒ (src ** (name + ".conf")).get.headOption.map("-Dakka.config=" + _.absolutePath).toSeq + (name: String) => (src ** (name + ".conf")).get.headOption.map("-Dakka.config=" + _.absolutePath).toSeq }, scalatestOptions in MultiJvm := { Seq("-C", "org.scalatest.extra.QuietReporter") ++ diff --git a/project/OSGi.scala b/project/OSGi.scala index d6089a2a8d..c05e4cb7db 100644 --- a/project/OSGi.scala +++ b/project/OSGi.scala @@ -73,7 +73,7 @@ object OSGi { "akka.http.$DSL$.coding.*", "akka.http.$DSL$.common.*", "akka.http.$DSL$.marshalling.*", - "akka.http.$DSL$.unmarshalling.*") flatMap { p ⇒ + "akka.http.$DSL$.unmarshalling.*") flatMap { p => Seq(p.replace("$DSL$", "scaladsl"), p.replace("$DSL$", "javadsl")) }, imports = Seq( diff --git a/project/ParadoxSupport.scala b/project/ParadoxSupport.scala index 83353ab1f8..2ba0869505 100644 --- a/project/ParadoxSupport.scala +++ b/project/ParadoxSupport.scala @@ -29,10 +29,10 @@ object ParadoxSupport { .scan() val allClasses = scanner.getAllClasses.getNames.asScala.toVector Def.task { Seq( - { context: Writer.Context ⇒ - new SignatureDirective(context.location.tree.label, context.properties, msg ⇒ log.warn(msg)) + { context: Writer.Context => + new SignatureDirective(context.location.tree.label, context.properties, msg => log.warn(msg)) }, - { _: Writer.Context ⇒ new UnidocDirective(allClasses) } + { _: Writer.Context => new UnidocDirective(allClasses) } )} }.value ) diff --git a/project/ProjectFileIgnoreSupport.scala b/project/ProjectFileIgnoreSupport.scala index 988db7bf1d..b915f064ee 100644 --- a/project/ProjectFileIgnoreSupport.scala +++ b/project/ProjectFileIgnoreSupport.scala @@ -68,22 +68,22 @@ class ProjectFileIgnoreSupport(ignoreConfigFile: File, descriptor: String) { def getPackageName0(fileType: String): String = { import java.io.{File => JFile} fileName.split(JFile.separatorChar) - .dropWhile(part ⇒ part != fileType) + .dropWhile(part => part != fileType) .drop(1) .dropRight(1) .mkString(".") } fileName.split('.').lastOption match { - case Some(fileType) ⇒ + case Some(fileType) => fileType match { - case "java" ⇒ + case "java" => Option(getPackageName0("java")) - case "scala" ⇒ + case "scala" => Option(getPackageName0("scala")) - case _ ⇒ None + case _ => None } - case None ⇒ None + case None => None } } } diff --git a/project/Protobuf.scala b/project/Protobuf.scala index 2de9db7395..7e17f174a9 100644 --- a/project/Protobuf.scala +++ b/project/Protobuf.scala @@ -46,27 +46,27 @@ object Protobuf { val cache = targets / "protoc" / "cache" (sourceDirs zip targetDirs) map { - case (src, dst) ⇒ + case (src, dst) => val relative = src.relativeTo(sources).getOrElse(throw new Exception(s"path $src is not a in source tree $sources")).toString val tmp = targets / "protoc" / relative IO.delete(tmp) generate(cmd, src, tmp, log, importPath.value) - transformDirectory(tmp, dst, _ ⇒ true, transformFile(_.replace("com.google.protobuf", "akka.protobuf")), cache, log) + transformDirectory(tmp, dst, _ => true, transformFile(_.replace("com.google.protobuf", "akka.protobuf")), cache, log) } } }) - private def callProtoc[T](protoc: String, args: Seq[String], log: Logger, thunk: (ProcessBuilder, Logger) ⇒ T): T = + private def callProtoc[T](protoc: String, args: Seq[String], log: Logger, thunk: (ProcessBuilder, Logger) => T): T = try { val proc = Process(protoc, args) thunk(proc, log) } catch { - case e: Exception ⇒ + case e: Exception => throw new RuntimeException("error while executing '%s' with args: %s" format (protoc, args.mkString(" ")), e) } private def checkProtocVersion(protoc: String, protocVersion: String, log: Logger): Unit = { - val res = callProtoc(protoc, Seq("--version"), log, { (p, l) ⇒ p !! l }) + val res = callProtoc(protoc, Seq("--version"), log, { (p, l) => p !! l }) val version = res.split(" ").last.trim if (version != protocVersion) { sys.error("Wrong protoc version! Expected %s but got %s" format (protocVersion, version)) @@ -82,7 +82,7 @@ object Protobuf { targetDir.mkdirs() log.info("Generating %d protobuf files from %s to %s".format(protoFiles.size, srcDir, targetDir)) - protoFiles.foreach { proto ⇒ log.info("Compiling %s" format proto) } + protoFiles.foreach { proto => log.info("Compiling %s" format proto) } val protoPathArg = importPath match { case None => Nil @@ -99,15 +99,15 @@ object Protobuf { /** * Create a transformed version of all files in a directory, given a predicate and a transform function for each file. From sbt-site */ - private def transformDirectory(sourceDir: File, targetDir: File, transformable: File ⇒ Boolean, transform: (File, File) ⇒ Unit, cache: File, log: Logger): File = { - val runTransform = FileFunction.cached(CacheStoreFactory(cache), FilesInfo.hash, FilesInfo.exists) { (in: ChangeReport[File], out: ChangeReport[File]) ⇒ + private def transformDirectory(sourceDir: File, targetDir: File, transformable: File => Boolean, transform: (File, File) => Unit, cache: File, log: Logger): File = { + val runTransform = FileFunction.cached(CacheStoreFactory(cache), FilesInfo.hash, FilesInfo.exists) { (in: ChangeReport[File], out: ChangeReport[File]) => val map = Path.rebase(sourceDir, targetDir) if (in.removed.nonEmpty || in.modified.nonEmpty) { log.info("Preprocessing directory %s..." format sourceDir) - for (source ← in.removed; target ← map(source)) { + for (source <- in.removed; target <- map(source)) { IO delete target } - val updated = for (source ← in.modified; target ← map(source)) yield { + val updated = for (source <- in.modified; target <- map(source)) yield { if (source.isFile) { if (transformable(source)) transform(source, target) else IO.copyFile(source, target) @@ -126,11 +126,11 @@ object Protobuf { /** * Transform a file, line by line. */ - def transformFile(transform: String ⇒ String)(source: File, target: File): Unit = { - IO.reader(source) { reader ⇒ - IO.writer(target, "", IO.defaultCharset) { writer ⇒ + def transformFile(transform: String => String)(source: File, target: File): Unit = { + IO.reader(source) { reader => + IO.writer(target, "", IO.defaultCharset) { writer => val pw = new PrintWriter(writer) - IO.foreachLine(reader) { line ⇒ pw.println(transform(line)) } + IO.foreachLine(reader) { line => pw.println(transform(line)) } } } } diff --git a/project/Publish.scala b/project/Publish.scala index 3f7ae2f272..2e559cd8fb 100644 --- a/project/Publish.scala +++ b/project/Publish.scala @@ -23,7 +23,7 @@ object Publish extends AutoPlugin { organizationName := "Lightbend Inc.", organizationHomepage := Some(url("http://www.lightbend.com")), publishMavenStyle := true, - pomIncludeRepository := { x ⇒ false }, + pomIncludeRepository := { x => false }, defaultPublishTo := crossTarget.value / "repository") def akkaPomExtra = { @@ -43,7 +43,7 @@ object Publish extends AutoPlugin { } private def sonatypeRepo(version: String): Option[Resolver] = - Option(sys.props("publish.maven.central")) filter (_.toLowerCase == "true") map { _ ⇒ + Option(sys.props("publish.maven.central")) filter (_.toLowerCase == "true") map { _ => val nexus = "https://oss.sonatype.org/" if (version endsWith "-SNAPSHOT") "snapshots" at nexus + "content/repositories/snapshots" else "releases" at nexus + "service/local/staging/deploy/maven2" @@ -53,7 +53,7 @@ object Publish extends AutoPlugin { Some(Resolver.file("Default Local Repository", repository)) private def akkaCredentials: Seq[Credentials] = - Option(System.getProperty("akka.publish.credentials", null)).map(f ⇒ Credentials(new File(f))).toSeq + Option(System.getProperty("akka.publish.credentials", null)).map(f => Credentials(new File(f))).toSeq } /** @@ -87,7 +87,7 @@ object DeployRsync extends AutoPlugin { deployRsync := { val (_, host) = (Space ~ StringBasic).parsed deployRsyncArtifact.value.foreach { - case (from, to) ⇒ s"rsync -rvz $from/ $host:$to"! + case (from, to) => s"rsync -rvz $from/ $host:$to"! } } ) diff --git a/project/Release.scala b/project/Release.scala index fa6e04308f..ebb681aa35 100644 --- a/project/Release.scala +++ b/project/Release.scala @@ -20,7 +20,7 @@ object Release extends ParadoxKeys { lazy val commandSettings = Seq( commands ++= Seq(buildReleaseCommand, buildDocsCommand)) - def buildReleaseCommand = Command.command("buildRelease") { state ⇒ + def buildReleaseCommand = Command.command("buildRelease") { state => val extracted = Project.extract(state) val release = extracted.get(releaseDirectory) val releaseVersion = extracted.get(version) diff --git a/project/StreamOperatorsIndexGenerator.scala b/project/StreamOperatorsIndexGenerator.scala index cd63093a5f..6117953594 100644 --- a/project/StreamOperatorsIndexGenerator.scala +++ b/project/StreamOperatorsIndexGenerator.scala @@ -107,10 +107,10 @@ object StreamOperatorsIndexGenerator extends AutoPlugin { "foldAsync", "newOnCompleteStage" ), - "ActorSink" → Seq( + "ActorSink" -> Seq( "actorRefWithAck" ), - "ActorSource" → Seq( + "ActorSource" -> Seq( "actorRef" ) ) @@ -125,7 +125,7 @@ object StreamOperatorsIndexGenerator extends AutoPlugin { def isPending(element: String, opName: String) = pendingTestCases.get(element).exists(_.contains(opName)) - def generateAlphabeticalIndex(dir: SettingKey[File], locate: File ⇒ File) = Def.task[Seq[File]] { + def generateAlphabeticalIndex(dir: SettingKey[File], locate: File => File) = Def.task[Seq[File]] { val file = locate(dir.value) val defs = @@ -160,16 +160,16 @@ object StreamOperatorsIndexGenerator extends AutoPlugin { "akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorFlow.scala", "akka-stream-typed/src/main/scala/akka/stream/typed/scaladsl/ActorSink.scala", "akka-stream-typed/src/main/scala/akka/stream/typed/javadsl/ActorSink.scala", - ).flatMap{ f ⇒ + ).flatMap{ f => val slashesNr = f.count(_ == '/') val element = f.split("/")(slashesNr).split("\\.")(0) IO.read(new File(f)).split("\n") .map(_.trim).filter(_.startsWith("def ")) - .map(_.drop(4).takeWhile(c ⇒ c != '[' && c != '(' && c != ':')) + .map(_.drop(4).takeWhile(c => c != '[' && c != '(' && c != ':')) .filter(op => !isPending(element, op)) .filter(op => !ignore.contains(op)) .map(_.replaceAll("Mat$", "")) - .map(method ⇒ (element, method)) + .map(method => (element, method)) } val sourceAndFlow = defs.collect { case ("Source", method) => method } intersect defs.collect { case ("Flow", method) => method } @@ -233,7 +233,7 @@ object StreamOperatorsIndexGenerator extends AutoPlugin { require(categoryLinkId == categoryId(categoryName), s"category id $categoryLinkId in $file") (description, categoryName) } catch { - case NonFatal(ex) ⇒ + case NonFatal(ex) => throw new RuntimeException(s"Unable to extract details from $file", ex) } diff --git a/project/TestExtras.scala b/project/TestExtras.scala index 886c5ff92b..5f084b1f23 100644 --- a/project/TestExtras.scala +++ b/project/TestExtras.scala @@ -34,7 +34,7 @@ object TestExtras { onlyTestTags := Params.testTagsOnly, // add filters for tests excluded by name - testOptions in Test ++= excludeTestNames.value.toSeq.map(exclude ⇒ Tests.Filter(test ⇒ !test.contains(exclude))), + testOptions in Test ++= excludeTestNames.value.toSeq.map(exclude => Tests.Filter(test => !test.contains(exclude))), // add arguments for tests excluded by tag testOptions in Test ++= { diff --git a/project/TimeStampede.scala b/project/TimeStampede.scala index aee3e4190d..e6d829acb3 100644 --- a/project/TimeStampede.scala +++ b/project/TimeStampede.scala @@ -21,7 +21,7 @@ object TimeStampede extends AutoPlugin { final val Snapshot = "-SNAPSHOT" - def stampVersion = Command.command("stampVersion") { state ⇒ + def stampVersion = Command.command("stampVersion") { state => val extracted = Project.extract(state) extracted.appendWithSession(List(version in ThisBuild ~= stamp), state) } diff --git a/project/VersionGenerator.scala b/project/VersionGenerator.scala index 2e3b3002b6..c52a86bebe 100644 --- a/project/VersionGenerator.scala +++ b/project/VersionGenerator.scala @@ -24,7 +24,7 @@ object VersionGenerator { |} |"""))) - def generateVersion(dir: SettingKey[File], locate: File ⇒ File, template: String) = Def.task[Seq[File]] { + def generateVersion(dir: SettingKey[File], locate: File => File, template: String) = Def.task[Seq[File]] { val file = locate(dir.value) val content = template.stripMargin.format(version.value) if (!file.exists || IO.read(file) != content) IO.write(file, content)